waft_widgets/widgets/navigator_pop_handler.rs
1//! Flutter counterpart: `widgets/navigator_pop_handler.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_foundation::{App, Handle};
7
8use crate::framework::{
9 BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
10};
11use crate::widgets::navigator::{NavigationNotification, RouteResult};
12use crate::widgets::notification_listener::NotificationListener;
13use crate::widgets::pop_scope::PopScope;
14
15/// A signature for a function that is passed the result of a `Route`.
16pub type PopResultCallback = Rc<dyn Fn(&mut App, RouteResult)>;
17
18/// Enables the handling of system back gestures.
19///
20/// Typically wraps a nested `Navigator` widget and allows it to handle system
21/// back gestures in the [`on_pop_with_result`](Self::on_pop_with_result) callback.
22///
23/// See also:
24///
25/// * [`PopScope`], which allows toggling the ability of a `Navigator` to
26/// handle pops.
27/// * [`NavigationNotification`], which indicates whether a `Navigator` in a
28/// subtree can handle pops.
29pub struct NavigatorPopHandler {
30 /// See `Widget::key`.
31 pub key: Option<KeyRef>,
32 /// The widget to place below this in the widget tree.
33 ///
34 /// Typically this is a `Navigator` that will handle the pop when
35 /// [`on_pop_with_result`](Self::on_pop_with_result) is called.
36 pub child: WidgetRef,
37 /// Whether this widget's ability to handle system back gestures is enabled or
38 /// disabled.
39 ///
40 /// When false, there will be no effect on system back gestures.
41 ///
42 /// This can be used, for example, when the nested `Navigator` is no longer
43 /// active but remains in the widget tree, such as in an inactive tab.
44 ///
45 /// Defaults to true.
46 pub enabled: bool,
47 /// Called when a handleable pop event happens.
48 ///
49 /// For example, a pop is handleable when a `Navigator` in
50 /// [`child`](Self::child) has multiple routes on its stack. It's not handleable when it
51 /// has only a single route, and so this is not called.
52 ///
53 /// Typically this is used to pop the `Navigator` in [`child`](Self::child).
54 ///
55 /// The passed `result` is the result of the popped `Route`.
56 pub on_pop_with_result: Option<PopResultCallback>,
57}
58
59impl NavigatorPopHandler {
60 /// Creates an instance of [`NavigatorPopHandler`]; Dart's optional arguments are the
61 /// setters.
62 ///
63 /// Dart's default: `enabled` true.
64 #[cfg_attr(debug_assertions, track_caller)]
65 pub fn new<K>(child: impl IntoWidget<K>) -> NavigatorPopHandler {
66 NavigatorPopHandler {
67 key: None,
68 child: child.into_widget(),
69 enabled: true,
70 on_pop_with_result: None,
71 }
72 }
73
74 /// Dart `NavigatorPopHandler(key:)`.
75 pub fn key(mut self, key: KeyRef) -> NavigatorPopHandler {
76 self.key = Some(key);
77 self
78 }
79
80 /// Dart `NavigatorPopHandler(enabled:)`.
81 pub fn enabled(mut self, enabled: bool) -> NavigatorPopHandler {
82 self.enabled = enabled;
83 self
84 }
85
86 /// Dart `NavigatorPopHandler(onPopWithResult:)`.
87 pub fn on_pop_with_result(
88 mut self,
89 on_pop_with_result: impl Fn(&mut App, RouteResult) + 'static,
90 ) -> NavigatorPopHandler {
91 self.on_pop_with_result = Some(Rc::new(on_pop_with_result));
92 self
93 }
94}
95
96impl Debug for NavigatorPopHandler {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.debug_struct("NavigatorPopHandler")
99 .field("enabled", &self.enabled)
100 .field("child", &self.child)
101 .finish_non_exhaustive()
102 }
103}
104
105impl StatefulWidget for NavigatorPopHandler {
106 type State = NavigatorPopHandlerState;
107
108 fn key(&self) -> Option<&KeyRef> {
109 self.key.as_ref()
110 }
111
112 fn create_state(&self) -> NavigatorPopHandlerState {
113 NavigatorPopHandlerState {
114 state: StateData::new(),
115 can_pop: true,
116 }
117 }
118}
119
120/// Dart's `_NavigatorPopHandlerState`.
121pub struct NavigatorPopHandlerState {
122 state: StateData<NavigatorPopHandler>,
123 can_pop: bool,
124}
125
126impl State for NavigatorPopHandlerState {
127 type Widget = NavigatorPopHandler;
128 crate::state_accessors!();
129
130 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
131 let enabled = self.widget(app).enabled;
132 let can_pop = app.get(self).can_pop;
133 let child = self.widget(app).child.clone();
134 // When the widget subtree indicates it can handle a pop, disable popping
135 // here, so that it can be manually handled in `can_pop`.
136 PopScope::new(
137 // Listen to changes in the navigation stack in the widget subtree.
138 NotificationListener::<NavigationNotification>::new(child)
139 .on_notification(move |app, notification: &NavigationNotification| {
140 // If this subtree cannot handle pop, then set `can_pop` to true so
141 // that our `PopScope` will allow the `Navigator` higher in the tree to
142 // handle the pop instead.
143 let next_can_pop = !notification.can_handle_pop;
144 if next_can_pop != app.get(self).can_pop {
145 self.set_state(app, |state| state.can_pop = next_can_pop);
146 }
147 false
148 })
149 .into_widget(),
150 )
151 .can_pop(!enabled || can_pop)
152 .on_pop_invoked_with_result(Rc::new(
153 move |app: &mut App, did_pop: bool, result: RouteResult| {
154 if did_pop {
155 return;
156 }
157 if let Some(on_pop_with_result) = self.widget(app).on_pop_with_result.clone() {
158 on_pop_with_result(app, result);
159 }
160 },
161 ))
162 .into_widget()
163 }
164}