Skip to main content

waft_material/compose/
three_pane_navigator.rs

1//! A Navigator whose pages follow an app's back stack and a three-pane scene strategy.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::rc::Rc;
6
7use waft_foundation::{App, Handle, ValueKey};
8use waft_widgets::{
9    BuildContext, GlobalKey, IntoWidget, KeyRef, Navigator, NavigatorPopHandler, NavigatorState,
10    PageRef, RouteEntry, RouteTransitionRecord, State, StateData, StatefulWidget,
11    TransitionDelegate, WidgetRef,
12};
13
14use crate::compose::{
15    ThreePaneScaffoldDestinationItem, ThreePaneScaffoldScene, ThreePaneSceneStrategy,
16};
17use crate::page::MaterialPage;
18
19/// Builds the page of its own for `back_stack[index]`.
20pub type ThreePaneEntryPageBuilder = Rc<dyn Fn(&mut App, BuildContext, usize) -> WidgetRef>;
21
22/// Builds the one page that holds a scene's [`ThreePaneScaffold`](crate::ThreePaneScaffold).
23pub type ThreePaneScenePageBuilder =
24    Rc<dyn Fn(&mut App, BuildContext, &ThreePaneScaffoldScene) -> WidgetRef>;
25
26/// Called with the length the back stack has after back, so the app truncates its stack.
27pub type ThreePaneBackStackTruncated = Rc<dyn Fn(&mut App, usize)>;
28
29/// Names the pane an app entry fills; `None` for an entry that is not a pane.
30pub type ThreePaneOf<E, K> = Rc<dyn Fn(&E) -> Option<ThreePaneScaffoldDestinationItem<K>>>;
31
32/// A [`Navigator`] whose pages follow an app's back stack, grouped by a [`ThreePaneSceneStrategy`].
33///
34/// Each entry before the scene is a page of its own, and one page holds the scene. With no scene
35/// every entry is its own page, so a phone's detail is an ordinary pushed page with the
36/// platform's back gestures. A page's key and name are the first back-stack index it shows, so a
37/// resize that splits a scene keeps the list's page; pages a resize adds or removes come and go
38/// without a transition.
39///
40/// The back stack stays the app's: every back, whether it leaves a page or only changes the
41/// panes of the scene, reaches the app as the length its stack should be truncated to. The
42/// navigator is nested in the app's, so it takes the system back first, through a
43/// [`NavigatorPopHandler`], while it has a page to pop.
44pub struct ThreePaneNavigator<E: 'static, K: PartialEq + 'static> {
45    /// The widget's key.
46    pub key: Option<KeyRef>,
47    /// The inner navigator's key; `None` uses one of the widget's own.
48    pub navigator_key: Option<GlobalKey>,
49    /// Which trailing entries share a page.
50    pub strategy: ThreePaneSceneStrategy,
51    /// The app's own back stack.
52    pub back_stack: Vec<E>,
53    /// The pane each entry fills, or `None` for an entry that is not a pane.
54    pub pane_of: ThreePaneOf<E, K>,
55    /// Builds the page of its own for an entry.
56    pub entry_page: ThreePaneEntryPageBuilder,
57    /// Builds the page that holds the scene.
58    pub scene_page: ThreePaneScenePageBuilder,
59    /// Called with the length the back stack has after back.
60    pub on_back_stack_truncated: ThreePaneBackStackTruncated,
61}
62
63impl<E: 'static, K: PartialEq + 'static> ThreePaneNavigator<E, K> {
64    /// Creates a navigator over the app's `back_stack`: `pane_of` names the pane each entry
65    /// fills (`None` for an entry that is not a pane), `entry_page` builds an entry's own page,
66    /// `scene_page` the page of the scene, and `on_back_stack_truncated` receives every back.
67    pub fn new(
68        strategy: ThreePaneSceneStrategy,
69        back_stack: Vec<E>,
70        pane_of: impl Fn(&E) -> Option<ThreePaneScaffoldDestinationItem<K>> + 'static,
71        entry_page: impl Fn(&mut App, BuildContext, usize) -> WidgetRef + 'static,
72        scene_page: impl Fn(&mut App, BuildContext, &ThreePaneScaffoldScene) -> WidgetRef + 'static,
73        on_back_stack_truncated: impl Fn(&mut App, usize) + 'static,
74    ) -> ThreePaneNavigator<E, K> {
75        ThreePaneNavigator {
76            key: None,
77            navigator_key: None,
78            strategy,
79            back_stack,
80            pane_of: Rc::new(pane_of),
81            entry_page: Rc::new(entry_page),
82            scene_page: Rc::new(scene_page),
83            on_back_stack_truncated: Rc::new(on_back_stack_truncated),
84        }
85    }
86
87    /// Sets the widget's key.
88    pub fn key(mut self, key: KeyRef) -> ThreePaneNavigator<E, K> {
89        self.key = Some(key);
90        self
91    }
92
93    /// Sets the inner navigator's key.
94    pub fn navigator_key(mut self, navigator_key: GlobalKey) -> ThreePaneNavigator<E, K> {
95        self.navigator_key = Some(navigator_key);
96        self
97    }
98
99    fn pane_stack(&self) -> Vec<Option<ThreePaneScaffoldDestinationItem<K>>> {
100        self.back_stack
101            .iter()
102            .map(|entry| (self.pane_of)(entry))
103            .collect()
104    }
105
106    fn pages(&self, app: &mut App, context: BuildContext) -> Vec<PageRef> {
107        let pane_stack = self.pane_stack();
108        match self.strategy.calculate_scene(&pane_stack) {
109            None => (0..self.back_stack.len())
110                .map(|index| self.build_entry_page(app, context, index))
111                .collect(),
112            Some(scene) => {
113                let mut pages: Vec<PageRef> = (0..scene.entries.start)
114                    .map(|index| self.build_entry_page(app, context, index))
115                    .collect();
116                pages.push(self.build_scene_page(app, context, &scene));
117                pages
118            }
119        }
120    }
121
122    fn build_entry_page(&self, app: &mut App, context: BuildContext, index: usize) -> PageRef {
123        let child = (self.entry_page)(app, context, index);
124        Rc::new(page_at(index, child))
125    }
126
127    /// The scene's page pops only when back leaves the scene; back inside it truncates the stack.
128    fn build_scene_page(
129        &self,
130        app: &mut App,
131        context: BuildContext,
132        scene: &ThreePaneScaffoldScene,
133    ) -> PageRef {
134        let child = (self.scene_page)(app, context, scene);
135        let page = page_at(scene.entries.start, child).can_pop(scene.previous_value.is_none());
136        if scene.previous_value.is_none() {
137            return Rc::new(page);
138        }
139        let len_after_back = scene.back_stack_len_after_back;
140        let on_back_stack_truncated = Rc::clone(&self.on_back_stack_truncated);
141        Rc::new(page.on_pop_invoked(Rc::new(move |app, did_pop, _result| {
142            if !did_pop {
143                on_back_stack_truncated(app, len_after_back);
144            }
145        })))
146    }
147}
148
149/// A page for the entries from `first_entry`: its key and name are that index.
150fn page_at(first_entry: usize, child: WidgetRef) -> MaterialPage {
151    MaterialPage::new(child)
152        .key(ValueKey::new(first_entry).into())
153        .name(first_entry.to_string())
154}
155
156/// The first back-stack index `page` shows, from its name.
157fn first_entry_of(page: &PageRef) -> Option<usize> {
158    page.name().and_then(|name| name.parse().ok())
159}
160
161impl<E: 'static, K: PartialEq + 'static> fmt::Debug for ThreePaneNavigator<E, K> {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.debug_struct("ThreePaneNavigator")
164            .field("key", &self.key)
165            .field("strategy", &self.strategy)
166            .field("back_stack_len", &self.back_stack.len())
167            .finish_non_exhaustive()
168    }
169}
170
171impl<E: 'static, K: PartialEq + 'static> StatefulWidget for ThreePaneNavigator<E, K> {
172    type State = ThreePaneNavigatorState<E, K>;
173
174    fn key(&self) -> Option<&KeyRef> {
175        self.key.as_ref()
176    }
177
178    fn create_state(&self) -> ThreePaneNavigatorState<E, K> {
179        ThreePaneNavigatorState {
180            state: StateData::new(),
181            own_navigator_key: GlobalKey::new(),
182            last_strategy: None,
183        }
184    }
185}
186
187/// The navigator's key, and the strategy of the last build: when it changes, the window
188/// regrouped the same entries.
189pub struct ThreePaneNavigatorState<E: 'static, K: PartialEq + 'static> {
190    state: StateData<ThreePaneNavigator<E, K>>,
191    own_navigator_key: GlobalKey,
192    last_strategy: Option<ThreePaneSceneStrategy>,
193}
194
195impl<E: 'static, K: PartialEq + 'static> State for ThreePaneNavigatorState<E, K> {
196    type Widget = ThreePaneNavigator<E, K>;
197    waft_widgets::state_accessors!();
198
199    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
200        let widget_ref = context.widget(app).clone();
201        let widget = waft_widgets::downcast_widget::<ThreePaneNavigator<E, K>>(&*widget_ref)
202            .expect("a ThreePaneNavigatorState builds its ThreePaneNavigator");
203        let regrouped = app.get(self).last_strategy.as_ref() != Some(&widget.strategy);
204        app.get_mut(self).last_strategy = Some(widget.strategy.clone());
205
206        let pages = widget.pages(app, context);
207        let on_back_stack_truncated = Rc::clone(&widget.on_back_stack_truncated);
208        let mut navigator = Navigator::new()
209            .pages(pages)
210            .on_did_remove_page(move |app, page| {
211                if let Some(first_entry) = first_entry_of(&page) {
212                    on_back_stack_truncated(app, first_entry);
213                }
214            });
215        if regrouped {
216            navigator = navigator.transition_delegate(Rc::new(RegroupTransitionDelegate));
217        }
218        let navigator_key = widget
219            .navigator_key
220            .clone()
221            .unwrap_or_else(|| app.get(self).own_navigator_key.clone());
222        NavigatorPopHandler::new(navigator.key(navigator_key.clone().into()))
223            .on_pop_with_result(move |app, _result| {
224                if let Some(navigator) = navigator_key.current_state::<NavigatorState>(app) {
225                    navigator.maybe_pop(app, None);
226                }
227            })
228            .into_widget()
229    }
230}
231
232/// Pages added or removed because the window regrouped the same back stack: they come and go
233/// without a transition, as they are not navigation.
234struct RegroupTransitionDelegate;
235
236impl TransitionDelegate for RegroupTransitionDelegate {
237    fn resolve(
238        &self,
239        app: &mut App,
240        new_page_route_history: &[Handle<RouteEntry>],
241        location_to_exiting_page_route: &HashMap<Option<Handle<RouteEntry>>, Handle<RouteEntry>>,
242        page_route_to_pageless_routes: &HashMap<
243            Option<Handle<RouteEntry>>,
244            Vec<Handle<RouteEntry>>,
245        >,
246    ) -> Vec<Handle<RouteEntry>> {
247        let mut results = Vec::new();
248        complete_exiting_routes(
249            app,
250            &mut results,
251            location_to_exiting_page_route,
252            page_route_to_pageless_routes,
253            None,
254        );
255        for page_route in new_page_route_history.iter().copied() {
256            if page_route.is_waiting_for_entering_decision(app) {
257                page_route.mark_for_add(app);
258            }
259            results.push(page_route);
260            complete_exiting_routes(
261                app,
262                &mut results,
263                location_to_exiting_page_route,
264                page_route_to_pageless_routes,
265                Some(page_route),
266            );
267        }
268        results
269    }
270}
271
272/// Completes, without a transition, the exiting routes above `location` and their pageless
273/// routes.
274fn complete_exiting_routes(
275    app: &mut App,
276    results: &mut Vec<Handle<RouteEntry>>,
277    location_to_exiting_page_route: &HashMap<Option<Handle<RouteEntry>>, Handle<RouteEntry>>,
278    page_route_to_pageless_routes: &HashMap<Option<Handle<RouteEntry>>, Vec<Handle<RouteEntry>>>,
279    location: Option<Handle<RouteEntry>>,
280) {
281    let Some(exiting_page_route) = location_to_exiting_page_route.get(&location).copied() else {
282        return;
283    };
284    complete(app, exiting_page_route);
285    for pageless_route in page_route_to_pageless_routes
286        .get(&Some(exiting_page_route))
287        .into_iter()
288        .flatten()
289    {
290        complete(app, *pageless_route);
291    }
292    results.push(exiting_page_route);
293    complete_exiting_routes(
294        app,
295        results,
296        location_to_exiting_page_route,
297        page_route_to_pageless_routes,
298        Some(exiting_page_route),
299    );
300}
301
302fn complete(app: &mut App, route: Handle<RouteEntry>) {
303    if route.is_waiting_for_exiting_decision(app) {
304        let result = route.route(app).current_result(app);
305        route.mark_for_complete(app, result);
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use std::cell::RefCell;
312
313    use waft_embedder::Size;
314    use waft_widgets::testing::{WidgetTester, find, test_widgets};
315    use waft_widgets::{
316        MediaQuery, MediaQueryData, StateSetter, StatefulBuilder, Text, WidgetsBinding,
317    };
318
319    use super::*;
320    use crate::compose::{
321        ListDetailPaneScaffoldRole, Pane, PaneScaffoldDirective, ThreePaneScaffold,
322        ThreePaneScaffoldDestinationItem, WindowSizeClass,
323    };
324    use crate::test_support::material_app;
325    use crate::theme_data::ThemeData;
326
327    type Stack = Rc<RefCell<Vec<Entry>>>;
328
329    /// One entry of the test app's own back stack.
330    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
331    enum Entry {
332        Home,
333        List,
334        Detail(i32),
335        Extra,
336    }
337
338    impl Entry {
339        fn pane(&self) -> Option<ThreePaneScaffoldDestinationItem<i32>> {
340            match *self {
341                Entry::Home => None,
342                Entry::List => Some(ThreePaneScaffoldDestinationItem::new(
343                    ListDetailPaneScaffoldRole::LIST,
344                    None,
345                )),
346                Entry::Detail(mail) => Some(ThreePaneScaffoldDestinationItem::new(
347                    ListDetailPaneScaffoldRole::DETAIL,
348                    Some(mail),
349                )),
350                Entry::Extra => Some(ThreePaneScaffoldDestinationItem::new(
351                    ListDetailPaneScaffoldRole::EXTRA,
352                    Some(9),
353                )),
354            }
355        }
356    }
357
358    fn list() -> Entry {
359        Entry::List
360    }
361
362    fn detail(mail: i32) -> Entry {
363        Entry::Detail(mail)
364    }
365
366    fn extra() -> Entry {
367        Entry::Extra
368    }
369
370    fn home() -> Entry {
371        Entry::Home
372    }
373
374    fn entry_widget(stack: &Stack, index: usize) -> WidgetRef {
375        let label = match stack.borrow()[index] {
376            Entry::List => "entry list",
377            Entry::Detail(_) => "entry detail",
378            Entry::Extra => "entry extra",
379            Entry::Home => "entry home",
380        };
381        Text::new(label).into_widget()
382    }
383
384    fn pane_widget(label: &'static str) -> Pane {
385        Pane::new(Text::new(label))
386    }
387
388    fn scene_widget(scene: &ThreePaneScaffoldScene) -> WidgetRef {
389        let mut scaffold = ThreePaneScaffold::list_detail(
390            scene.directive.clone(),
391            scene.value,
392            pane_widget("list pane"),
393            pane_widget("detail pane"),
394        );
395        if scene.entry_for(ListDetailPaneScaffoldRole::EXTRA).is_some() {
396            scaffold = scaffold.tertiary_pane(pane_widget("extra pane"));
397        }
398        scaffold.into_widget()
399    }
400
401    fn host(stack: Stack) -> impl Fn(&mut App, BuildContext, StateSetter) -> WidgetRef {
402        move |app: &mut App, context: BuildContext, set_state: StateSetter| {
403            let size_class = WindowSizeClass::of(app, context);
404            let strategy = ThreePaneSceneStrategy::list_detail(
405                PaneScaffoldDirective::from_window_size_class(size_class),
406            );
407            let stack_for_pages = Rc::clone(&stack);
408            let stack_for_truncate = Rc::clone(&stack);
409            ThreePaneNavigator::new(
410                strategy,
411                stack.borrow().clone(),
412                Entry::pane,
413                move |_app, _context, index| entry_widget(&stack_for_pages, index),
414                move |_app, _context, scene| scene_widget(scene),
415                move |app, len| {
416                    stack_for_truncate.borrow_mut().truncate(len);
417                    set_state(app, &mut |_app| {});
418                },
419            )
420            .into_widget()
421        }
422    }
423
424    fn pump(tester: &mut WidgetTester, size: Size, stack: Stack) {
425        tester.set_surface_size(Some(size));
426        let theme = ThemeData::new(&tester.cell.borrow());
427        let home = MediaQuery::new(
428            MediaQueryData::new().size(size),
429            StatefulBuilder::new(host(Rc::clone(&stack))),
430        );
431        tester.pump_widget(material_app(theme, home.into_widget()));
432    }
433
434    /// Pumps the first frame, and the one where the navigator's pop handler learns it can pop.
435    fn pump_first(tester: &mut WidgetTester, size: Size, stack: Stack) {
436        pump(tester, size, stack);
437        tester.pump();
438    }
439
440    /// The system back, as the engine's `popRoute` sends it.
441    fn system_back(tester: &mut WidgetTester) {
442        {
443            let mut app = tester.cell.borrow_mut();
444            let view = app.platform().views().first().expect("a view").id();
445            WidgetsBinding::instance(&mut app).handle_pop_route(&mut app, view);
446            app.drain_microtasks();
447        }
448        tester.pump_and_settle();
449    }
450
451    fn shown(tester: &WidgetTester, text: &str) -> bool {
452        !find::text(text).evaluate(tester).is_empty()
453    }
454
455    fn scaffolds(tester: &WidgetTester) -> usize {
456        find::by_type::<ThreePaneScaffold>().evaluate(tester).len()
457    }
458
459    #[test]
460    fn a_phone_shows_the_detail_as_its_own_page_and_back_pops_it() {
461        test_widgets(|tester| {
462            let stack: Stack = Rc::new(RefCell::new(vec![home(), list()]));
463            pump_first(tester, Size::new(400.0, 700.0), Rc::clone(&stack));
464            assert!(shown(tester, "entry list"));
465
466            stack.borrow_mut().push(detail(1));
467            pump(tester, Size::new(400.0, 700.0), Rc::clone(&stack));
468            assert!(
469                tester.pump_and_settle() > 1,
470                "the detail is pushed with a transition"
471            );
472            assert!(shown(tester, "entry detail"));
473            assert!(!shown(tester, "entry list"));
474            assert_eq!(scaffolds(tester), 0);
475
476            system_back(tester);
477            assert_eq!(stack.borrow().len(), 2);
478            assert!(shown(tester, "entry list"));
479        });
480    }
481
482    #[test]
483    fn a_wide_window_shows_the_list_and_detail_in_one_page_and_back_leaves_it() {
484        test_widgets(|tester| {
485            let stack: Stack = Rc::new(RefCell::new(vec![home(), list(), detail(1)]));
486            pump_first(tester, Size::new(1000.0, 700.0), Rc::clone(&stack));
487            assert!(shown(tester, "list pane"));
488            assert!(shown(tester, "detail pane"));
489            assert_eq!(scaffolds(tester), 1);
490            assert!(!shown(tester, "entry detail"));
491
492            system_back(tester);
493            assert_eq!(stack.borrow().len(), 1);
494            assert!(shown(tester, "entry home"));
495        });
496    }
497
498    #[test]
499    fn back_that_only_changes_the_panes_stays_in_the_scene_page() {
500        test_widgets(|tester| {
501            let stack: Stack = Rc::new(RefCell::new(vec![home(), list(), detail(1), extra()]));
502            pump_first(tester, Size::new(1000.0, 700.0), Rc::clone(&stack));
503            assert!(shown(tester, "extra pane"));
504
505            system_back(tester);
506            assert_eq!(stack.borrow().len(), 3);
507            assert_eq!(scaffolds(tester), 1);
508            assert!(!shown(tester, "extra pane"));
509            assert!(shown(tester, "list pane"));
510            assert!(shown(tester, "detail pane"));
511        });
512    }
513
514    #[test]
515    fn resizing_across_840_regroups_the_same_stack_without_a_transition() {
516        test_widgets(|tester| {
517            let stack: Stack = Rc::new(RefCell::new(vec![home(), list(), detail(1)]));
518            pump_first(tester, Size::new(839.0, 700.0), Rc::clone(&stack));
519            assert_eq!(scaffolds(tester), 0);
520            assert!(shown(tester, "entry detail"));
521
522            pump(tester, Size::new(840.0, 700.0), Rc::clone(&stack));
523            assert_eq!(
524                tester.pump_and_settle(),
525                1,
526                "the detail's page leaves at once"
527            );
528            assert_eq!(stack.borrow().len(), 3);
529            assert_eq!(scaffolds(tester), 1);
530            assert!(shown(tester, "list pane"));
531            assert!(!shown(tester, "entry detail"));
532
533            pump(tester, Size::new(839.0, 700.0), Rc::clone(&stack));
534            assert_eq!(
535                tester.pump_and_settle(),
536                1,
537                "the detail's page comes at once"
538            );
539            assert_eq!(stack.borrow().len(), 3);
540            assert_eq!(scaffolds(tester), 0);
541            assert!(shown(tester, "entry detail"));
542
543            system_back(tester);
544            assert_eq!(stack.borrow().len(), 2);
545            assert!(shown(tester, "entry list"));
546        });
547    }
548}