1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum AutofillContextAction {
17 Commit,
23
24 Cancel,
29}
30
31#[derive(Debug)]
61pub struct AutofillGroup {
62 pub key: Option<KeyRef>,
64 pub child: WidgetRef,
66 pub on_dispose_action: AutofillContextAction,
73}
74
75impl AutofillGroup {
76 #[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 pub fn key(mut self, key: KeyRef) -> AutofillGroup {
88 self.key = Some(key);
89 self
90 }
91
92 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 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 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
158pub struct AutofillGroupState {
173 state: StateData<AutofillGroup>,
174 clients: HashMap<String, AnyAutofillClient>,
175 is_topmost_autofill_group: bool,
179}
180
181impl AutofillGroupState {
182 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 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#[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 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}