Skip to main content

waft_material/
text_form_field.rs

1//! Flutter counterpart: material_ui's `text_form_field.dart`.
2//!
3//! [`TextFormField`] is a `FormField<String>` leaf: its widget carries the form field's
4//! [`FormFieldData`] and the arguments Dart's constructor captures in the builder closure, kept
5//! as the [`TextField`] the builder builds; [`TextFormField::build_field`] is that closure.
6#![allow(deprecated)]
7
8use std::any::TypeId;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use waft_embedder::{
13    BoxHeightStyle, BoxWidthStyle, Brightness, Clip, Color, Locale, Radius, SmartDashesType,
14    SmartQuotesType, TextCapitalization, TextEditingValue, TextInputAction, TextInputType,
15};
16use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref, ValueChanged};
17use waft_gestures::{DragStartBehavior, GestureTapCallback, PointerDownEvent, PointerUpEvent};
18use waft_painting::{
19    AnyTextStyle, EdgeInsets, StrutStyle, TextAlign, TextAlignVertical, TextDirection,
20};
21use waft_services::{
22    MaxLengthEnforcement, MouseCursorRef, RestorationBucket, TextInputFormatterRef,
23};
24use waft_widgets::{
25    AnyFormFieldState, AutovalidateMode, BuildContext, ContentInsertionConfiguration, EditableText,
26    EditableTextContextMenuBuilder, EditableTextState, FocusNodeRef, FormFieldData, FormFieldLeaf,
27    FormFieldState, FormFieldStateData, FormFieldStateLeaf, IntoWidget, KeyRef,
28    RestorableListenable, RestorableProperty, RestorableTextEditingController, RestorationMixin,
29    RestorationMixinData, ScrollControllerRef, ScrollPhysicsRef, SpellCheckConfiguration, State,
30    StateData, StatefulWidget, SystemContextMenu, TextEditingControllerRef,
31    TextMagnifierConfiguration, TextSelectionControls, ToolbarOptions, UndoHistoryController,
32    UnmanagedRestorationScope, WidgetRef,
33};
34
35use crate::adaptive_text_selection_toolbar::AdaptiveTextSelectionToolbar;
36use crate::input_decorator::{InputDecoration, InputDecorationTheme};
37use crate::material_state::MaterialStatesController;
38use crate::text_field::TextField;
39
40/// A [`FormField`](waft_widgets::FormField) that contains a [`TextField`].
41///
42/// This is a convenience widget that wraps a [`TextField`] widget in a `FormField`.
43///
44/// A `Form` ancestor is not required. The `Form` allows one to save, reset, or validate
45/// multiple fields at once. To use without a `Form`, pass a `GlobalKey` to the constructor and
46/// use `GlobalKey::current_state` to save or reset the form field.
47///
48/// When a [`controller`](Self::controller) is specified, its `TextEditingController::text`
49/// defines the [`initial_value`](FormFieldData::initial_value). If this `FormField` is part of
50/// a scrolling container that lazily constructs its children, like a `ListView` or a
51/// `CustomScrollView`, then a [`controller`](Self::controller) should be specified. The
52/// controller's lifetime should be managed by a stateful widget ancestor of the scrolling
53/// container.
54///
55/// If a [`controller`](Self::controller) is not specified, [`initial_value`](Self::initial_value)
56/// can be used to give the automatically generated controller an initial value.
57///
58/// For a documentation about the various parameters, see the [`TextField`] class and
59/// `TextField::new`, the constructor.
60pub struct TextFormField {
61    form_field: FormFieldData<String>,
62    /// {@macro flutter.widgets.editableText.groupId}
63    pub group_id: TypeId,
64    /// Controls the text being edited.
65    ///
66    /// If null, this widget will create its own `TextEditingController` and initialize its
67    /// `TextEditingController::text` with [`initial_value`](FormFieldData::initial_value).
68    pub controller: Option<TextEditingControllerRef>,
69    /// Called when the user initiates a change to the TextField's value: when they have
70    /// inserted or deleted text or reset the form.
71    pub on_changed: Option<ValueChanged<String>>,
72    /// Dart's constructor argument `initialValue`, which fills the form field's
73    /// [`initial_value`](FormFieldData::initial_value) when there is no
74    /// [`controller`](Self::controller).
75    initial_value: Option<String>,
76    /// The constructor's other arguments, which Dart's builder closure captures: the
77    /// [`TextField`] it builds before the state fills the controller, the decoration, the
78    /// `on_changed` handler and `enabled`.
79    text_field: TextField,
80}
81
82impl TextFormField {
83    /// Creates a [`FormField`](waft_widgets::FormField) that contains a [`TextField`].
84    pub fn new() -> TextFormField {
85        let mut form_field = FormFieldData::new(Rc::new(TextFormField::build_field));
86        form_field.initial_value = Some(String::new());
87        form_field.enabled = true;
88        form_field.autovalidate_mode = AutovalidateMode::Disabled;
89        TextFormField {
90            form_field,
91            group_id: TypeId::of::<EditableText>(),
92            controller: None,
93            on_changed: None,
94            initial_value: None,
95            text_field: TextField::new()
96                .autocorrect(true)
97                .context_menu_builder(Some(Rc::new(Self::default_context_menu_builder))),
98        }
99    }
100
101    /// Dart `TextFormField(key:)`.
102    pub fn key(mut self, key: KeyRef) -> TextFormField {
103        self.form_field.key = Some(key);
104        self
105    }
106
107    /// Dart `TextFormField(groupId:)`.
108    pub fn group_id(mut self, group_id: TypeId) -> TextFormField {
109        self.group_id = group_id;
110        self
111    }
112
113    /// Dart `TextFormField(controller:)`.
114    pub fn controller(mut self, controller: TextEditingControllerRef) -> TextFormField {
115        self.controller = Some(controller);
116        self.form_field.initial_value = self.form_field_initial_value();
117        self
118    }
119
120    /// Dart `TextFormField(initialValue:)`.
121    pub fn initial_value(mut self, initial_value: impl Into<String>) -> TextFormField {
122        self.initial_value = Some(initial_value.into());
123        self.form_field.initial_value = self.form_field_initial_value();
124        self
125    }
126
127    /// Dart `TextFormField(focusNode:)`.
128    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> TextFormField {
129        self.text_field = self.text_field.focus_node(focus_node);
130        self
131    }
132
133    /// Dart `TextFormField(forceErrorText:)`.
134    pub fn force_error_text(mut self, force_error_text: impl Into<String>) -> TextFormField {
135        self.form_field.force_error_text = Some(force_error_text.into());
136        self
137    }
138
139    /// Dart `TextFormField(decoration:)`.
140    pub fn decoration(mut self, decoration: Option<InputDecoration>) -> TextFormField {
141        self.text_field = self.text_field.decoration(decoration);
142        self.form_field.enabled = self.effective_enabled();
143        self
144    }
145
146    /// Dart `TextFormField(keyboardType:)`.
147    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> TextFormField {
148        self.text_field = self.text_field.keyboard_type(keyboard_type);
149        self
150    }
151
152    /// Dart `TextFormField(textCapitalization:)`.
153    pub fn text_capitalization(mut self, text_capitalization: TextCapitalization) -> TextFormField {
154        self.text_field = self.text_field.text_capitalization(text_capitalization);
155        self
156    }
157
158    /// Dart `TextFormField(textInputAction:)`.
159    pub fn text_input_action(mut self, text_input_action: TextInputAction) -> TextFormField {
160        self.text_field = self.text_field.text_input_action(text_input_action);
161        self
162    }
163
164    /// Dart `TextFormField(style:)`.
165    pub fn style(mut self, style: impl Into<AnyTextStyle>) -> TextFormField {
166        self.text_field = self.text_field.style(style);
167        self
168    }
169
170    /// Dart `TextFormField(strutStyle:)`.
171    pub fn strut_style(mut self, strut_style: StrutStyle) -> TextFormField {
172        self.text_field = self.text_field.strut_style(strut_style);
173        self
174    }
175
176    /// Dart `TextFormField(textDirection:)`.
177    pub fn text_direction(mut self, text_direction: TextDirection) -> TextFormField {
178        self.text_field = self.text_field.text_direction(text_direction);
179        self
180    }
181
182    /// Dart `TextFormField(textAlign:)`.
183    pub fn text_align(mut self, text_align: TextAlign) -> TextFormField {
184        self.text_field = self.text_field.text_align(text_align);
185        self
186    }
187
188    /// Dart `TextFormField(textAlignVertical:)`.
189    pub fn text_align_vertical(mut self, text_align_vertical: TextAlignVertical) -> TextFormField {
190        self.text_field = self.text_field.text_align_vertical(text_align_vertical);
191        self
192    }
193
194    /// Dart `TextFormField(autofocus:)`.
195    pub fn autofocus(mut self, autofocus: bool) -> TextFormField {
196        self.text_field = self.text_field.autofocus(autofocus);
197        self
198    }
199
200    /// Dart `TextFormField(readOnly:)`.
201    pub fn read_only(mut self, read_only: bool) -> TextFormField {
202        self.text_field = self.text_field.read_only(read_only);
203        self
204    }
205
206    /// Dart `TextFormField(toolbarOptions:)`.
207    #[deprecated(note = "Use `context_menu_builder` instead.")]
208    pub fn toolbar_options(mut self, toolbar_options: ToolbarOptions) -> TextFormField {
209        self.text_field = self.text_field.toolbar_options(toolbar_options);
210        self
211    }
212
213    /// Dart `TextFormField(showCursor:)`.
214    pub fn show_cursor(mut self, show_cursor: bool) -> TextFormField {
215        self.text_field = self.text_field.show_cursor(show_cursor);
216        self
217    }
218
219    /// Dart `TextFormField(obscuringCharacter:)`.
220    pub fn obscuring_character(mut self, obscuring_character: impl Into<String>) -> TextFormField {
221        self.text_field = self.text_field.obscuring_character(obscuring_character);
222        self
223    }
224
225    /// Dart `TextFormField(obscureText:)`.
226    pub fn obscure_text(mut self, obscure_text: bool) -> TextFormField {
227        self.text_field = self.text_field.obscure_text(obscure_text);
228        self
229    }
230
231    /// Dart `TextFormField(autocorrect:)`.
232    pub fn autocorrect(mut self, autocorrect: bool) -> TextFormField {
233        self.text_field = self.text_field.autocorrect(autocorrect);
234        self
235    }
236
237    /// Dart `TextFormField(smartDashesType:)`.
238    pub fn smart_dashes_type(mut self, smart_dashes_type: SmartDashesType) -> TextFormField {
239        self.text_field = self.text_field.smart_dashes_type(smart_dashes_type);
240        self
241    }
242
243    /// Dart `TextFormField(smartQuotesType:)`.
244    pub fn smart_quotes_type(mut self, smart_quotes_type: SmartQuotesType) -> TextFormField {
245        self.text_field = self.text_field.smart_quotes_type(smart_quotes_type);
246        self
247    }
248
249    /// Dart `TextFormField(enableSuggestions:)`.
250    pub fn enable_suggestions(mut self, enable_suggestions: bool) -> TextFormField {
251        self.text_field = self.text_field.enable_suggestions(enable_suggestions);
252        self
253    }
254
255    /// Dart `TextFormField(maxLengthEnforcement:)`.
256    pub fn max_length_enforcement(
257        mut self,
258        max_length_enforcement: MaxLengthEnforcement,
259    ) -> TextFormField {
260        self.text_field = self
261            .text_field
262            .max_length_enforcement(max_length_enforcement);
263        self
264    }
265
266    /// Dart `TextFormField(maxLines:)`.
267    pub fn max_lines(mut self, max_lines: Option<i32>) -> TextFormField {
268        self.text_field = self.text_field.max_lines(max_lines);
269        self
270    }
271
272    /// Dart `TextFormField(minLines:)`.
273    pub fn min_lines(mut self, min_lines: i32) -> TextFormField {
274        self.text_field = self.text_field.min_lines(min_lines);
275        self
276    }
277
278    /// Dart `TextFormField(expands:)`.
279    pub fn expands(mut self, expands: bool) -> TextFormField {
280        self.text_field = self.text_field.expands(expands);
281        self
282    }
283
284    /// Dart `TextFormField(maxLength:)`.
285    pub fn max_length(mut self, max_length: i32) -> TextFormField {
286        self.text_field = self.text_field.max_length(max_length);
287        self
288    }
289
290    /// Dart `TextFormField(onChanged:)`.
291    pub fn on_changed(mut self, on_changed: impl Fn(&mut App, String) + 'static) -> TextFormField {
292        self.on_changed = Some(Rc::new(on_changed));
293        self
294    }
295
296    /// Dart `TextFormField(onTap:)`.
297    pub fn on_tap(mut self, on_tap: GestureTapCallback) -> TextFormField {
298        self.text_field = self.text_field.on_tap(on_tap);
299        self
300    }
301
302    /// Dart `TextFormField(onTapAlwaysCalled:)`.
303    pub fn on_tap_always_called(mut self, on_tap_always_called: bool) -> TextFormField {
304        self.text_field = self.text_field.on_tap_always_called(on_tap_always_called);
305        self
306    }
307
308    /// Dart `TextFormField(onTapOutside:)`.
309    pub fn on_tap_outside(
310        mut self,
311        on_tap_outside: impl Fn(&mut App, PointerDownEvent) + 'static,
312    ) -> TextFormField {
313        self.text_field = self.text_field.on_tap_outside(on_tap_outside);
314        self
315    }
316
317    /// Dart `TextFormField(onTapUpOutside:)`.
318    pub fn on_tap_up_outside(
319        mut self,
320        on_tap_up_outside: impl Fn(&mut App, PointerUpEvent) + 'static,
321    ) -> TextFormField {
322        self.text_field = self.text_field.on_tap_up_outside(on_tap_up_outside);
323        self
324    }
325
326    /// Dart `TextFormField(onEditingComplete:)`.
327    pub fn on_editing_complete(
328        mut self,
329        on_editing_complete: impl Fn(&mut App) + 'static,
330    ) -> TextFormField {
331        self.text_field = self.text_field.on_editing_complete(on_editing_complete);
332        self
333    }
334
335    /// Dart `TextFormField(onFieldSubmitted:)`.
336    pub fn on_field_submitted(
337        mut self,
338        on_field_submitted: impl Fn(&mut App, String) + 'static,
339    ) -> TextFormField {
340        self.text_field = self.text_field.on_submitted(on_field_submitted);
341        self
342    }
343
344    /// Dart `TextFormField(onSaved:)`.
345    pub fn on_saved(
346        mut self,
347        on_saved: impl Fn(&mut App, Option<String>) + 'static,
348    ) -> TextFormField {
349        self.form_field.on_saved = Some(Rc::new(on_saved));
350        self
351    }
352
353    /// Dart `TextFormField(validator:)`.
354    pub fn validator(
355        mut self,
356        validator: impl Fn(&mut App, Option<&String>) -> Option<String> + 'static,
357    ) -> TextFormField {
358        self.form_field.validator = Some(Rc::new(validator));
359        self
360    }
361
362    /// Dart `TextFormField(errorBuilder:)`.
363    pub fn error_builder(
364        mut self,
365        error_builder: impl Fn(&mut App, BuildContext, String) -> WidgetRef + 'static,
366    ) -> TextFormField {
367        self.form_field.error_builder = Some(Rc::new(error_builder));
368        self
369    }
370
371    /// Dart `TextFormField(inputFormatters:)`.
372    pub fn input_formatters(
373        mut self,
374        input_formatters: Vec<TextInputFormatterRef>,
375    ) -> TextFormField {
376        self.text_field = self.text_field.input_formatters(input_formatters);
377        self
378    }
379
380    /// Dart `TextFormField(enabled:)`.
381    pub fn enabled(mut self, enabled: bool) -> TextFormField {
382        self.text_field = self.text_field.enabled(enabled);
383        self.form_field.enabled = self.effective_enabled();
384        self
385    }
386
387    /// Dart `TextFormField(ignorePointers:)`.
388    pub fn ignore_pointers(mut self, ignore_pointers: bool) -> TextFormField {
389        self.text_field = self.text_field.ignore_pointers(ignore_pointers);
390        self
391    }
392
393    /// Dart `TextFormField(cursorWidth:)`.
394    pub fn cursor_width(mut self, cursor_width: f64) -> TextFormField {
395        self.text_field = self.text_field.cursor_width(cursor_width);
396        self
397    }
398
399    /// Dart `TextFormField(cursorHeight:)`.
400    pub fn cursor_height(mut self, cursor_height: f64) -> TextFormField {
401        self.text_field = self.text_field.cursor_height(cursor_height);
402        self
403    }
404
405    /// Dart `TextFormField(cursorRadius:)`.
406    pub fn cursor_radius(mut self, cursor_radius: Radius) -> TextFormField {
407        self.text_field = self.text_field.cursor_radius(cursor_radius);
408        self
409    }
410
411    /// Dart `TextFormField(cursorColor:)`.
412    pub fn cursor_color(mut self, cursor_color: Color) -> TextFormField {
413        self.text_field = self.text_field.cursor_color(cursor_color);
414        self
415    }
416
417    /// Dart `TextFormField(cursorErrorColor:)`.
418    pub fn cursor_error_color(mut self, cursor_error_color: Color) -> TextFormField {
419        self.text_field = self.text_field.cursor_error_color(cursor_error_color);
420        self
421    }
422
423    /// Dart `TextFormField(keyboardAppearance:)`.
424    pub fn keyboard_appearance(mut self, keyboard_appearance: Brightness) -> TextFormField {
425        self.text_field = self.text_field.keyboard_appearance(keyboard_appearance);
426        self
427    }
428
429    /// Dart `TextFormField(scrollPadding:)`.
430    pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> TextFormField {
431        self.text_field = self.text_field.scroll_padding(scroll_padding);
432        self
433    }
434
435    /// Dart `TextFormField(enableInteractiveSelection:)`.
436    pub fn enable_interactive_selection(
437        mut self,
438        enable_interactive_selection: bool,
439    ) -> TextFormField {
440        self.text_field = self
441            .text_field
442            .enable_interactive_selection(enable_interactive_selection);
443        self
444    }
445
446    /// Dart `TextFormField(selectAllOnFocus:)`.
447    pub fn select_all_on_focus(mut self, select_all_on_focus: bool) -> TextFormField {
448        self.text_field = self.text_field.select_all_on_focus(select_all_on_focus);
449        self
450    }
451
452    /// Dart `TextFormField(selectionControls:)`.
453    pub fn selection_controls(
454        mut self,
455        selection_controls: Rc<dyn TextSelectionControls>,
456    ) -> TextFormField {
457        self.text_field = self.text_field.selection_controls(selection_controls);
458        self
459    }
460
461    /// Dart `TextFormField(buildCounter:)`.
462    pub fn build_counter(
463        mut self,
464        build_counter: impl Fn(&mut App, BuildContext, i32, Option<i32>, bool) -> Option<WidgetRef>
465        + 'static,
466    ) -> TextFormField {
467        self.text_field = self.text_field.build_counter(build_counter);
468        self
469    }
470
471    /// Dart `TextFormField(scrollPhysics:)`.
472    pub fn scroll_physics(mut self, scroll_physics: ScrollPhysicsRef) -> TextFormField {
473        self.text_field = self.text_field.scroll_physics(scroll_physics);
474        self
475    }
476
477    /// Dart `TextFormField(autofillHints:)`.
478    pub fn autofill_hints(mut self, autofill_hints: Vec<String>) -> TextFormField {
479        self.text_field = self.text_field.autofill_hints(autofill_hints);
480        self
481    }
482
483    /// Dart `TextFormField(autovalidateMode:)`.
484    pub fn autovalidate_mode(mut self, autovalidate_mode: AutovalidateMode) -> TextFormField {
485        self.form_field.autovalidate_mode = autovalidate_mode;
486        self
487    }
488
489    /// Dart `TextFormField(scrollController:)`.
490    pub fn scroll_controller(mut self, scroll_controller: ScrollControllerRef) -> TextFormField {
491        self.text_field = self.text_field.scroll_controller(scroll_controller);
492        self
493    }
494
495    /// Dart `TextFormField(restorationId:)`.
496    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> TextFormField {
497        let restoration_id = restoration_id.into();
498        self.form_field.restoration_id = Some(restoration_id.clone());
499        self.text_field = self.text_field.restoration_id(restoration_id);
500        self
501    }
502
503    /// Dart `TextFormField(enableIMEPersonalizedLearning:)`.
504    pub fn enable_ime_personalized_learning(
505        mut self,
506        enable_ime_personalized_learning: bool,
507    ) -> TextFormField {
508        self.text_field = self
509            .text_field
510            .enable_ime_personalized_learning(enable_ime_personalized_learning);
511        self
512    }
513
514    /// Dart `TextFormField(enableInlinePrediction:)`.
515    pub fn enable_inline_prediction(mut self, enable_inline_prediction: bool) -> TextFormField {
516        self.text_field = self
517            .text_field
518            .enable_inline_prediction(enable_inline_prediction);
519        self
520    }
521
522    /// Dart `TextFormField(mouseCursor:)`.
523    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> TextFormField {
524        self.text_field = self.text_field.mouse_cursor(mouse_cursor);
525        self
526    }
527
528    /// Dart `TextFormField(contextMenuBuilder:)`.
529    pub fn context_menu_builder(
530        mut self,
531        context_menu_builder: Option<EditableTextContextMenuBuilder>,
532    ) -> TextFormField {
533        self.text_field = self.text_field.context_menu_builder(context_menu_builder);
534        self
535    }
536
537    /// Dart `TextFormField(spellCheckConfiguration:)`.
538    pub fn spell_check_configuration(
539        mut self,
540        spell_check_configuration: SpellCheckConfiguration,
541    ) -> TextFormField {
542        self.text_field = self
543            .text_field
544            .spell_check_configuration(spell_check_configuration);
545        self
546    }
547
548    /// Dart `TextFormField(magnifierConfiguration:)`.
549    pub fn magnifier_configuration(
550        mut self,
551        magnifier_configuration: TextMagnifierConfiguration,
552    ) -> TextFormField {
553        self.text_field = self
554            .text_field
555            .magnifier_configuration(magnifier_configuration);
556        self
557    }
558
559    /// Dart `TextFormField(undoController:)`.
560    pub fn undo_controller(mut self, undo_controller: Ref<UndoHistoryController>) -> TextFormField {
561        self.text_field = self.text_field.undo_controller(undo_controller);
562        self
563    }
564
565    /// Dart `TextFormField(onAppPrivateCommand:)`.
566    pub fn on_app_private_command(
567        mut self,
568        on_app_private_command: impl Fn(&mut App, &str) + 'static,
569    ) -> TextFormField {
570        self.text_field = self
571            .text_field
572            .on_app_private_command(on_app_private_command);
573        self
574    }
575
576    /// Dart `TextFormField(cursorOpacityAnimates:)`.
577    pub fn cursor_opacity_animates(mut self, cursor_opacity_animates: bool) -> TextFormField {
578        self.text_field = self
579            .text_field
580            .cursor_opacity_animates(cursor_opacity_animates);
581        self
582    }
583
584    /// Dart `TextFormField(selectionHeightStyle:)`.
585    pub fn selection_height_style(
586        mut self,
587        selection_height_style: BoxHeightStyle,
588    ) -> TextFormField {
589        self.text_field = self
590            .text_field
591            .selection_height_style(selection_height_style);
592        self
593    }
594
595    /// Dart `TextFormField(selectionWidthStyle:)`.
596    pub fn selection_width_style(mut self, selection_width_style: BoxWidthStyle) -> TextFormField {
597        self.text_field = self.text_field.selection_width_style(selection_width_style);
598        self
599    }
600
601    /// Dart `TextFormField(dragStartBehavior:)`.
602    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> TextFormField {
603        self.text_field = self.text_field.drag_start_behavior(drag_start_behavior);
604        self
605    }
606
607    /// Dart `TextFormField(contentInsertionConfiguration:)`.
608    pub fn content_insertion_configuration(
609        mut self,
610        content_insertion_configuration: ContentInsertionConfiguration,
611    ) -> TextFormField {
612        self.text_field = self
613            .text_field
614            .content_insertion_configuration(content_insertion_configuration);
615        self
616    }
617
618    /// Dart `TextFormField(statesController:)`.
619    pub fn states_controller(
620        mut self,
621        states_controller: Ref<MaterialStatesController>,
622    ) -> TextFormField {
623        self.text_field = self.text_field.states_controller(states_controller);
624        self
625    }
626
627    /// Dart `TextFormField(clipBehavior:)`.
628    pub fn clip_behavior(mut self, clip_behavior: Clip) -> TextFormField {
629        self.text_field = self.text_field.clip_behavior(clip_behavior);
630        self
631    }
632
633    /// Dart `TextFormField(scribbleEnabled:)`.
634    #[deprecated(note = "Use `stylus_handwriting_enabled` instead.")]
635    pub fn scribble_enabled(mut self, scribble_enabled: bool) -> TextFormField {
636        self.text_field = self.text_field.scribble_enabled(scribble_enabled);
637        self
638    }
639
640    /// Dart `TextFormField(stylusHandwritingEnabled:)`.
641    pub fn stylus_handwriting_enabled(mut self, stylus_handwriting_enabled: bool) -> TextFormField {
642        self.text_field = self
643            .text_field
644            .stylus_handwriting_enabled(stylus_handwriting_enabled);
645        self
646    }
647
648    /// Dart `TextFormField(canRequestFocus:)`.
649    pub fn can_request_focus(mut self, can_request_focus: bool) -> TextFormField {
650        self.text_field = self.text_field.can_request_focus(can_request_focus);
651        self
652    }
653
654    /// Dart `TextFormField(hintLocales:)`.
655    pub fn hint_locales(mut self, hint_locales: Vec<Locale>) -> TextFormField {
656        self.text_field = self.text_field.hint_locales(hint_locales);
657        self
658    }
659
660    fn default_context_menu_builder(
661        app: &mut App,
662        _context: BuildContext,
663        editable_text_state: Handle<EditableTextState>,
664    ) -> WidgetRef {
665        if SystemContextMenu::is_supported_by_field(app, editable_text_state) {
666            return SystemContextMenu::editable_text(app, editable_text_state).into_widget();
667        }
668        AdaptiveTextSelectionToolbar::editable_text(app, editable_text_state).into_widget()
669    }
670
671    /// Dart's `controller != null ? controller.text : (initialValue ?? '')`, which the
672    /// constructor hands the form field; with a controller it is `None` here, as its text needs
673    /// the App, and the state reads it when the widget arrives.
674    fn form_field_initial_value(&self) -> Option<String> {
675        match self.controller {
676            Some(_) => None,
677            None => Some(self.initial_value.clone().unwrap_or_default()),
678        }
679    }
680
681    /// Dart's `enabled ?? decoration?.enabled ?? true`, which the constructor hands both the
682    /// form field and the text field.
683    fn effective_enabled(&self) -> bool {
684        self.text_field
685            .enabled
686            .or(self
687                .text_field
688                .decoration
689                .as_ref()
690                .map(|decoration| decoration.enabled))
691            .unwrap_or(true)
692    }
693
694    /// Dart's builder closure: the [`TextField`] for the form field's current state.
695    fn build_field(app: &mut App, field: AnyFormFieldState<String>) -> WidgetRef {
696        let state = field
697            .downcast::<TextFormFieldState>(app)
698            .expect("a TextFormField's state is a TextFormFieldState");
699        let context = field.context(app);
700        let decoration_theme = InputDecorationTheme::of(app, context);
701        let widget = state.widget(app);
702        let mut effective_decoration = widget
703            .text_field
704            .decoration
705            .clone()
706            .unwrap_or_default()
707            .apply_defaults(decoration_theme);
708        let error_builder = widget.form_field.error_builder.clone();
709
710        if let Some(error_text) = field.error_text(app) {
711            effective_decoration = match error_builder {
712                Some(error_builder) => {
713                    let error = error_builder(app, state.context(app), error_text);
714                    effective_decoration.copy_with().error(error)
715                }
716                None => effective_decoration.copy_with().error_text(error_text),
717            };
718        }
719
720        let widget = state.widget(app);
721        let on_changed = widget.on_changed.clone();
722        let on_changed_handler = move |app: &mut App, value: String| {
723            field.did_change(app, Some(value.clone()));
724            if let Some(on_changed) = &on_changed {
725                on_changed(app, value);
726            }
727        };
728
729        let text_field = &widget.text_field;
730        let child = text_field
731            .clone()
732            .group_id(widget.group_id)
733            .controller(state.effective_controller(app))
734            .decoration(Some(effective_decoration))
735            .smart_dashes_type(text_field.effective_smart_dashes_type())
736            .smart_quotes_type(text_field.effective_smart_quotes_type())
737            .on_changed(on_changed_handler)
738            .enabled(widget.effective_enabled())
739            .enable_interactive_selection(
740                text_field
741                    .enable_interactive_selection
742                    .unwrap_or(!text_field.obscure_text || !text_field.read_only),
743            )
744            .selection_height_style(
745                text_field
746                    .selection_height_style
747                    .unwrap_or_else(EditableText::default_selection_height_style),
748            )
749            .selection_width_style(
750                text_field
751                    .selection_width_style
752                    .unwrap_or_else(EditableText::default_selection_width_style),
753            );
754
755        UnmanagedRestorationScope::new(child)
756            .bucket(state.bucket(app).and_then(|bucket| bucket.upgrade(app)))
757            .into_widget()
758    }
759
760    /// Dart's constructor asserts across fields.
761    fn debug_check_constructor(&self) {
762        let text_field = &self.text_field;
763        debug_assert!(self.initial_value.is_none() || self.controller.is_none());
764        debug_assert!(
765            text_field
766                .max_lines
767                .is_none_or(|max| text_field.min_lines.is_none_or(|min| max >= min)),
768            "minLines can't be greater than maxLines"
769        );
770        debug_assert!(
771            !text_field.expands
772                || (text_field.max_lines.is_none() && text_field.min_lines.is_none()),
773            "minLines and maxLines must be null when expands is true."
774        );
775        debug_assert!(
776            !text_field.obscure_text || text_field.max_lines == Some(1),
777            "Obscured fields cannot be multiline."
778        );
779        debug_assert!(
780            self.form_field.error_builder.is_none()
781                || text_field
782                    .decoration
783                    .as_ref()
784                    .is_none_or(|decoration| decoration.error_text.is_none()),
785            "Declaring both errorBuilder and decoration.errorText is not supported."
786        );
787    }
788}
789
790impl Default for TextFormField {
791    fn default() -> TextFormField {
792        TextFormField::new()
793    }
794}
795
796impl Debug for TextFormField {
797    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798        f.debug_struct("TextFormField")
799            .field("form_field", &self.form_field)
800            .field("controller", &self.controller)
801            .field("text_field", &self.text_field)
802            .finish_non_exhaustive()
803    }
804}
805
806impl FormFieldLeaf for TextFormField {
807    type Value = String;
808    waft_widgets::form_field_accessors!();
809}
810
811impl StatefulWidget for TextFormField {
812    type State = TextFormFieldState;
813
814    fn key(&self) -> Option<&KeyRef> {
815        self.form_field.key.as_ref()
816    }
817
818    fn debug_check_constructor(&self) {
819        TextFormField::debug_check_constructor(self);
820    }
821
822    fn create_state(&self) -> TextFormFieldState {
823        TextFormFieldState {
824            state: StateData::new(),
825            restoration: RestorationMixinData::new(),
826            form_field_state: FormFieldStateData::new(&self.form_field),
827            controller: None,
828            initial_value: None,
829            widget_initial_value: None,
830        }
831    }
832}
833
834/// Dart's `_TextFormFieldState`.
835pub struct TextFormFieldState {
836    state: StateData<TextFormField>,
837    restoration: RestorationMixinData,
838    form_field_state: FormFieldStateData<String>,
839    controller: Option<Ref<RestorableTextEditingController>>,
840    initial_value: Option<String>,
841    /// Dart's `widget.initialValue` for a widget with a controller: the controller's text when
842    /// the widget arrived, which Dart's constructor reads.
843    widget_initial_value: Option<String>,
844}
845
846impl TextFormFieldState {
847    fn effective_controller(self: Handle<Self>, app: &App) -> TextEditingControllerRef {
848        if let Some(controller) = self.widget(app).controller.clone() {
849            return controller;
850        }
851        let restorable = app
852            .get(self)
853            .controller
854            .handle()
855            .expect("a local controller exists when the widget does not supply one");
856        RestorableListenable::value(restorable, app)
857            .keep(app)
858            .into_erased()
859    }
860
861    fn register_controller(self: Handle<Self>, app: &mut App) {
862        let controller = app
863            .get(self)
864            .controller
865            .handle()
866            .expect("register_controller needs a local controller");
867        self.register_for_restoration(app, controller.as_property(), "controller");
868    }
869
870    fn create_local_controller(self: Handle<Self>, app: &mut App, value: Option<TextEditingValue>) {
871        debug_assert!(app.get(self).controller.is_none());
872        let controller = match value {
873            None => RestorableTextEditingController::new(app),
874            Some(value) => RestorableTextEditingController::from_value(app, value),
875        };
876        app.get_mut(self).controller = Some(controller.clone());
877        if !self.restore_pending(app) {
878            self.register_controller(app);
879        }
880    }
881
882    /// Records what Dart's constructor gives the form field as `initialValue` when the widget
883    /// has a controller: the controller's text.
884    fn read_widget_initial_value(self: Handle<Self>, app: &mut App) {
885        let text = self
886            .widget(app)
887            .controller
888            .as_ref()
889            .map(|controller| controller.text_value(app).to_owned());
890        app.get_mut(self).widget_initial_value = text;
891    }
892
893    fn handle_controller_changed(self: Handle<Self>, app: &mut App) {
894        // Suppress changes that originated from within this class.
895        //
896        // In the case where a controller has been passed in to this widget, we
897        // register this change listener. In these cases, we'll also receive change
898        // notifications for changes originating from within this class -- for
899        // example, the reset() method. In such cases, the FormField value will
900        // already have been set.
901        let text = self.effective_controller(app).text_value(app).to_owned();
902        if self.value(app) != Some(&text) {
903            self.did_change(app, Some(text));
904        }
905    }
906}
907
908impl RestorationMixin for TextFormFieldState {
909    waft_widgets::restoration_mixin_accessors!();
910
911    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
912        FormFieldState::restoration_id(self, app)
913    }
914
915    fn restore_state(
916        self: Handle<Self>,
917        app: &mut App,
918        old_bucket: Option<Handle<RestorationBucket>>,
919        initial_restore: bool,
920    ) {
921        FormFieldState::restore_state(self, app, old_bucket, initial_restore);
922        if app.get(self).controller.is_some() {
923            self.register_controller(app);
924        }
925        // Make sure to update the internal [FormFieldState] value to sync up with
926        // text editing controller value.
927        let text = self.effective_controller(app).text_value(app).to_owned();
928        self.set_value(app, Some(text));
929    }
930}
931
932impl FormFieldStateLeaf for TextFormFieldState {
933    waft_widgets::form_field_state_accessors!();
934
935    fn did_change(self: Handle<Self>, app: &mut App, value: Option<String>) {
936        FormFieldState::did_change(self, app, value.clone());
937
938        let controller = self.effective_controller(app);
939        if Some(controller.text_value(app)) != value.as_deref() {
940            controller.set_value(app, TextEditingValue::new().text(value.unwrap_or_default()));
941        }
942    }
943
944    fn reset(self: Handle<Self>, app: &mut App) {
945        // Set the controller value before calling super.reset() to let
946        // _handleControllerChanged suppress the change.
947        let initial_value = app.get(self).initial_value.clone().unwrap_or_default();
948        self.effective_controller(app)
949            .set_value(app, TextEditingValue::new().text(initial_value));
950        FormFieldState::reset(self, app);
951        if self.widget(app).controller.is_some() {
952            let widget_initial_value = app.get(self).widget_initial_value.clone();
953            self.set_value(app, widget_initial_value);
954        }
955        if let Some(on_changed) = self.widget(app).on_changed.clone() {
956            let text = self.effective_controller(app).text_value(app).to_owned();
957            on_changed(app, text);
958        }
959    }
960}
961
962impl State for TextFormFieldState {
963    type Widget = TextFormField;
964    waft_widgets::state_accessors!();
965
966    fn init_state(self: Handle<Self>, app: &mut App) {
967        FormFieldState::init_state(self, app);
968        match self.widget(app).controller.clone() {
969            None => {
970                let value = self
971                    .widget(app)
972                    .form_field
973                    .initial_value
974                    .clone()
975                    .map(|initial_value| TextEditingValue::new().text(initial_value));
976                self.create_local_controller(app, value);
977            }
978            Some(controller) => {
979                controller.add_listener(
980                    app,
981                    Listener::handle_method(self, Self::handle_controller_changed),
982                );
983            }
984        }
985        self.read_widget_initial_value(app);
986        let initial_value = self
987            .widget(app)
988            .form_field
989            .initial_value
990            .clone()
991            .or_else(|| app.get(self).widget_initial_value.clone());
992        app.get_mut(self).initial_value = initial_value;
993        if self.widget(app).controller.is_some() {
994            let value = app.get(self).widget_initial_value.clone();
995            self.set_value(app, value);
996        }
997    }
998
999    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TextFormField) {
1000        FormFieldState::did_update_widget(self, app, old_widget);
1001        self.read_widget_initial_value(app);
1002        if self.widget(app).controller != old_widget.controller {
1003            if let Some(old_controller) = old_widget.controller.clone() {
1004                old_controller.remove_listener(
1005                    app,
1006                    &Listener::handle_method(self, Self::handle_controller_changed),
1007                );
1008            }
1009            if let Some(controller) = self.widget(app).controller.clone() {
1010                controller.add_listener(
1011                    app,
1012                    Listener::handle_method(self, Self::handle_controller_changed),
1013                );
1014            }
1015
1016            if let Some(old_controller) = old_widget.controller.clone()
1017                && self.widget(app).controller.is_none()
1018            {
1019                let value = old_controller.value(app).clone();
1020                self.create_local_controller(app, Some(value));
1021            }
1022
1023            if let Some(controller) = self.widget(app).controller.clone() {
1024                let text = controller.text_value(app).to_owned();
1025                self.set_value(app, Some(text));
1026                if old_widget.controller.is_none() {
1027                    let local = app
1028                        .get(self)
1029                        .controller
1030                        .handle()
1031                        .expect("a local controller while the old widget had none");
1032                    self.unregister_from_restoration(app, local.as_property());
1033                    RestorableProperty::dispose(local, app);
1034                    app.get_mut(self).controller = None;
1035                }
1036            }
1037        }
1038    }
1039
1040    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1041        FormFieldState::did_change_dependencies(self, app);
1042    }
1043
1044    fn deactivate(self: Handle<Self>, app: &mut App) {
1045        FormFieldState::deactivate(self, app);
1046    }
1047
1048    fn dispose(self: Handle<Self>, app: &mut App) {
1049        if let Some(controller) = self.widget(app).controller.clone() {
1050            controller.remove_listener(
1051                app,
1052                &Listener::handle_method(self, Self::handle_controller_changed),
1053            );
1054        }
1055        if let Some(controller) = app.get(self).controller.handle() {
1056            RestorableProperty::dispose(controller, app);
1057        }
1058        FormFieldState::dispose(self, app);
1059    }
1060
1061    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1062        FormFieldState::build(self, app, context)
1063    }
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use std::cell::{Cell, RefCell};
1069
1070    use waft_services::TextInputClient;
1071    use waft_widgets::{
1072        AnyElement, Center, Form, FormState, GlobalKey, ListView, StateSetter, StatefulBuilder,
1073        Text, TextEditingController,
1074    };
1075
1076    use waft_widgets::testing::{WidgetTester, find, test_widgets};
1077
1078    use super::*;
1079    use crate::material::Material;
1080    use crate::scaffold::Scaffold;
1081    use crate::test_support::material_app;
1082    use crate::theme_data::ThemeData;
1083    use waft_widgets::TextEditingControllerLeaf;
1084
1085    /// Dart's `MaterialApp(home: Material(child: Center(child: field)))`.
1086    fn centered<K>(tester: &WidgetTester, field: impl IntoWidget<K>) -> WidgetRef {
1087        material_app(
1088            ThemeData::new(&tester.cell.borrow()),
1089            Material::new()
1090                .child(Center::new().child(field))
1091                .into_widget(),
1092        )
1093    }
1094
1095    fn editable_state(tester: &WidgetTester) -> Handle<EditableTextState> {
1096        find::by_type::<EditableText>().evaluate(tester)[0]
1097            .state_handle::<EditableTextState>(&tester.cell.borrow())
1098            .expect("an EditableText state")
1099    }
1100
1101    fn field_state(tester: &WidgetTester) -> Handle<TextFormFieldState> {
1102        find::by_type::<TextFormField>().evaluate(tester)[0]
1103            .state_handle::<TextFormFieldState>(&tester.cell.borrow())
1104            .expect("a TextFormField state")
1105    }
1106
1107    fn text_field(tester: &WidgetTester) -> AnyElement {
1108        find::by_type::<TextField>().evaluate(tester)[0]
1109    }
1110
1111    #[test]
1112    fn text_form_field_accepts_text_field_no_max_length_as_value_to_max_length_parameter() {
1113        let _ = TextFormField::new()
1114            .max_length(TextField::NO_MAX_LENGTH)
1115            .into_widget();
1116    }
1117
1118    #[test]
1119    fn passes_text_align_to_underlying_text_field() {
1120        test_widgets(|tester| {
1121            let root = centered(tester, TextFormField::new().text_align(TextAlign::Center));
1122            tester.pump_widget(root);
1123
1124            assert_eq!(find::by_type::<TextField>().evaluate(tester).len(), 1);
1125            let text_align =
1126                tester.widget::<TextField, _>(text_field(tester), |field| field.text_align);
1127            assert_eq!(text_align, TextAlign::Center);
1128        });
1129    }
1130
1131    #[test]
1132    fn passes_text_input_action_to_underlying_text_field() {
1133        test_widgets(|tester| {
1134            let root = centered(
1135                tester,
1136                TextFormField::new().text_input_action(TextInputAction::Next),
1137            );
1138            tester.pump_widget(root);
1139
1140            let action =
1141                tester.widget::<TextField, _>(text_field(tester), |field| field.text_input_action);
1142            assert_eq!(action, Some(TextInputAction::Next));
1143        });
1144    }
1145
1146    #[test]
1147    // Dart's 3.14 and 6.28 are plain values, not approximations of π and τ.
1148    #[allow(clippy::approx_constant)]
1149    fn passes_cursor_attributes_to_underlying_text_field() {
1150        test_widgets(|tester| {
1151            let cursor_color = crate::colors::Colors::PURPLE.primary();
1152            let root = centered(
1153                tester,
1154                TextFormField::new()
1155                    .cursor_width(3.14)
1156                    .cursor_height(6.28)
1157                    .cursor_radius(Radius::circular(4.0))
1158                    .cursor_color(cursor_color),
1159            );
1160            tester.pump_widget(root);
1161
1162            let (width, height, radius, color) =
1163                tester.widget::<TextField, _>(text_field(tester), |field| {
1164                    (
1165                        field.cursor_width,
1166                        field.cursor_height,
1167                        field.cursor_radius,
1168                        field.cursor_color,
1169                    )
1170                });
1171            assert_eq!(width, 3.14);
1172            assert_eq!(height, Some(6.28));
1173            assert_eq!(radius, Some(Radius::circular(4.0)));
1174            assert_eq!(color, Some(cursor_color));
1175        });
1176    }
1177
1178    #[test]
1179    fn on_field_submit_callbacks_are_called() {
1180        test_widgets(|tester| {
1181            let called = Rc::new(Cell::new(false));
1182            let flag = Rc::clone(&called);
1183            let root = centered(
1184                tester,
1185                TextFormField::new().on_field_submitted(move |_app, _value| flag.set(true)),
1186            );
1187            tester.pump_widget(root);
1188
1189            tester.show_keyboard(find::by_type::<TextFormField>());
1190            tester
1191                .test_text_input()
1192                .receive_action(TextInputAction::Done);
1193            tester.pump();
1194            assert!(called.get());
1195        });
1196    }
1197
1198    #[test]
1199    fn on_changed_callbacks_are_called() {
1200        test_widgets(|tester| {
1201            let value = Rc::new(RefCell::new(String::new()));
1202            let seen = Rc::clone(&value);
1203            let root = centered(
1204                tester,
1205                TextFormField::new().on_changed(move |_app, v| *seen.borrow_mut() = v),
1206            );
1207            tester.pump_widget(root);
1208
1209            tester.enter_text(find::by_type::<TextFormField>(), "Soup");
1210            tester.pump();
1211            assert_eq!(*value.borrow(), "Soup");
1212        });
1213    }
1214
1215    fn validate_counting(tester: &mut WidgetTester, enabled: Option<bool>) {
1216        let validate_called = Rc::new(Cell::new(0));
1217        let counter = Rc::clone(&validate_called);
1218        let mut field = TextFormField::new()
1219            .autovalidate_mode(AutovalidateMode::Always)
1220            .validator(move |_app, _value| {
1221                counter.set(counter.get() + 1);
1222                None
1223            });
1224        if let Some(enabled) = enabled {
1225            field = field.enabled(enabled);
1226        }
1227        let root = centered(tester, field);
1228        tester.pump_widget(root);
1229
1230        assert_eq!(validate_called.get(), 1);
1231        tester.enter_text(find::by_type::<TextFormField>(), "a");
1232        tester.pump();
1233        assert_eq!(validate_called.get(), 2);
1234    }
1235
1236    #[test]
1237    fn autovalidate_mode_is_passed_to_super() {
1238        test_widgets(|tester| validate_counting(tester, None));
1239    }
1240
1241    #[test]
1242    fn validate_is_called_if_widget_is_enabled() {
1243        test_widgets(|tester| validate_counting(tester, Some(true)));
1244    }
1245
1246    #[test]
1247    fn passing_a_build_counter_shows_returned_widget() {
1248        test_widgets(|tester| {
1249            let root = centered(
1250                tester,
1251                TextFormField::new()
1252                    .build_counter(|_app, _context, current_length, max_length, _is_focused| {
1253                        let max_length =
1254                            max_length.map_or_else(|| "null".to_owned(), |max| max.to_string());
1255                        Some(Text::new(format!("{current_length} of {max_length}")).into_widget())
1256                    })
1257                    .max_length(10),
1258            );
1259            tester.pump_widget(root);
1260
1261            assert_eq!(find::text("0 of 10").evaluate(tester).len(), 1);
1262
1263            tester.enter_text(find::by_type::<TextFormField>(), "01234");
1264            tester.pump();
1265
1266            assert_eq!(find::text("5 of 10").evaluate(tester).len(), 1);
1267        });
1268    }
1269
1270    #[test]
1271    fn readonly_text_form_field_will_hide_cursor_by_default() {
1272        test_widgets(|tester| {
1273            let root = centered(
1274                tester,
1275                TextFormField::new()
1276                    .initial_value("readonly")
1277                    .read_only(true),
1278            );
1279            tester.pump_widget(root);
1280
1281            let element = find::by_type::<EditableText>().evaluate(tester)[0];
1282            let show_cursor =
1283                tester.widget::<EditableText, _>(element, EditableText::effective_show_cursor);
1284            assert!(!show_cursor);
1285        });
1286    }
1287
1288    fn editable_text_value(tester: &WidgetTester) -> String {
1289        let state = editable_state(tester);
1290        TextInputClient::current_text_editing_value(state, &tester.cell.borrow())
1291            .expect("the field has a value")
1292            .text
1293    }
1294
1295    #[test]
1296    fn reset_resets_the_text_fields_value_to_the_initial_value() {
1297        test_widgets(|tester| {
1298            let root = centered(tester, TextFormField::new().initial_value("initialValue"));
1299            tester.pump_widget(root);
1300
1301            tester.enter_text(find::by_type::<TextFormField>(), "changedValue");
1302
1303            let state = field_state(tester);
1304            state.reset(&mut tester.cell.borrow_mut());
1305            tester.pump();
1306
1307            assert_eq!(editable_text_value(tester), "initialValue");
1308        });
1309    }
1310
1311    #[test]
1312    fn reset_resets_the_text_fields_value_to_the_controller_initial_value() {
1313        test_widgets(|tester| {
1314            let controller = {
1315                let mut app = tester.cell.borrow_mut();
1316                let controller = TextEditingController::new(&mut app);
1317                controller.set_text(&mut app, "initialValue");
1318                controller
1319            };
1320            let root = centered(tester, TextFormField::new().controller(controller.erase()));
1321            tester.pump_widget(root);
1322
1323            tester.enter_text(find::by_type::<TextFormField>(), "changedValue");
1324
1325            let state = field_state(tester);
1326            state.reset(&mut tester.cell.borrow_mut());
1327            tester.pump();
1328
1329            assert_eq!(editable_text_value(tester), "initialValue");
1330        });
1331    }
1332
1333    #[test]
1334    fn did_change_changes_text_fields_value() {
1335        test_widgets(|tester| {
1336            let root = centered(tester, TextFormField::new().initial_value("initialValue"));
1337            tester.pump_widget(root);
1338
1339            assert_eq!(editable_text_value(tester), "initialValue");
1340
1341            let state = field_state(tester);
1342            state.did_change(&mut tester.cell.borrow_mut(), Some("changedValue".into()));
1343            tester.pump();
1344
1345            assert_eq!(editable_text_value(tester), "changedValue");
1346        });
1347    }
1348
1349    #[test]
1350    fn on_changed_callbacks_value_and_form_field_state_value_are_sync() {
1351        test_widgets(|tester| {
1352            let called = Rc::new(Cell::new(false));
1353            let state_slot: Rc<Cell<Option<Handle<TextFormFieldState>>>> = Rc::new(Cell::new(None));
1354            let (flag, slot) = (Rc::clone(&called), Rc::clone(&state_slot));
1355            let root = centered(
1356                tester,
1357                TextFormField::new().on_changed(move |app, value| {
1358                    flag.set(true);
1359                    let state = slot.get().expect("the case records the state");
1360                    assert_eq!(state.value(app), Some(&value));
1361                }),
1362            );
1363            tester.pump_widget(root);
1364
1365            state_slot.set(Some(field_state(tester)));
1366
1367            tester.enter_text(find::by_type::<TextFormField>(), "Soup");
1368
1369            assert!(called.get());
1370        });
1371    }
1372
1373    #[test]
1374    fn text_form_field_on_changed_is_called_when_the_form_is_reset() {
1375        test_widgets(|tester| {
1376            let state_key = GlobalKey::new();
1377            let form_key = GlobalKey::new();
1378            let value = Rc::new(RefCell::new("initialValue".to_owned()));
1379            let seen = Rc::clone(&value);
1380            let root = material_app(
1381                ThemeData::new(&tester.cell.borrow()),
1382                Scaffold::new()
1383                    .body(
1384                        Form::new(
1385                            TextFormField::new()
1386                                .key(state_key.clone().into())
1387                                .initial_value(value.borrow().clone())
1388                                .on_changed(move |_app, new_value| *seen.borrow_mut() = new_value),
1389                        )
1390                        .key(form_key.clone().into()),
1391                    )
1392                    .into_widget(),
1393            );
1394            tester.pump_widget(root);
1395
1396            let field_value = |tester: &WidgetTester| {
1397                let app = tester.cell.borrow();
1398                let state = state_key
1399                    .current_state::<TextFormFieldState>(&app)
1400                    .expect("the field mounted");
1401                state.value(&app).cloned()
1402            };
1403
1404            // Initial value is 'initialValue'.
1405            assert_eq!(field_value(tester).as_deref(), Some("initialValue"));
1406            assert_eq!(*value.borrow(), "initialValue");
1407
1408            // Change value to 'changedValue'.
1409            tester.enter_text(find::by_type::<TextFormField>(), "changedValue");
1410            assert_eq!(field_value(tester).as_deref(), Some("changedValue"));
1411            assert_eq!(*value.borrow(), "changedValue");
1412
1413            // Should be back to 'initialValue' when the form is reset.
1414            {
1415                let mut app = tester.cell.borrow_mut();
1416                let form = form_key
1417                    .current_state::<FormState>(&app)
1418                    .expect("the form mounted");
1419                form.reset(&mut app);
1420            }
1421            tester.pump();
1422            assert_eq!(field_value(tester).as_deref(), Some("initialValue"));
1423            assert_eq!(*value.borrow(), "initialValue");
1424        });
1425    }
1426
1427    #[test]
1428    fn is_valid_returns_false_when_force_error_text_is_set_and_will_change_error_display() {
1429        test_widgets(|tester| {
1430            let field_key1 = GlobalKey::new();
1431            let field_key2 = GlobalKey::new();
1432            let valid_string = "Valid string";
1433            let validator = move |_app: &mut App, s: Option<&String>| {
1434                if s.map(String::as_str) == Some(valid_string) {
1435                    None
1436                } else {
1437                    Some("Error text".to_owned())
1438                }
1439            };
1440            let root = material_app(
1441                ThemeData::new(&tester.cell.borrow()),
1442                Center::new()
1443                    .child(
1444                        Material::new().child(Form::new(ListView::new().children(vec![
1445                        TextFormField::new()
1446                            .key(field_key1.clone().into())
1447                            .initial_value(valid_string)
1448                            .validator(validator)
1449                            .autovalidate_mode(AutovalidateMode::Disabled)
1450                            .into_widget(),
1451                        TextFormField::new()
1452                            .key(field_key2.clone().into())
1453                            .initial_value("")
1454                            .force_error_text("Forcing error.")
1455                            .validator(validator)
1456                            .autovalidate_mode(AutovalidateMode::Disabled)
1457                            .into_widget(),
1458                    ]))),
1459                    )
1460                    .into_widget(),
1461            );
1462            tester.pump_widget(root);
1463
1464            let mut app = tester.cell.borrow_mut();
1465            let state1 = field_key1
1466                .current_state::<TextFormFieldState>(&app)
1467                .expect("the first field mounted");
1468            let state2 = field_key2
1469                .current_state::<TextFormFieldState>(&app)
1470                .expect("the second field mounted");
1471            assert!(state1.is_valid(&mut app));
1472            assert!(!state1.has_error(&app));
1473            assert!(!state2.is_valid(&mut app));
1474            assert!(state2.has_error(&app));
1475        });
1476    }
1477
1478    #[test]
1479    fn widget_returned_by_error_builder_is_shown() {
1480        test_widgets(|tester| {
1481            let root = centered(
1482                tester,
1483                TextFormField::new()
1484                    .autovalidate_mode(AutovalidateMode::Always)
1485                    .validator(|_app, _value| Some("validation error".to_owned()))
1486                    .error_builder(|_app, _context, error_text| {
1487                        Text::new(format!("**{error_text}**")).into_widget()
1488                    }),
1489            );
1490            tester.pump_widget(root);
1491            tester.pump();
1492
1493            assert_eq!(find::text("**validation error**").evaluate(tester).len(), 1);
1494        });
1495    }
1496
1497    #[test]
1498    #[should_panic(
1499        expected = "Declaring both errorBuilder and decoration.errorText is not supported."
1500    )]
1501    fn text_form_field_asserts_when_both_error_builder_and_decoration_error_text_are_provided() {
1502        let _ = TextFormField::new()
1503            .decoration(Some(
1504                InputDecoration::new().error_text("decoration error text"),
1505            ))
1506            .error_builder(|_app, _context, error_text| Text::new(error_text).into_widget())
1507            .into_widget();
1508    }
1509
1510    #[test]
1511    fn text_form_field_resets_to_initial_value_after_set_state() {
1512        test_widgets(|tester| {
1513            let form_key = GlobalKey::new();
1514            let controller = {
1515                let mut app = tester.cell.borrow_mut();
1516                let controller = TextEditingController::new(&mut app);
1517                controller.set_text(&mut app, "Initial Value");
1518                controller.clone()
1519            };
1520            let set_state: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
1521            let setter_slot = Rc::clone(&set_state);
1522            let key_for_form = form_key.clone();
1523            let root = material_app(
1524                ThemeData::new(&tester.cell.borrow()),
1525                Scaffold::new()
1526                    .body(StatefulBuilder::new({
1527                        let controller = controller.clone();
1528                        move |_app, _context, setter| {
1529                            *setter_slot.borrow_mut() = Some(setter);
1530                            Form::new(TextFormField::new().controller(controller.erase()))
1531                                .key(key_for_form.clone().into())
1532                                .into_widget()
1533                        }
1534                    }))
1535                    .into_widget(),
1536            );
1537            tester.pump_widget(root);
1538
1539            tester.enter_text(find::by_type::<TextFormField>(), "Changed");
1540            tester.pump();
1541            assert_eq!(controller.text_value(&tester.cell.borrow()), "Changed");
1542
1543            let setter = set_state.borrow().clone().expect("the builder ran");
1544            setter(&mut tester.cell.borrow_mut(), &mut |_app| {});
1545            tester.pump();
1546
1547            {
1548                let mut app = tester.cell.borrow_mut();
1549                let form = form_key
1550                    .current_state::<FormState>(&app)
1551                    .expect("the form mounted");
1552                form.reset(&mut app);
1553            }
1554            tester.pump();
1555
1556            assert_eq!(
1557                controller.text_value(&tester.cell.borrow()),
1558                "Initial Value"
1559            );
1560        });
1561    }
1562}