Skip to main content

waft_widgets/widgets/
pages.rs

1//! Flutter counterpart: `widgets/pages.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::AnimationRef;
8use waft_foundation::{App, Handle, HandleId, Retained};
9use waft_painting::Color;
10
11use crate::framework::{BuildContext, WidgetRef};
12use crate::widgets::navigator::{AnyRoute, Route, RouteData, RouteSettingsRef};
13use crate::widgets::routes::{
14    AnyModalRoute, AnyTransitionRoute, LocalHistoryRoute, LocalHistoryRouteData, ModalRoute,
15    ModalRouteData, OverlayRoute, OverlayRouteData, PredictiveBackRoute, RoutePageBuilder,
16    RouteTransitionsBuilder, TransitionRoute, TransitionRouteData,
17};
18use waft_foundation::Ref;
19
20/// The fields Dart's `PageRoute` declares; every page route carries this bag under the field
21/// `page_route`.
22pub struct PageRouteData {
23    /// Whether this page route is a full-screen dialog.
24    ///
25    /// In Material and Cupertino, being fullscreen has the effects of making the app bars have
26    /// a close button instead of a back button. On iOS, dialogs transitions animate differently
27    /// and are also not closeable with the back swipe gesture.
28    pub fullscreen_dialog: bool,
29    /// See [`TransitionRoute::allow_snapshotting`].
30    pub allow_snapshotting: bool,
31    /// See [`ModalRoute::barrier_dismissible`].
32    pub barrier_dismissible: bool,
33}
34
35impl PageRouteData {
36    /// The bag of a freshly created page route; Dart's constructor defaults.
37    pub fn new() -> PageRouteData {
38        PageRouteData {
39            fullscreen_dialog: false,
40            allow_snapshotting: true,
41            barrier_dismissible: false,
42        }
43    }
44}
45
46impl Default for PageRouteData {
47    fn default() -> PageRouteData {
48        PageRouteData::new()
49    }
50}
51
52/// The accessors [`PageRoute`] asks for, for a struct whose bag is the field `page_route`.
53#[macro_export]
54macro_rules! page_route_accessors {
55    () => {
56        fn page_route_data(
57            self: ::waft_foundation::Handle<Self>,
58            app: &::waft_foundation::App,
59        ) -> &$crate::PageRouteData {
60            &app.get(self).page_route
61        }
62
63        fn page_route_data_mut(
64            self: ::waft_foundation::Handle<Self>,
65            app: &mut ::waft_foundation::App,
66        ) -> &mut $crate::PageRouteData {
67            &mut app.get_mut(self).page_route
68        }
69    };
70}
71
72/// A modal route that replaces the entire screen.
73///
74/// [`PageRouteBuilder`] provides a way to create a [`PageRoute`] using callbacks rather than by
75/// defining a new type.
76///
77/// If [`barrier_dismissible`](ModalRoute::barrier_dismissible) is true, then pressing the
78/// escape key on the keyboard will cause the current route to be popped with no value.
79///
80/// See also:
81///
82///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
83pub trait PageRoute: ModalRoute {
84    /// Dart's `PageRoute` fields, held under the field `page_route`
85    /// ([`page_route_accessors!`](crate::page_route_accessors)).
86    fn page_route_data(self: Handle<Self>, app: &App) -> &PageRouteData;
87
88    /// See [`page_route_data`](Self::page_route_data).
89    fn page_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut PageRouteData;
90
91    /// This route as the erased [`AnyPageRoute`].
92    fn as_page_route(self: Handle<Self>) -> AnyPageRoute {
93        AnyPageRoute {
94            id: self.id(),
95            vtable: const { &PageRouteVTable::of::<Self>() },
96        }
97    }
98
99    /// Dart's `PageRoute.fullscreenDialog`.
100    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
101        self.page_route_data(app).fullscreen_dialog
102    }
103
104    /// Dart's `PageRoute.allowSnapshotting`.
105    fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
106        self.page_route_data(app).allow_snapshotting
107    }
108
109    /// Dart's `PageRoute.opaque`.
110    fn opaque(self: Handle<Self>, app: &App) -> bool {
111        let _ = app;
112        true
113    }
114
115    /// Dart's `PageRoute.barrierDismissible`.
116    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
117        self.page_route_data(app).barrier_dismissible
118    }
119
120    /// Dart's `PageRoute.canTransitionTo`.
121    fn can_transition_to(self: Handle<Self>, app: &App, next_route: AnyTransitionRoute) -> bool {
122        next_route.as_route().as_page_route(app).is_some()
123    }
124
125    /// Dart's `PageRoute.canTransitionFrom`.
126    fn can_transition_from(
127        self: Handle<Self>,
128        app: &App,
129        previous_route: AnyTransitionRoute,
130    ) -> bool {
131        previous_route.as_route().as_page_route(app).is_some()
132    }
133
134    /// Dart's `PageRoute.popGestureEnabled`.
135    fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool {
136        // Fullscreen dialogs aren't dismissible by back swipe.
137        !PageRoute::fullscreen_dialog(self, app) && ModalRoute::pop_gesture_enabled(self, app)
138    }
139}
140
141/// The vtable of an erased [`AnyPageRoute`].
142struct PageRouteVTable {
143    type_name: fn() -> &'static str,
144    route: fn(HandleId) -> AnyRoute,
145    modal_route: fn(HandleId) -> AnyModalRoute,
146}
147
148impl PageRouteVTable {
149    /// The table for one page route type.
150    const fn of<R: PageRoute>() -> PageRouteVTable {
151        PageRouteVTable {
152            type_name: std::any::type_name::<R>,
153            route: |id| Route::as_route(resolve::<R>(id)),
154            modal_route: |id| ModalRoute::as_modal_route(resolve::<R>(id)),
155        }
156    }
157}
158
159/// Erased [`PageRoute`]: what Dart's `route is PageRoute` produces.
160#[derive(Clone, Copy)]
161pub struct AnyPageRoute {
162    id: HandleId,
163    vtable: &'static PageRouteVTable,
164}
165
166/// A kept page route as a [`RouteRef`] or a [`ModalRouteRef`], through
167/// [`Retained::erase`]: Dart's upcast.
168impl From<AnyPageRoute> for AnyRoute {
169    fn from(route: AnyPageRoute) -> AnyRoute {
170        route.as_route()
171    }
172}
173
174impl From<AnyPageRoute> for AnyModalRoute {
175    fn from(route: AnyPageRoute) -> AnyModalRoute {
176        route.as_modal_route()
177    }
178}
179
180/// A field Dart types as the erased object, kept: AnyPageRoute with its count.
181pub type PageRouteRef = Retained<AnyPageRoute>;
182
183waft_foundation::erased_handle!(AnyPageRoute: PageRoute => PageRoute::as_page_route);
184
185impl Debug for AnyPageRoute {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
188    }
189}
190
191impl AnyPageRoute {
192    /// This page route as the erased [`AnyRoute`].
193    pub fn as_route(self) -> AnyRoute {
194        (self.vtable.route)(self.id)
195    }
196
197    /// This page route as the erased [`AnyModalRoute`].
198    pub fn as_modal_route(self) -> AnyModalRoute {
199        (self.vtable.modal_route)(self.id)
200    }
201}
202
203/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
204fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
205    Handle::from_id(id)
206}
207
208/// The `PredictiveBackRoute` implementation a [`PageRoute`] leaf inherits. Write it inside
209/// `impl PredictiveBackRoute for MyRoute { .. }`.
210#[macro_export]
211macro_rules! page_predictive_back_route_overrides {
212    () => {
213        $crate::modal_predictive_back_route_overrides!($crate::PageRoute::pop_gesture_enabled);
214    };
215}
216
217/// The `TransitionRoute` overrides a [`PageRoute`] leaf inherits, plus
218/// [`modal_transition_route_overrides!`](crate::modal_transition_route_overrides). Write it
219/// inside `impl TransitionRoute for MyRoute { .. }`, next to the leaf's own
220/// `transition_duration` and `opaque` (which a leaf that does not override it writes as
221/// `fn opaque(self: Handle<Self>, app: &App) -> bool { PageRoute::opaque(self, app) }`).
222#[macro_export]
223macro_rules! page_transition_route_overrides {
224    () => {
225        $crate::modal_transition_route_overrides!();
226
227        fn allow_snapshotting(
228            self: ::waft_foundation::Handle<Self>,
229            app: &::waft_foundation::App,
230        ) -> bool {
231            $crate::PageRoute::allow_snapshotting(self, app)
232        }
233
234        fn can_transition_to(
235            self: ::waft_foundation::Handle<Self>,
236            app: &::waft_foundation::App,
237            next_route: $crate::AnyTransitionRoute,
238        ) -> bool {
239            $crate::PageRoute::can_transition_to(self, app, next_route)
240        }
241
242        fn can_transition_from(
243            self: ::waft_foundation::Handle<Self>,
244            app: &::waft_foundation::App,
245            previous_route: $crate::AnyTransitionRoute,
246        ) -> bool {
247            $crate::PageRoute::can_transition_from(self, app, previous_route)
248        }
249    };
250}
251
252/// The `Route` overrides a [`PageRoute`] leaf inherits, plus
253/// [`modal_route_overrides!`](crate::modal_route_overrides). Write it inside
254/// `impl Route for MyRoute { .. }`.
255#[macro_export]
256macro_rules! page_route_overrides {
257    () => {
258        $crate::modal_route_overrides!();
259
260        fn as_page_route(
261            self: ::waft_foundation::Handle<Self>,
262        ) -> ::std::option::Option<$crate::AnyPageRoute> {
263            ::std::option::Option::Some($crate::PageRoute::as_page_route(self))
264        }
265    };
266}
267
268/// Dart's `_defaultTransitionsBuilder`: a jump cut.
269fn default_transitions_builder(
270    _app: &mut App,
271    _context: BuildContext,
272    _animation: AnimationRef<f64>,
273    _secondary_animation: AnimationRef<f64>,
274    child: WidgetRef,
275) -> WidgetRef {
276    child
277}
278
279/// A utility type for defining one-off page routes in terms of callbacks.
280///
281/// Callers must define the [`page_builder`](Self::page_builder) function which creates the
282/// route's primary contents. To add transitions define the
283/// [`transitions_builder`](Self::transitions_builder) function.
284///
285/// See also:
286///
287///  * [`Route`], which documents the meaning of Dart's `T` generic type argument.
288pub struct PageRouteBuilder {
289    route: RouteData,
290    overlay_route: OverlayRouteData,
291    transition_route: TransitionRouteData,
292    local_history: LocalHistoryRouteData,
293    modal_route: ModalRouteData,
294    page_route: PageRouteData,
295    /// Used to build the route's primary contents.
296    ///
297    /// See [`ModalRoute::build_page`] for the complete definition of the parameters.
298    pub page_builder: RoutePageBuilder,
299    /// Used to build the route's transitions.
300    ///
301    /// The `animation` argument drives this route's own entrance and exit transition. The
302    /// `secondary_animation` argument drives transitions for this route when another route is
303    /// pushed on top of it or popped from above it, if both routes allow transition
304    /// coordination. See [`TransitionRoute::can_transition_to`] and
305    /// [`TransitionRoute::can_transition_from`].
306    ///
307    /// The default transition is a jump cut (i.e. no animation).
308    pub transitions_builder: RouteTransitionsBuilder,
309    transition_duration: Duration,
310    reverse_transition_duration: Duration,
311    opaque: bool,
312    barrier_dismissible: bool,
313    barrier_color: Option<Color>,
314    barrier_label: Option<String>,
315    maintain_state: bool,
316}
317
318impl PageRouteBuilder {
319    /// Creates a route that delegates to builder callbacks; Dart's optional arguments are the
320    /// setters.
321    ///
322    /// Dart's defaults: `transitions_builder` a jump cut, `transition_duration` and
323    /// `reverse_transition_duration` 300 ms, `opaque` true, `barrier_dismissible` false,
324    /// `maintain_state` true, `fullscreen_dialog` false, `allow_snapshotting` true.
325    pub fn new(app: &mut App, page_builder: RoutePageBuilder) -> Ref<PageRouteBuilder> {
326        let route = RouteData::new(app, None, None);
327        let transition_route = TransitionRouteData::new(app);
328        let modal_route = ModalRouteData::new(app);
329        app.create(PageRouteBuilder {
330            route,
331            overlay_route: OverlayRouteData::new(),
332            transition_route,
333            local_history: LocalHistoryRouteData::new(),
334            modal_route,
335            page_route: PageRouteData::new(),
336            page_builder,
337            transitions_builder: Rc::new(default_transitions_builder),
338            transition_duration: Duration::from_millis(300),
339            reverse_transition_duration: Duration::from_millis(300),
340            opaque: true,
341            barrier_dismissible: false,
342            barrier_color: None,
343            barrier_label: None,
344            maintain_state: true,
345        })
346    }
347
348    /// Dart `PageRouteBuilder(settings:)`.
349    pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
350        self.route_data_mut(app).set_settings(settings);
351        self
352    }
353
354    /// Dart `PageRouteBuilder(requestFocus:)`.
355    pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
356        self.route_data_mut(app)
357            .set_request_focus(Some(request_focus));
358        self
359    }
360
361    /// Dart `PageRouteBuilder(transitionsBuilder:)`.
362    pub fn transitions_builder(
363        self: Ref<Self>,
364        app: &mut App,
365        transitions_builder: RouteTransitionsBuilder,
366    ) -> Ref<Self> {
367        app.get_mut(&self).transitions_builder = transitions_builder;
368        self
369    }
370
371    /// Dart `PageRouteBuilder(transitionDuration:)`.
372    pub fn transition_duration(
373        self: Ref<Self>,
374        app: &mut App,
375        transition_duration: Duration,
376    ) -> Ref<Self> {
377        app.get_mut(&self).transition_duration = transition_duration;
378        self
379    }
380
381    /// Dart `PageRouteBuilder(reverseTransitionDuration:)`.
382    pub fn reverse_transition_duration(
383        self: Ref<Self>,
384        app: &mut App,
385        reverse_transition_duration: Duration,
386    ) -> Ref<Self> {
387        app.get_mut(&self).reverse_transition_duration = reverse_transition_duration;
388        self
389    }
390
391    /// Dart `PageRouteBuilder(opaque:)`.
392    pub fn opaque(self: Ref<Self>, app: &mut App, opaque: bool) -> Ref<Self> {
393        app.get_mut(&self).opaque = opaque;
394        self
395    }
396
397    /// Dart `PageRouteBuilder(barrierDismissible:)`.
398    pub fn barrier_dismissible(
399        self: Ref<Self>,
400        app: &mut App,
401        barrier_dismissible: bool,
402    ) -> Ref<Self> {
403        app.get_mut(&self).barrier_dismissible = barrier_dismissible;
404        self
405    }
406
407    /// Dart `PageRouteBuilder(barrierColor:)`.
408    pub fn barrier_color(self: Ref<Self>, app: &mut App, barrier_color: Color) -> Ref<Self> {
409        app.get_mut(&self).barrier_color = Some(barrier_color);
410        self
411    }
412
413    /// Dart `PageRouteBuilder(barrierLabel:)`.
414    pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
415        app.get_mut(&self).barrier_label = Some(barrier_label);
416        self
417    }
418
419    /// Dart `PageRouteBuilder(maintainState:)`.
420    pub fn maintain_state(self: Ref<Self>, app: &mut App, maintain_state: bool) -> Ref<Self> {
421        app.get_mut(&self).maintain_state = maintain_state;
422        self
423    }
424
425    /// Dart `PageRouteBuilder(fullscreenDialog:)`.
426    pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
427        self.page_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
428        self
429    }
430
431    /// Dart `PageRouteBuilder(allowSnapshotting:)`.
432    pub fn allow_snapshotting(
433        self: Ref<Self>,
434        app: &mut App,
435        allow_snapshotting: bool,
436    ) -> Ref<Self> {
437        self.page_route_data_mut(app).allow_snapshotting = allow_snapshotting;
438        self
439    }
440}
441
442impl Route for PageRouteBuilder {
443    crate::page_route_overrides!();
444}
445
446impl OverlayRoute for PageRouteBuilder {
447    crate::modal_overlay_route_overrides!();
448}
449
450impl PredictiveBackRoute for PageRouteBuilder {
451    crate::page_predictive_back_route_overrides!();
452}
453
454impl TransitionRoute for PageRouteBuilder {
455    crate::page_transition_route_overrides!();
456
457    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
458        app.get(self).transition_duration
459    }
460
461    fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
462        app.get(self).reverse_transition_duration
463    }
464
465    fn opaque(self: Handle<Self>, app: &App) -> bool {
466        app.get(self).opaque
467    }
468}
469
470impl LocalHistoryRoute for PageRouteBuilder {
471    crate::local_history_route_accessors!();
472}
473
474impl ModalRoute for PageRouteBuilder {
475    crate::modal_route_accessors!();
476
477    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
478        app.get(self).barrier_dismissible
479    }
480
481    fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
482        app.get(self).barrier_color
483    }
484
485    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
486        app.get(self).barrier_label.clone()
487    }
488
489    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
490        app.get(self).maintain_state
491    }
492
493    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
494        PageRoute::fullscreen_dialog(self, app)
495    }
496
497    fn build_page(
498        self: Handle<Self>,
499        app: &mut App,
500        context: BuildContext,
501        animation: AnimationRef<f64>,
502        secondary_animation: AnimationRef<f64>,
503    ) -> WidgetRef {
504        let page_builder = Rc::clone(&app.get(self).page_builder);
505        page_builder(app, context, animation, secondary_animation)
506    }
507
508    fn build_transitions(
509        self: Handle<Self>,
510        app: &mut App,
511        context: BuildContext,
512        animation: AnimationRef<f64>,
513        secondary_animation: AnimationRef<f64>,
514        child: WidgetRef,
515    ) -> WidgetRef {
516        let transitions_builder = Rc::clone(&app.get(self).transitions_builder);
517        transitions_builder(app, context, animation, secondary_animation, child)
518    }
519}
520
521impl PageRoute for PageRouteBuilder {
522    crate::page_route_accessors!();
523}