ltk/nav_stack.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! [`NavStack`]: the navigation state of a multi-screen app.
use serde::{ Deserialize, Serialize };
use crate::app::BackResponse;
/// The screens the user went through to get where they are, root first.
///
/// A plain value the app keeps in its model — the runtime never sees it.
/// It exists so the two things that must agree are one object: what
/// [`App::on_back`](crate::App::on_back) walks and what
/// [`App::save_state`](crate::App::save_state) persists. It serialises
/// whenever the route type does, and it is never empty: there is always a
/// root to fall back to, including after deserialising.
///
/// ```rust
/// use ltk::{ App, BackResponse, Element, NavStack, text };
/// use serde::{ Deserialize, Serialize };
///
/// #[ derive( Clone, PartialEq, Serialize, Deserialize ) ]
/// enum Route { Inbox, Thread( u64 ), Settings }
///
/// #[ derive( Clone ) ]
/// enum Msg { Open( Route ), Back }
///
/// struct Mail { nav: NavStack<Route> }
///
/// impl App for Mail
/// {
/// type Message = Msg;
///
/// fn app_id( &self ) -> &str { "net.example.Mail" }
///
/// fn view( &self ) -> Element<Msg>
/// {
/// let screen = match self.nav.current()
/// {
/// Route::Inbox => text( "inbox" ),
/// Route::Thread( id ) => text( format!( "thread {id}" ) ),
/// Route::Settings => text( "settings" ),
/// };
/// screen.into()
/// }
///
/// fn update( &mut self, msg: Msg )
/// {
/// match msg
/// {
/// Msg::Open( route ) => self.nav.push( route ),
/// Msg::Back => { self.nav.pop(); }
/// }
/// }
///
/// fn on_back( &mut self ) -> BackResponse<Msg> { self.nav.back( Msg::Back ) }
///
/// fn save_state( &self ) -> Option<Vec<u8>> { serde_json::to_vec( &self.nav ).ok() }
///
/// fn restore_state( &mut self, state: Vec<u8> )
/// {
/// if let Ok( nav ) = serde_json::from_slice( &state ) { self.nav = nav; }
/// }
/// }
/// ```
#[ derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize ) ]
pub struct NavStack<R>
{
root: R,
above: Vec<R>,
}
impl<R> NavStack<R>
{
pub fn new( root: R ) -> Self
{
Self { root, above: Vec::new() }
}
/// The route on screen.
pub fn current( &self ) -> &R
{
self.above.last().unwrap_or( &self.root )
}
pub fn current_mut( &mut self ) -> &mut R
{
self.above.last_mut().unwrap_or( &mut self.root )
}
/// Go to `route`, keeping the current one underneath.
pub fn push( &mut self, route: R )
{
self.above.push( route );
}
/// Go back one route. `None` at the root, which stays.
pub fn pop( &mut self ) -> Option<R>
{
self.above.pop()
}
/// Swap the current route for `route` without growing the stack — a
/// sideways move (tab to tab, step to step) back should not retrace.
/// Returns the route it replaced.
pub fn replace( &mut self, route: R ) -> R
{
std::mem::replace( self.current_mut(), route )
}
pub fn pop_to_root( &mut self )
{
self.above.clear();
}
/// Start over from a new root.
pub fn reset( &mut self, root: R )
{
self.root = root;
self.above.clear();
}
pub fn can_pop( &self ) -> bool
{
!self.above.is_empty()
}
/// Number of routes, the root included.
pub fn depth( &self ) -> usize
{
self.above.len() + 1
}
/// Routes from the root up to the current one.
pub fn iter( &self ) -> impl Iterator<Item = &R>
{
std::iter::once( &self.root ).chain( self.above.iter() )
}
/// The answer for [`App::on_back`](crate::App::on_back): `pop` when
/// there is a route to go back to, [`BackResponse::Unhandled`] at the
/// root. `pop` is the app's message that ends up calling [`Self::pop`].
pub fn back<M>( &self, pop: M ) -> BackResponse<M>
{
if self.can_pop() { BackResponse::Message( pop ) } else { BackResponse::Unhandled }
}
}
#[ cfg( test ) ]
mod tests
{
use super::*;
#[ test ]
fn push_and_pop_walk_the_routes()
{
let mut nav = NavStack::new( "inbox" );
nav.push( "thread" );
nav.push( "attachment" );
assert_eq!( *nav.current(), "attachment" );
assert_eq!( nav.depth(), 3 );
assert_eq!( nav.pop(), Some( "attachment" ) );
assert_eq!( *nav.current(), "thread" );
}
#[ test ]
fn the_root_cannot_be_popped()
{
let mut nav = NavStack::new( "inbox" );
assert!( !nav.can_pop() );
assert_eq!( nav.pop(), None );
assert_eq!( *nav.current(), "inbox" );
}
#[ test ]
fn replace_is_a_sideways_move()
{
let mut nav = NavStack::new( "inbox" );
nav.push( "general" );
assert_eq!( nav.replace( "network" ), "general" );
assert_eq!( nav.depth(), 2 );
nav.pop();
assert_eq!( *nav.current(), "inbox" );
let mut root_only = NavStack::new( "a" );
root_only.replace( "b" );
assert_eq!( *root_only.current(), "b" );
assert!( !root_only.can_pop() );
}
#[ test ]
fn back_is_unhandled_only_at_the_root()
{
let mut nav = NavStack::new( 0 );
assert_eq!( nav.back( "pop" ), BackResponse::Unhandled );
nav.push( 1 );
assert_eq!( nav.back( "pop" ), BackResponse::Message( "pop" ) );
}
#[ test ]
fn reset_and_pop_to_root()
{
let mut nav = NavStack::new( 0 );
nav.push( 1 );
nav.push( 2 );
nav.pop_to_root();
assert_eq!( nav.iter().copied().collect::<Vec<_>>(), vec![ 0 ] );
nav.push( 1 );
nav.reset( 9 );
assert_eq!( nav.iter().copied().collect::<Vec<_>>(), vec![ 9 ] );
}
#[ test ]
fn survives_a_serde_round_trip()
{
let mut nav = NavStack::new( "inbox".to_string() );
nav.push( "thread".to_string() );
let bytes = serde_json::to_vec( &nav ).unwrap();
let restored: NavStack<String> = serde_json::from_slice( &bytes ).unwrap();
assert_eq!( restored, nav );
assert!( restored.can_pop() );
}
}