Skip to main content

waft_widgets/widgets/
pop_scope.rs

1//! Flutter counterpart: `widgets/pop_scope.dart`.
2
3use crate::widgets::routes::ModalRouteRef;
4use std::rc::Rc;
5
6use waft_foundation::{App, Handle, OptionRetained, ValueListenable, ValueNotifier};
7
8use crate::framework::{
9    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
10};
11use crate::widgets::navigator::RouteResult;
12use crate::widgets::routes::{
13    AnyModalRoute, PopEntry, PopEntryObject, PopInvokedWithResultCallback,
14};
15use waft_foundation::Ref;
16
17/// Manages back navigation gestures.
18///
19/// The [`can_pop`](Self::can_pop) parameter disables back gestures when set to false.
20///
21/// The [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result) parameter reports when
22/// pop navigation was attempted, and `did_pop` indicates whether or not the navigation was
23/// successful. The `result` contains the pop result.
24///
25/// Android has a system back gesture that is a swipe inward from near the edge of the screen.
26/// It is recognized by Android before being passed to Flutter.
27///
28/// If [`can_pop`](Self::can_pop) is false, then a system back gesture will not pop the route
29/// off of the enclosing `Navigator`.
30/// [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result) will still be called, and
31/// `did_pop` will be false. Programmatically attempting pop navigation will also result in a
32/// call to [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result), with `did_pop`
33/// indicating success or failure.
34///
35/// If [`can_pop`](Self::can_pop) is true, then a system back gesture will cause the enclosing
36/// `Navigator` to receive a pop as usual.
37/// [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result) will be called with
38/// `did_pop` as true, unless the pop failed for reasons unrelated to [`PopScope`], in which
39/// case it will be false.
40///
41/// See also:
42///
43///  * [`ModalRoute::register_pop_entry`](crate::ModalRoute::register_pop_entry) and
44///    [`ModalRoute::unregister_pop_entry`](crate::ModalRoute::unregister_pop_entry), which this
45///    widget uses to integrate with the navigation system.
46pub struct PopScope {
47    pub key: Option<KeyRef>,
48    /// The widget below this widget in the tree.
49    pub child: WidgetRef,
50    /// Called after a route pop was handled.
51    ///
52    /// It's not possible to prevent the pop from happening at the time that this callback is
53    /// called; the pop has already happened. Use [`can_pop`](Self::can_pop) to disable pops in
54    /// advance.
55    ///
56    /// This will still be called even when the pop is canceled. A pop is canceled when the
57    /// relevant [`Route::pop_disposition`](crate::Route::pop_disposition) reports
58    /// [`RoutePopDisposition::DoNotPop`](crate::RoutePopDisposition::DoNotPop), such as when
59    /// [`can_pop`](Self::can_pop) is set to false on a [`PopScope`]. The `did_pop` parameter
60    /// indicates whether or not the back navigation actually happened successfully.
61    ///
62    /// The `result` contains the pop result.
63    pub on_pop_invoked_with_result: Option<PopInvokedWithResultCallback>,
64    /// When false, blocks the current route from being popped.
65    ///
66    /// This includes the root route, where upon popping, the app would exit.
67    ///
68    /// If multiple [`PopScope`] widgets appear in a route's widget subtree, then each and every
69    /// `can_pop` must be true in order for the route to be able to pop.
70    pub can_pop: bool,
71}
72
73impl PopScope {
74    /// Creates a widget that registers a callback to veto attempts by the user to dismiss the
75    /// enclosing [`ModalRoute`](crate::ModalRoute); Dart's optional arguments are the setters.
76    ///
77    /// Dart's default: `can_pop` true.
78    #[cfg_attr(debug_assertions, track_caller)]
79    pub fn new<K>(child: impl IntoWidget<K>) -> PopScope {
80        PopScope {
81            key: None,
82            child: child.into_widget(),
83            on_pop_invoked_with_result: None,
84            can_pop: true,
85        }
86    }
87
88    /// Dart `PopScope(key:)`.
89    pub fn key(mut self, key: KeyRef) -> PopScope {
90        self.key = Some(key);
91        self
92    }
93
94    /// Dart `PopScope(onPopInvokedWithResult:)`.
95    pub fn on_pop_invoked_with_result(
96        mut self,
97        on_pop_invoked_with_result: PopInvokedWithResultCallback,
98    ) -> PopScope {
99        self.on_pop_invoked_with_result = Some(on_pop_invoked_with_result);
100        self
101    }
102
103    /// Dart `PopScope(canPop:)`.
104    pub fn can_pop(mut self, can_pop: bool) -> PopScope {
105        self.can_pop = can_pop;
106        self
107    }
108
109    /// Dart's `_callPopInvoked`, as a closure the caller runs once it has released the arena.
110    fn pop_invocation(&self, did_pop: bool, result: RouteResult) -> impl FnOnce(&mut App) + use<> {
111        let callback = self.on_pop_invoked_with_result.clone();
112        move |app: &mut App| {
113            if let Some(callback) = callback {
114                callback(app, did_pop, result);
115            }
116        }
117    }
118}
119
120impl std::fmt::Debug for PopScope {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("PopScope")
123            .field("can_pop", &self.can_pop)
124            .finish_non_exhaustive()
125    }
126}
127
128impl StatefulWidget for PopScope {
129    type State = PopScopeState;
130
131    fn key(&self) -> Option<&KeyRef> {
132        self.key.as_ref()
133    }
134
135    fn create_state(&self) -> PopScopeState {
136        PopScopeState {
137            state: StateData::new(),
138            route: None,
139            can_pop_notifier: None,
140            pop_entry: None,
141        }
142    }
143}
144
145/// Dart's `_PopScopeState`.
146pub struct PopScopeState {
147    state: StateData<PopScope>,
148    route: Option<ModalRouteRef>,
149    can_pop_notifier: Option<Ref<ValueNotifier<bool>>>,
150    /// This state as the `PopEntry` it registers, minted once in `init_state`: the route
151    /// unregisters by identity, and Dart passes `this`.
152    pop_entry: Option<Rc<dyn PopEntry>>,
153}
154
155impl PopScopeState {
156    fn pop_entry(self: Handle<Self>, app: &App) -> Rc<dyn PopEntry> {
157        Rc::clone(
158            app.get(self)
159                .pop_entry
160                .as_ref()
161                .expect("init_state has run"),
162        )
163    }
164}
165
166impl PopEntryObject for PopScopeState {
167    fn on_pop_invoked_with_result(
168        self: Handle<Self>,
169        app: &mut App,
170        did_pop: bool,
171        result: RouteResult,
172    ) {
173        // The widget's callback is taken out of the arena before it can re-enter it.
174        let call = self.widget(app).pop_invocation(did_pop, result);
175        call(app);
176    }
177
178    fn can_pop_notifier(self: Handle<Self>, app: &App) -> Rc<dyn ValueListenable<bool>> {
179        Rc::new(
180            app.get(self)
181                .can_pop_notifier
182                .clone()
183                .expect("init_state has run"),
184        )
185    }
186}
187
188impl State for PopScopeState {
189    type Widget = PopScope;
190    crate::state_accessors!();
191
192    fn init_state(self: Handle<Self>, app: &mut App) {
193        let can_pop = self.widget(app).can_pop;
194        app.get_mut(self).can_pop_notifier = Some(app.create(ValueNotifier::new(can_pop)));
195        app.get_mut(self).pop_entry = Some(Rc::new(self));
196    }
197
198    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
199        let context = self.context(app);
200        let next_route = AnyModalRoute::of(app, context);
201        if next_route != app.get(self).route.handle() {
202            if let Some(route) = app.get(self).route.handle() {
203                route.unregister_pop_entry(app, self.pop_entry(app));
204            }
205            app.get_mut(self).route = next_route.and_then(|route| route.upgrade(app));
206            if let Some(route) = next_route {
207                route.register_pop_entry(app, self.pop_entry(app));
208            }
209        }
210    }
211
212    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &PopScope) {
213        let can_pop = self.widget(app).can_pop;
214        let notifier = app
215            .get(self)
216            .can_pop_notifier
217            .handle()
218            .expect("init_state has run");
219        notifier.set_value(app, can_pop);
220    }
221
222    fn dispose(self: Handle<Self>, app: &mut App) {
223        if let Some(route) = app.get(self).route.handle() {
224            route.unregister_pop_entry(app, self.pop_entry(app));
225        }
226        let notifier = app
227            .get(self)
228            .can_pop_notifier
229            .handle()
230            .expect("init_state has run");
231        notifier.dispose(app);
232    }
233
234    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
235        self.widget(app).child.clone()
236    }
237}