Skip to main content

waft_widgets/widgets/
autofill.rs

1//! Flutter counterpart: `widgets/autofill.dart`.
2
3use std::collections::HashMap;
4
5use waft_foundation::{App, Handle};
6use waft_services::{AnyAutofillClient, AutofillScope, TextInput};
7
8use crate::framework::{
9    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
10};
11
12pub use waft_services::AutofillHints;
13
14/// Predefined autofill context clean up actions.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum AutofillContextAction {
17    /// Destroys the current autofill context after informing the platform to save
18    /// the user input from it.
19    ///
20    /// Corresponds to calling [`TextInput::finish_autofill_context`] with
21    /// `should_save == true`.
22    Commit,
23
24    /// Destroys the current autofill context without saving the user input.
25    ///
26    /// Corresponds to calling [`TextInput::finish_autofill_context`] with
27    /// `should_save == false`.
28    Cancel,
29}
30
31/// An [`AutofillScope`] widget that groups `AutofillClient`s together.
32///
33/// `AutofillClient`s that share the same closest [`AutofillGroup`] ancestor must
34/// be built together, and they will be autofilled together.
35///
36/// The [`AutofillGroup`] widget only knows about `AutofillClient`s registered to
37/// it using the [`AutofillGroupState::register`] API. Typically, [`AutofillGroup`]
38/// will not pick up `AutofillClient`s that are not mounted, for example, an
39/// `AutofillClient` within a `Scrollable` that has never been scrolled into the
40/// viewport. To workaround this problem, ensure clients in the same
41/// [`AutofillGroup`] are built together.
42///
43/// The topmost [`AutofillGroup`] widgets (the ones that are closest to the root
44/// widget) can be used to clean up the current autofill context when the
45/// current autofill context is no longer relevant.
46///
47/// By default, [`on_dispose_action`](Self::on_dispose_action) is set to
48/// [`AutofillContextAction::Commit`], in which case when any of the topmost
49/// [`AutofillGroup`]s is being disposed, the platform will be informed to save
50/// the user input from the current autofill context, then the current autofill
51/// context will be destroyed, to free resources. You can, for example, wrap a
52/// route that contains a `Form` full of autofillable input fields in an
53/// [`AutofillGroup`], so the user input of the `Form` can be saved for future
54/// autofill by the platform.
55///
56/// See also:
57///
58/// * [`AutofillContextAction`], an enum that contains predefined autofill context
59///   clean up actions to be run when a topmost [`AutofillGroup`] is disposed.
60#[derive(Debug)]
61pub struct AutofillGroup {
62    /// See [`StatefulWidget::key`].
63    pub key: Option<KeyRef>,
64    /// The widget below this widget in the tree.
65    pub child: WidgetRef,
66    /// The [`AutofillContextAction`] to be run when this [`AutofillGroup`] is the
67    /// topmost [`AutofillGroup`] and it's being disposed, in order to clean up the
68    /// current autofill context.
69    ///
70    /// Defaults to [`AutofillContextAction::Commit`], which prompts the platform to
71    /// save the user input and destroy the current autofill context.
72    pub on_dispose_action: AutofillContextAction,
73}
74
75impl AutofillGroup {
76    /// Creates a scope for autofillable input fields.
77    #[cfg_attr(debug_assertions, track_caller)]
78    pub fn new<K>(child: impl IntoWidget<K>) -> AutofillGroup {
79        AutofillGroup {
80            key: None,
81            child: child.into_widget(),
82            on_dispose_action: AutofillContextAction::Commit,
83        }
84    }
85
86    /// Dart `AutofillGroup(key:)`.
87    pub fn key(mut self, key: KeyRef) -> AutofillGroup {
88        self.key = Some(key);
89        self
90    }
91
92    /// Dart `AutofillGroup(onDisposeAction:)`.
93    pub fn on_dispose_action(mut self, on_dispose_action: AutofillContextAction) -> AutofillGroup {
94        self.on_dispose_action = on_dispose_action;
95        self
96    }
97
98    /// Returns the [`AutofillGroupState`] of the closest [`AutofillGroup`] widget
99    /// which encloses the given context, or null if one cannot be found.
100    ///
101    /// Calling this method will create a dependency on the closest
102    /// [`AutofillGroup`] in the [`context`], if there is one.
103    ///
104    /// See also:
105    ///
106    /// * [`AutofillGroup::of`], which is similar to this method, but asserts if an
107    ///   [`AutofillGroup`] cannot be found.
108    /// * `EditableTextState`, where this method is used to retrieve the closest
109    ///   [`AutofillGroupState`].
110    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<AutofillGroupState>> {
111        context
112            .depend_on_inherited_widget_of_exact_type::<AutofillScopeInherited>(app)
113            .and_then(|scope| scope.scope)
114    }
115
116    /// Returns the [`AutofillGroupState`] of the closest [`AutofillGroup`] widget
117    /// which encloses the given context.
118    ///
119    /// If no instance is found, this method panics.
120    ///
121    /// Calling this method will create a dependency on the closest
122    /// [`AutofillGroup`] in the [`context`].
123    ///
124    /// See also:
125    ///
126    /// * [`AutofillGroup::maybe_of`], which is similar to this method, but returns
127    ///   null if an [`AutofillGroup`] cannot be found.
128    /// * `EditableTextState`, where this method is used to retrieve the closest
129    ///   [`AutofillGroupState`].
130    pub fn of(app: &mut App, context: BuildContext) -> Handle<AutofillGroupState> {
131        AutofillGroup::maybe_of(app, context).expect(
132            "AutofillGroup.of() was called with a context that does not contain an \
133             AutofillGroup widget.\n\
134             No AutofillGroup widget ancestor could be found starting from the \
135             context that was passed to AutofillGroup.of(). This can happen \
136             because you are using a widget that looks for an AutofillGroup \
137             ancestor, but no such ancestor exists.",
138        )
139    }
140}
141
142impl StatefulWidget for AutofillGroup {
143    type State = AutofillGroupState;
144
145    fn key(&self) -> Option<&KeyRef> {
146        self.key.as_ref()
147    }
148
149    fn create_state(&self) -> AutofillGroupState {
150        AutofillGroupState {
151            state: StateData::new(),
152            clients: HashMap::new(),
153            is_topmost_autofill_group: false,
154        }
155    }
156}
157
158/// State associated with an [`AutofillGroup`] widget.
159///
160/// An [`AutofillGroupState`] can be used to register an `AutofillClient` when it
161/// enters this [`AutofillGroup`] (for example, when an `EditableText` is mounted or
162/// reparented onto the [`AutofillGroup`]'s subtree), and unregister an
163/// `AutofillClient` when it exits (for example, when an `EditableText` gets
164/// unmounted or reparented out of the [`AutofillGroup`]'s subtree).
165///
166/// The [`AutofillGroupState`] class also provides an [`AutofillScope::attach`]
167/// method that can be called by `TextInputClient`s that support autofill,
168/// instead of [`TextInput::attach`], to create a `TextInputConnection` to interact
169/// with the platform's text input system.
170///
171/// Typically obtained using [`AutofillGroup::of`].
172pub struct AutofillGroupState {
173    state: StateData<AutofillGroup>,
174    clients: HashMap<String, AnyAutofillClient>,
175    // Whether this AutofillGroup widget is the topmost AutofillGroup (i.e., it
176    // has no AutofillGroup ancestor). Each topmost AutofillGroup runs its
177    // `AutofillGroup.onDisposeAction` when it gets disposed.
178    is_topmost_autofill_group: bool,
179}
180
181impl AutofillGroupState {
182    /// Adds the `AutofillClient` to this [`AutofillGroup`].
183    ///
184    /// Typically, this is called by `TextInputClient`s that support autofill (for
185    /// example, `EditableTextState`) in [`State::did_change_dependencies`], when the
186    /// input field should be registered to a new [`AutofillGroup`].
187    ///
188    /// See also:
189    ///
190    /// * `EditableTextState.didChangeDependencies`, where this method is called
191    ///   to update the current [`AutofillScope`] when needed.
192    pub fn register(self: Handle<Self>, app: &mut App, client: AnyAutofillClient) {
193        let autofill_id = client.autofill_id(app);
194        app.get_mut(self)
195            .clients
196            .entry(autofill_id)
197            .or_insert(client);
198    }
199
200    /// Removes an `AutofillClient` with the given `autofill_id` from this
201    /// [`AutofillGroup`].
202    ///
203    /// Typically, this should be called by a text field when it's being disposed,
204    /// or before it's registered with a different [`AutofillGroup`].
205    ///
206    /// See also:
207    ///
208    /// * `EditableTextState.didChangeDependencies`, where this method is called
209    ///   to unregister from the previous [`AutofillScope`].
210    /// * `EditableTextState.dispose`, where this method is called to unregister
211    ///   from the current [`AutofillScope`] when the widget is about to be removed
212    ///   from the tree.
213    pub fn unregister(self: Handle<Self>, app: &mut App, autofill_id: &str) {
214        debug_assert!(app.get(self).clients.contains_key(autofill_id));
215        app.get_mut(self).clients.remove(autofill_id);
216    }
217}
218
219impl AutofillScope for AutofillGroupState {
220    fn get_autofill_client(
221        self: Handle<Self>,
222        app: &App,
223        autofill_id: &str,
224    ) -> Option<AnyAutofillClient> {
225        app.get(self).clients.get(autofill_id).copied()
226    }
227
228    fn autofill_clients(self: Handle<Self>, app: &App) -> Vec<AnyAutofillClient> {
229        app.get(self)
230            .clients
231            .values()
232            .copied()
233            .filter(|client| {
234                client
235                    .text_input_configuration(app)
236                    .autofill_configuration
237                    .enabled
238            })
239            .collect()
240    }
241}
242
243impl State for AutofillGroupState {
244    type Widget = AutofillGroup;
245    crate::state_accessors!();
246
247    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
248        let context = self.context(app);
249        let is_topmost = AutofillGroup::maybe_of(app, context).is_none();
250        app.get_mut(self).is_topmost_autofill_group = is_topmost;
251    }
252
253    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
254        let child = self.widget(app).child.clone();
255        AutofillScopeInherited {
256            scope: Some(self),
257            child,
258        }
259        .into_widget()
260    }
261
262    fn dispose(self: Handle<Self>, app: &mut App) {
263        if !app.get(self).is_topmost_autofill_group {
264            return;
265        }
266        match self.widget(app).on_dispose_action {
267            AutofillContextAction::Cancel => TextInput::finish_autofill_context(app, false),
268            AutofillContextAction::Commit => TextInput::finish_autofill_context(app, true),
269        }
270    }
271}
272
273/// Dart's `_AutofillScope`.
274#[derive(Debug)]
275struct AutofillScopeInherited {
276    scope: Option<Handle<AutofillGroupState>>,
277    child: WidgetRef,
278}
279
280impl InheritedWidget for AutofillScopeInherited {
281    fn child(&self) -> &WidgetRef {
282        &self.child
283    }
284
285    fn update_should_notify(&self, old: &AutofillScopeInherited) -> bool {
286        self.scope != old.scope
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use waft_foundation::{AppCell, Handle};
293    use waft_services::{
294        AutofillClient, AutofillConfiguration, TextEditingValue, TextInputConfiguration,
295    };
296
297    use super::*;
298    use crate::framework::{AnyElement, Element, IntoWidget};
299    use crate::test_harness::Harness;
300    use crate::widgets::basic::SizedBox;
301
302    struct TestClient {
303        autofill_id: String,
304        enabled: bool,
305    }
306
307    impl AutofillClient for TestClient {
308        fn autofill_id(self: Handle<Self>, app: &App) -> String {
309            app.get(self).autofill_id.clone()
310        }
311
312        fn text_input_configuration(self: Handle<Self>, app: &App) -> TextInputConfiguration {
313            if !app.get(self).enabled {
314                return TextInputConfiguration::default();
315            }
316            TextInputConfiguration::builder()
317                .autofill_configuration(AutofillConfiguration::new(
318                    app.get(self).autofill_id.clone(),
319                    vec![AutofillHints::EMAIL.to_owned()],
320                    TextEditingValue::new(),
321                ))
322                .build()
323        }
324
325        fn autofill(self: Handle<Self>, _app: &mut App, _new_editing_value: TextEditingValue) {}
326    }
327
328    fn descendant(harness: &Harness, app: &App, depth: usize) -> AnyElement {
329        let mut element = harness.root.as_element();
330        for _ in 0..=depth {
331            element = element.children(app)[0];
332        }
333        element
334    }
335
336    #[test]
337    fn maybe_of_is_none_without_an_ancestor() {
338        let cell = AppCell::new();
339        let mut app = cell.borrow_mut();
340        let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
341        harness.pump(&mut app);
342        let context = descendant(&harness, &app, 0);
343        assert!(AutofillGroup::maybe_of(&mut app, context).is_none());
344    }
345
346    #[test]
347    #[should_panic(expected = "AutofillGroup.of() was called with a context that does not contain")]
348    fn of_panics_without_an_ancestor() {
349        let cell = AppCell::new();
350        let mut app = cell.borrow_mut();
351        let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
352        harness.pump(&mut app);
353        let context = descendant(&harness, &app, 0);
354        let _ = AutofillGroup::of(&mut app, context);
355    }
356
357    #[test]
358    fn maybe_of_finds_the_group() {
359        let cell = AppCell::new();
360        let mut app = cell.borrow_mut();
361        let harness = Harness::mount(
362            &mut app,
363            AutofillGroup::new(SizedBox::shrink()).into_widget(),
364        );
365        harness.pump(&mut app);
366        // TestRoot → AutofillGroup → _AutofillScope → SizedBox
367        let child = descendant(&harness, &app, 2);
368        assert!(AutofillGroup::maybe_of(&mut app, child).is_some());
369    }
370
371    #[test]
372    fn register_and_unregister() {
373        let cell = AppCell::new();
374        let mut app = cell.borrow_mut();
375        let harness = Harness::mount(
376            &mut app,
377            AutofillGroup::new(SizedBox::shrink()).into_widget(),
378        );
379        harness.pump(&mut app);
380        let child = descendant(&harness, &app, 2);
381        let group = AutofillGroup::of(&mut app, child);
382
383        let enabled = app.create(TestClient {
384            autofill_id: "email".into(),
385            enabled: true,
386        });
387        let disabled = app.create(TestClient {
388            autofill_id: "plain".into(),
389            enabled: false,
390        });
391
392        group.register(&mut app, enabled.as_autofill_client());
393        group.register(&mut app, disabled.as_autofill_client());
394
395        assert_eq!(
396            group
397                .get_autofill_client(&app, "email")
398                .map(|c| c.autofill_id(&app)),
399            Some("email".into())
400        );
401        assert_eq!(
402            group
403                .autofill_clients(&app)
404                .into_iter()
405                .map(|c| c.autofill_id(&app))
406                .collect::<Vec<_>>(),
407            vec!["email".to_string()]
408        );
409
410        group.unregister(&mut app, "email");
411        group.unregister(&mut app, "plain");
412        assert!(group.get_autofill_client(&app, "email").is_none());
413        assert!(group.autofill_clients(&app).is_empty());
414    }
415}