day_core/nav.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Route registry (docs/navigation.md): every mounted `nav()` / `nav_stack()` host
5//! register a controller here. Registrations form a stack so hosts can nest (e.g. a `tabs()`
6//! inside a `nav()` route), and the stack order is the nesting order (outermost first).
7//!
8//! Two addressing modes (docs/navigation.md):
9//! * A single key (`navigate("inbox")`) is relative: tried innermost-first, falling through
10//! outward. A tab key selects the tab; a key the tabs host doesn't know still resolves
11//! against the enclosing surface.
12//! * A `/`-separated path (`navigate("mail/inbox/msg-42")`) is absolute: the first segment
13//! anchors at the outermost surface that recognizes it, every surface inside the anchor is
14//! reset to its root, and the remaining segments are consumed inward, including by
15//! surfaces that only mount as the outer switch takes effect (a pending queue hands each
16//! newly registered surface the next segment).
17//!
18//! A trailing `?name=value&…` query carries [`route_params`] to the destination builders.
19//! [`current_route`] reports the full path (every mounted surface's contribution, outermost
20//! to innermost), so persisting navigation is `save(current_route())` + `navigate(&saved)`.
21
22use std::cell::{Cell, RefCell};
23use std::rc::Rc;
24
25/// A mounted host's control surface. Closures run user code (route builders), so the registry
26/// Never holds a borrow across a call (§3.3 discipline: clone the `Rc` out, then call).
27pub struct NavController {
28 /// Push (or, in split/tab presentation, select) a registered route. False = unknown route.
29 pub push: Box<dyn Fn(&str) -> bool>,
30 /// Pop the top route. `already_popped` = the native side popped first (iOS back).
31 /// False = nothing to pop (tabs hosts always return false: they have no stack).
32 pub pop: Box<dyn Fn(bool) -> bool>,
33 /// Current route path ("" while showing the root).
34 pub current: Box<dyn Fn() -> String>,
35 /// Consume one segment of an absolute path. Selectors/tabs accept a declared key (same as
36 /// `push`); a `nav_stack` accepts any segment by pushing it (its destinations are open-ended).
37 /// Distinct from `push` so a relative `navigate("key")` can still fall through a stack.
38 pub enter: Box<dyn Fn(&str) -> bool>,
39 /// This surface's contribution to the full route: `[]` at root, `[key]` for a nav host /
40 /// tabs, the whole path for a stack.
41 pub segments: Box<dyn Fn() -> Vec<String>>,
42 /// How deeply this surface is nested: 0 for one mounted at the window root, 1 for one built
43 /// inside another surface's page, and so on.
44 ///
45 /// An absolute path walks outermost-inward, and registration order is not that order: a
46 /// nav host builds its pages before registering itself, so a stack inside a page registers
47 /// first. Ordering the descent by depth instead of by position is what lets `section/detail`
48 /// find the stack no matter which of the two registered first.
49 pub depth: usize,
50 /// Presentation order of the containing fullscreen cover; zero for ordinary pages.
51 /// A cover and its descendants receive Back before navigation underneath it.
52 pub layer: Box<dyn Fn() -> u64>,
53 /// Whether this surface is on screen: false for one sitting inside a resident page its host
54 /// is not currently showing.
55 ///
56 /// A tab bar or a rail keeps every page it has built alive (docs/navigation.md), so the nav
57 /// surfaces inside the tabs the user is not looking at stay registered. Without this they
58 /// contribute their segments to [`current_route`] just like the visible ones, and the route
59 /// reads as the concatenation of every tab's state. Registration cannot answer the question
60 /// once and for all (which page is showing changes after the build), so it is a predicate.
61 pub active: Box<dyn Fn() -> bool>,
62}
63
64/// Opaque handle from [`register_nav`]; a nested host calls [`unregister_nav`] on dispose.
65#[derive(Clone, Copy, PartialEq, Eq, Debug)]
66pub struct NavToken(u64);
67
68/// An app-level Back handler: Jetpack Compose's `BackHandler(enabled) { … }`
69/// (docs/navigation.md "Handling the system Back"). Registered with [`register_back_handler`]
70/// by `Decorate::on_system_back`; removed with [`unregister_nav`].
71///
72/// A handler is the last thing a back reaches. Every navigation surface answers first (a
73/// presented cover closes, a pushed page pops, a guard decides), and only a back none of them
74/// takes runs a handler, in place of the platform's default (leaving the app). Among handlers
75/// that are on screen and enabled, the one in the topmost cover wins, then the one nested most
76/// deeply in the piece tree (the most ancestors above [`Self::node`]), then the most recently
77/// registered.
78pub struct BackHandler {
79 /// The node the handler's piece is built under. Its depth in the tree, read when a back
80 /// arrives rather than at registration (a document page can move to a window of its own),
81 /// is what makes an inner handler win over an outer one, whichever mounted first.
82 pub node: crate::RNode,
83 /// Presentation order of the containing cover, like [`NavController::layer`].
84 pub layer: Box<dyn Fn() -> u64>,
85 /// Whether the handler is on screen, like [`NavController::active`]: false inside a resident
86 /// page its host is not showing.
87 pub active: Box<dyn Fn() -> bool>,
88 /// The app's condition: whether the handler wants the back right now. Read untracked; the
89 /// caller re-runs [`sync_system_back`] when it changes.
90 pub enabled: Box<dyn Fn() -> bool>,
91 /// What a back the handler takes does.
92 pub run: Box<dyn Fn()>,
93}
94
95day_reactive::tls_slots! {
96 nav;
97 static NAV_STACK: RefCell<Vec<(NavToken, Rc<NavController>)>> =
98 const { RefCell::new(Vec::new()) };
99 /// Surfaces consulted only when every mounted one refuses a route ([`register_nav_fallback`]).
100 static FALLBACK_NAV: RefCell<Vec<(NavToken, Rc<NavController>)>> =
101 const { RefCell::new(Vec::new()) };
102 static NEXT_TOKEN: Cell<u64> = const { Cell::new(1) };
103 /// The app's Back handlers ([`register_back_handler`]), in registration order.
104 static BACK_HANDLERS: RefCell<Vec<(NavToken, Rc<BackHandler>)>> =
105 const { RefCell::new(Vec::new()) };
106 /// What the toolkit was last told by [`sync_system_back`]: whether the system back is armed.
107 static BACK_ARMED: Cell<bool> = const { Cell::new(false) };
108 /// A launch deep link recorded by the platform entry before `launch_with` runs: the entry
109 /// point for hosts with no process environment (web-dom seeds it from the page's URL hash). The
110 /// `DAY_DEEPLINK` environment variable, where one exists, still wins.
111 static LAUNCH_DEEPLINK: RefCell<Option<String>> = const { RefCell::new(None) };
112 /// Query params of the most recent `navigate()` (empty between navigations). Destination
113 /// builders read them via [`route_params`] while their route is being entered.
114 static PARAMS: RefCell<Rc<Vec<(String, String)>>> = RefCell::new(Rc::new(Vec::new()));
115 /// Absolute-path segments not yet consumed: surfaces that mount during the navigation
116 /// cascade take the front segment(s) as they register (see [`register_nav`]).
117 static PENDING: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
118 /// The app-installed persistence sink a nav surface's `.restore` reads and writes through
119 /// ([`set_nav_store`]). `None` = no store installed, so `.restore` is a no-op.
120 static NAV_STORE: RefCell<Option<Rc<dyn NavStore>>> = const { RefCell::new(None) };
121
122 static NAV_OBSERVER: RefCell<Option<Rc<NavObserver>>> = const { RefCell::new(None) };
123 /// The last route the observer was told about; dedups the several call sites below (a single
124 /// user navigation reaches `maybe_notify_route_change` from both the event-pump tail and the
125 /// imperative `navigate` tail; only the first, changing, call fires).
126 static LAST_ROUTE: RefCell<String> = const { RefCell::new(String::new()) };
127}
128
129/// Install a controller (innermost = last). Returns its token. The root `nav()` registers once
130/// and never unregisters; nested hosts (`tabs()` in a route) unregister when their scope disposes.
131///
132/// If an absolute navigation left unconsumed segments, the new surface consumes as many leading
133/// ones as it accepts; this is how `navigate("mail/inbox/msg-42")` reaches a stack that only
134/// mounts once the "mail" switch has taken effect.
135pub fn register_nav(ctrl: NavController) -> NavToken {
136 let token = NEXT_TOKEN.with(|c| {
137 let t = c.get();
138 c.set(t + 1);
139 NavToken(t)
140 });
141 let ctrl = Rc::new(ctrl);
142 NAV_STACK.with(|s| s.borrow_mut().push((token, ctrl.clone())));
143 // A newly mounted surface can retain the path signal from an earlier visit. An
144 // absolute destination replaces that path just as it does for a resident surface;
145 // otherwise register-time delivery appends before navigate_absolute can reset it.
146 // With no pending destination, a bare reopen keeps the remembered path.
147 if PENDING.with(|p| !p.borrow().is_empty()) {
148 let _ = (ctrl.push)("");
149 }
150 // Feed pending absolute segments to the just-mounted surface (front-first, stop at the
151 // first refusal, since deeper segments wait for deeper surfaces).
152 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
153 if !(ctrl.enter)(&front) {
154 break;
155 }
156 // `enter` may itself have consumed the segment: a push that mounts a surface
157 // registers it, and `register_nav` takes pending segments as it does. Only drop
158 // the head when it is still there.
159 PENDING.with(|p| {
160 let mut p = p.borrow_mut();
161 if !p.is_empty() {
162 p.remove(0);
163 }
164 });
165 }
166 token
167}
168
169/// Install a controller that answers a route only after every surface registered with
170/// [`register_nav`] has refused it: a presentation that exists for apps whose own navigation
171/// does not show the destination (the Settings cover on a phone app with no Settings section).
172///
173/// A fallback is not part of the mounted hierarchy. It contributes nothing to
174/// [`current_route`], takes no pending segments as it registers, and never anchors ahead of an
175/// app's section of the same name, however early it registered. When it accepts the first
176/// segment of an absolute path, the remaining segments go to its own `enter`.
177/// [`unregister_nav`] removes it.
178pub fn register_nav_fallback(ctrl: NavController) -> NavToken {
179 let token = NEXT_TOKEN.with(|c| {
180 let t = c.get();
181 c.set(t + 1);
182 NavToken(t)
183 });
184 FALLBACK_NAV.with(|s| s.borrow_mut().push((token, Rc::new(ctrl))));
185 token
186}
187
188/// The fallback controllers that are currently active, in registration order.
189fn active_fallbacks() -> Vec<Rc<NavController>> {
190 let all: Vec<Rc<NavController>> =
191 FALLBACK_NAV.with(|s| s.borrow().iter().map(|(_, c)| c.clone()).collect());
192 all.into_iter().filter(|c| (c.active)()).collect()
193}
194
195/// Install an app-level Back handler ([`BackHandler`]). Returns its token, which
196/// [`unregister_nav`] removes it with. Arms the platform's system back when the handler is
197/// enabled ([`sync_system_back`]).
198pub fn register_back_handler(handler: BackHandler) -> NavToken {
199 let token = NEXT_TOKEN.with(|c| {
200 let t = c.get();
201 c.set(t + 1);
202 NavToken(t)
203 });
204 BACK_HANDLERS.with(|s| s.borrow_mut().push((token, Rc::new(handler))));
205 sync_system_back();
206 token
207}
208
209/// Remove a controller whose host was disposed, or a Back handler whose piece was. No-op if
210/// already gone.
211pub fn unregister_nav(token: NavToken) {
212 NAV_STACK.with(|s| s.borrow_mut().retain(|(t, _)| *t != token));
213 FALLBACK_NAV.with(|s| s.borrow_mut().retain(|(t, _)| *t != token));
214 let had = BACK_HANDLERS.with(|s| {
215 let mut s = s.borrow_mut();
216 let before = s.len();
217 s.retain(|(t, _)| *t != token);
218 s.len() != before
219 });
220 if had {
221 sync_system_back();
222 }
223}
224
225/// The Back handler a back would run now: on screen and enabled, in the topmost cover, the
226/// most deeply nested in the piece tree, the most recently registered. Handlers are cloned out
227/// of the registry first, since `active`/`enabled` run app code (§3.3).
228fn winning_back_handler() -> Option<Rc<BackHandler>> {
229 let handlers = back_handlers_newest_first();
230 if handlers.is_empty() {
231 return None;
232 }
233 // Read every depth in one borrow, before any app code runs. A back arrives from the event
234 // pump or from app code, never from inside a tree borrow; if one ever does, equal depths
235 // leave registration order to decide rather than failing the back.
236 let depths = crate::tree::with_tree_if_free(|t| {
237 handlers
238 .iter()
239 .map(|h| tree_depth(t, h.node))
240 .collect::<Vec<_>>()
241 })
242 .unwrap_or_else(|| vec![0; handlers.len()]);
243 let mut ranked: Vec<(usize, Rc<BackHandler>)> = depths.into_iter().zip(handlers).collect();
244 day_reactive::untrack(|| {
245 // Stable, so equal keys keep the newest-first order.
246 ranked.sort_by_key(|(depth, h)| std::cmp::Reverse(((h.layer)(), *depth)));
247 ranked
248 .into_iter()
249 .map(|(_, h)| h)
250 .find(|h| (h.active)() && (h.enabled)())
251 })
252}
253
254/// The registered Back handlers, most recently registered first.
255fn back_handlers_newest_first() -> Vec<Rc<BackHandler>> {
256 BACK_HANDLERS.with(|s| s.borrow().iter().rev().map(|(_, h)| h.clone()).collect())
257}
258
259/// Whether any Back handler is on screen and enabled: what arming the system back needs, which,
260/// unlike choosing the one to run, does not depend on the tree.
261fn any_back_handler_wants() -> bool {
262 let handlers = back_handlers_newest_first();
263 !handlers.is_empty()
264 && day_reactive::untrack(|| handlers.iter().any(|h| (h.active)() && (h.enabled)()))
265}
266
267/// How many ancestors `node` has: its nesting depth in the piece tree.
268fn tree_depth(t: &dyn crate::tree::TreeOps, node: crate::RNode) -> usize {
269 let mut depth = 0;
270 let mut at = node;
271 while let Some(parent) = t.parent_of(at) {
272 depth += 1;
273 at = parent;
274 }
275 depth
276}
277
278/// Run the winning Back handler. False = none is on screen and enabled.
279fn run_back_handler() -> bool {
280 match winning_back_handler() {
281 Some(h) => {
282 (h.run)();
283 true
284 }
285 None => false,
286 }
287}
288
289/// Tell the toolkit whether the platform's system back belongs to the app's handlers: armed
290/// while any handler is on screen and enabled (`Toolkit::set_system_back`). Cheap and
291/// idempotent; the toolkit hears only changes. A handler's piece calls it whenever its
292/// `enabled` or the selection of a resident page around it changes, including a tab picked from
293/// code, and the event pump calls it after every batch for gates no signal reports.
294///
295/// While the tree is borrowed (a handler registered during a build that a toolkit call is
296/// part of), the update waits for the next safe point.
297pub fn sync_system_back() {
298 let want = any_back_handler_wants();
299 if BACK_ARMED.with(|a| a.get()) == want || crate::tree::tree_absent() {
300 return;
301 }
302 match crate::tree::with_tree_if_free(|t| t.set_system_back(want)) {
303 Some(()) => BACK_ARMED.with(|a| a.set(want)),
304 None => crate::tree::run_posted_or_defer(Box::new(sync_system_back)),
305 }
306}
307
308/// The platform's system back, armed by [`sync_system_back`], that no native container took
309/// (`Event::NavBack` on `WINDOW_NODE`): run the app's handler. The native side already gave
310/// its covers and pushed pages the first answer, so Day's surfaces are not asked again. With
311/// no handler left enabled (it turned off between the arming and the press), the press is
312/// dropped and the toolkit released, so the next one leaves the app as usual.
313pub(crate) fn system_back() {
314 if !run_back_handler() {
315 log::debug!("day: system back with no enabled handler; releasing it");
316 // The toolkit holds the back armed whatever Day last told it (a recreated Android
317 // activity starts over): tell it again rather than trust the cached answer.
318 BACK_ARMED.with(|a| a.set(true));
319 }
320 sync_system_back();
321}
322
323/// Drop every controller: a fresh mount / test boot (called from tree install/uninstall).
324pub fn clear_controllers() {
325 NAV_STACK.with(|s| s.borrow_mut().clear());
326 FALLBACK_NAV.with(|s| s.borrow_mut().clear());
327 NEXT_TOKEN.with(|c| c.set(1));
328 BACK_HANDLERS.with(|s| s.borrow_mut().clear());
329 // A fresh mount comes with a fresh toolkit, whose system back starts released.
330 BACK_ARMED.with(|a| a.set(false));
331 PENDING.with(|p| p.borrow_mut().clear());
332 PARAMS.with(|p| *p.borrow_mut() = Rc::new(Vec::new()));
333}
334
335/// Dispatch innermost→outermost; the first controller that returns true wins. Controllers are
336/// `Rc`-cloned out of the stack before the call, so their closures (which re-enter the tree and
337/// may register/unregister hosts) never run while the stack is borrowed (§3.3).
338///
339/// Presented covers and their descendants come before the covered window. Within a presentation
340/// layer, "innermost" is decided by [`NavController::depth`], not by registration order: the mirror of
341/// [`nested_after`]'s outermost-first rule, and for the same reason: a host registers after
342/// building its pages, so the registry places it after the surfaces those pages contain. Asked in
343/// reverse-registration order, a tab bar would answer a back before the stack pushed inside its
344/// page ever heard it (which is how a phone's `nav_back` cleared the tab selection and stranded
345/// the pushed detail in the tree). The sort is stable over the reversed list, so equal depths
346/// keep newest-registration-first, which is what sibling surfaces want.
347fn dispatch(f: impl Fn(&NavController) -> bool) -> bool {
348 let mut controllers: Vec<Rc<NavController>> =
349 NAV_STACK.with(|s| s.borrow().iter().rev().map(|(_, c)| c.clone()).collect());
350 controllers.sort_by_key(|c| std::cmp::Reverse(((c.layer)(), c.depth)));
351 for c in controllers {
352 if (c.active)() && f(&c) {
353 return true;
354 }
355 }
356 active_fallbacks().into_iter().any(|c| f(&c))
357}
358
359// ---------------------------------------------------------------------------
360// Route strings (docs/navigation.md): `seg/seg/seg?name=value&name2=value2`
361// ---------------------------------------------------------------------------
362
363/// Split a route string into its path segments and query params. Segments and param
364/// names/values are percent-decoded (`%2F` → `/`, …); everything else is taken literally.
365pub fn parse_route(route: &str) -> (Vec<String>, Vec<(String, String)>) {
366 let (path, query) = match route.split_once('?') {
367 Some((p, q)) => (p, q),
368 None => (route, ""),
369 };
370 let segments: Vec<String> = path
371 .split('/')
372 .filter(|s| !s.is_empty())
373 .map(percent_decode)
374 .collect();
375 let params: Vec<(String, String)> = query
376 .split('&')
377 .filter(|s| !s.is_empty())
378 .map(|pair| match pair.split_once('=') {
379 Some((k, v)) => (percent_decode(k), percent_decode(v)),
380 None => (percent_decode(pair), String::new()),
381 })
382 .collect();
383 (segments, params)
384}
385
386/// Assemble a route string from segments and params, the inverse of [`parse_route`].
387/// Reserved characters (`/`, `?`, `&`, `=`, `%`) in segments and params are percent-encoded.
388pub fn encode_route(segments: &[String], params: &[(String, String)]) -> String {
389 let mut out = segments
390 .iter()
391 .map(|s| percent_encode(s))
392 .collect::<Vec<_>>()
393 .join("/");
394 if !params.is_empty() {
395 out.push('?');
396 out.push_str(
397 ¶ms
398 .iter()
399 .map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v)))
400 .collect::<Vec<_>>()
401 .join("&"),
402 );
403 }
404 out
405}
406
407fn percent_decode(s: &str) -> String {
408 let bytes = s.as_bytes();
409 let mut out = Vec::with_capacity(bytes.len());
410 let mut i = 0;
411 while i < bytes.len() {
412 if bytes[i] == b'%'
413 && i + 2 < bytes.len() + 1
414 && let (Some(h), Some(l)) = (
415 bytes.get(i + 1).and_then(|b| (*b as char).to_digit(16)),
416 bytes.get(i + 2).and_then(|b| (*b as char).to_digit(16)),
417 )
418 {
419 out.push((h * 16 + l) as u8);
420 i += 3;
421 } else {
422 out.push(bytes[i]);
423 i += 1;
424 }
425 }
426 String::from_utf8_lossy(&out).into_owned()
427}
428
429fn percent_encode(s: &str) -> String {
430 let mut out = String::with_capacity(s.len());
431 for b in s.bytes() {
432 match b {
433 b'/' | b'?' | b'&' | b'=' | b'%' => out.push_str(&format!("%{b:02X}")),
434 _ => out.push(b as char),
435 }
436 }
437 out
438}
439
440/// The query params carried by the most recent [`navigate`] call (`?name=value&…`). Read them
441/// inside a destination builder: `route_param("id")`. They describe the navigation in flight;
442/// a push you perform by writing a path signal directly carries its data in your own state
443/// instead (docs/navigation.md).
444pub fn route_params() -> Rc<Vec<(String, String)>> {
445 PARAMS.with(|p| p.borrow().clone())
446}
447
448/// The value of one query param of the most recent [`navigate`] (`None` = not present).
449pub fn route_param(name: &str) -> Option<String> {
450 route_params()
451 .iter()
452 .find(|(k, _)| k == name)
453 .map(|(_, v)| v.clone())
454}
455
456/// Record the host's launch deep link before `launch_with` runs (docs/navigation.md).
457/// Platform glue only; apps navigate with [`navigate`]. `DAY_DEEPLINK`, where a process
458/// environment exists, takes precedence.
459///
460/// UI thread only: the slot is thread-local, because the web host that seeds it runs on the one
461/// thread there is. Glue that may be called from another thread (a notification tap arriving on a
462/// JNI or delegate thread) wants [`request_route`], which is thread-safe and works at any
463/// lifecycle stage.
464pub fn set_launch_deeplink(route: &str) {
465 LAUNCH_DEEPLINK.with(|l| *l.borrow_mut() = Some(route.to_string()));
466}
467
468/// A route requested from outside the reactive turn, at any lifecycle stage, from any thread:
469/// the rail a notification tap navigates through (docs/notify.md).
470///
471/// This is process-global rather than thread-local ([`LAUNCH_DEEPLINK`] is the latter) because the
472/// caller is usually not on the UI thread: Android delivers a tap on a JNI thread and Apple on a
473/// delegate callback, and both can arrive before `launch_with` has run at all.
474static REQUESTED_ROUTE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
475
476fn requested_slot() -> std::sync::MutexGuard<'static, Option<String>> {
477 // A panic while holding this lock would otherwise wedge every later navigation; the buffer is
478 // one Option<String>, so recovering the value is always safe.
479 REQUESTED_ROUTE.lock().unwrap_or_else(|e| e.into_inner())
480}
481
482/// Ask the app to navigate, from anywhere, at any time.
483///
484/// Cold start (a tap that launches the process) and warm tap (the app is already running) are the
485/// same call: before launch the route is buffered and `launch_with` applies it after the first
486/// mount, so it lands once routes actually exist; after launch it is applied on the UI thread.
487/// An empty route is ignored, and the newest request wins: a user who taps twice gets the second
488/// destination.
489pub fn request_route(route: &str) {
490 if route.is_empty() {
491 return;
492 }
493 *requested_slot() = Some(route.to_string());
494 // Before a backend installs the poster there is no UI thread to post to; the launch drain
495 // picks the buffer up instead.
496 if day_reactive::has_main_poster() {
497 day_reactive::on_main(|| {
498 if let Some(route) = take_requested_route() {
499 apply_route_request(&route);
500 }
501 });
502 }
503}
504
505/// Take the buffered route, if any. `launch_with` drains it after the first mount.
506pub(crate) fn take_requested_route() -> Option<String> {
507 requested_slot().take()
508}
509
510/// Apply a route the backend or a part asked for. Echoes of our own `set_route` match the current
511/// route and are dropped.
512pub(crate) fn apply_route_request(route: &str) {
513 if current_route().as_deref() != Some(route) && !navigate(route) {
514 log::warn!("requested route {route:?} did not match");
515 }
516}
517
518/// Whether a launch deep link is pending (`DAY_DEEPLINK` or a platform hint). A nav surface's
519/// `.restore` reads this so a deep link wins over restored state (docs/navigation.md).
520pub fn has_launch_deeplink() -> bool {
521 launch_deeplink().is_some()
522}
523
524/// A key/value sink a nav surface's `.restore` persists its state through, so navigation
525/// survives a relaunch or an Android process death (docs/navigation.md). `day::launch` installs
526/// the preferences store (`day_part_preferences::install_nav_store`) unless the app installed one
527/// first; an app marks the surfaces it wants remembered with `.restore(key)`. With no store installed,
528/// `.restore` is a silent no-op, so a surface's `.restore` call never fails to build.
529///
530/// Keys are opaque to day-core and namespaced by the surface's `.restore(key)` argument; the
531/// store implementation is responsible for keeping them clear of the app's own data.
532pub trait NavStore {
533 /// The last value saved under `key`, or `None` if nothing was stored (first launch).
534 fn load(&self, key: &str) -> Option<String>;
535 /// Persist `value` under `key`, replacing any prior value.
536 fn save(&self, key: &str, value: &str);
537}
538
539/// Install the app's navigation persistence store (docs/navigation.md). Call once at startup,
540/// before the UI mounts, so a `.restore` surface reads it on first build. A later call replaces
541/// the store.
542pub fn set_nav_store(store: Rc<dyn NavStore>) {
543 NAV_STORE.with(|s| *s.borrow_mut() = Some(store));
544}
545
546/// Whether a [`NavStore`] is installed. `day::launch` installs the preferences store when the
547/// app has not installed one of its own.
548pub fn has_nav_store() -> bool {
549 NAV_STORE.with(|s| s.borrow().is_some())
550}
551
552/// Read a `.restore` key through the installed [`NavStore`] (`None` if none is installed or the
553/// key was never saved).
554pub fn nav_store_load(key: &str) -> Option<String> {
555 match NAV_STORE.with(|s| s.borrow().clone()) {
556 Some(st) => st.load(key),
557 None => {
558 warn_no_nav_store(key);
559 None
560 }
561 }
562}
563
564/// Debug-build diagnostic, once per process: a surface asked to `.restore(key)` while no
565/// [`NavStore`] is installed persists nothing, and does so silently: the surface still builds,
566/// the app still runs, and the setting never survives a relaunch. That follows from the
567/// design (`.restore` must never fail to build), but it reads as a bug, so say it out loud where
568/// a developer will see it.
569fn warn_no_nav_store(key: &str) {
570 if !cfg!(debug_assertions) {
571 return;
572 }
573 thread_local! {
574 // Android-only false positive, as with day-spec's `APP_TEMP_DIR`: already a `const` block.
575 #[allow(clippy::missing_const_for_thread_local)]
576 static WARNED: Cell<bool> = const { Cell::new(false) };
577 }
578 WARNED.with(|w| {
579 if !w.replace(true) {
580 log::warn!(
581 ".restore({key:?}) has no NavStore installed — navigation state will not \
582 persist. `day::launch` installs the preferences store unless the `day` \
583 crate's `prefs` feature is off; otherwise call `day_core::set_nav_store` \
584 before the UI mounts (docs/navigation.md)."
585 );
586 }
587 });
588}
589
590/// Write a `.restore` key through the installed [`NavStore`] (a no-op if none is installed).
591pub fn nav_store_save(key: &str, value: &str) {
592 if let Some(st) = NAV_STORE.with(|s| s.borrow().clone()) {
593 st.save(key, value);
594 }
595}
596
597/// The launch deep link: the `DAY_DEEPLINK` environment variable, else the platform's
598/// [`set_launch_deeplink`] hint. Consumed by `launch_with` after the first mount.
599pub(crate) fn launch_deeplink() -> Option<String> {
600 std::env::var("DAY_DEEPLINK")
601 .ok()
602 .filter(|r| !r.is_empty())
603 // A route buffered by `request_route` before launch: a notification tap that cold-started
604 // the process. Peeked, not taken, so `has_launch_deeplink()` keeps answering true for a
605 // nav surface's `.restore` (a tap must beat restored state); `launch_with` takes it.
606 .or_else(|| requested_slot().clone())
607 .or_else(|| LAUNCH_DEEPLINK.with(|l| l.borrow().clone()))
608 .filter(|r| !r.is_empty())
609}
610
611/// Navigate to a route (docs/navigation.md).
612///
613/// * `""`: pop the innermost stack to its root (falls through outward).
614/// * A single key is relative: innermost surface first, falling through outward.
615/// * `a/b/c` is absolute: anchor at the outermost surface that knows `a`, reset every surface
616/// inside the anchor to its root, then feed `b`, `c`, … inward (surfaces that mount during
617/// the cascade consume the rest as they register).
618/// * A trailing `?name=value&…` carries [`route_params`] to the destination builders.
619///
620/// False = no mounted surface recognized the (first) segment.
621pub fn navigate(route: &str) -> bool {
622 let (segments, params) = parse_route(route);
623 PENDING.with(|p| p.borrow_mut().clear());
624 PARAMS.with(|p| *p.borrow_mut() = Rc::new(params));
625 let ok = match segments.len() {
626 0 => dispatch(|nav| (nav.push)("")),
627 1 => dispatch(|nav| (nav.push)(&segments[0])),
628 _ => navigate_absolute(&segments),
629 };
630 maybe_notify_route_change();
631 ok
632}
633
634/// The surfaces inside `list[anchor]`, outermost first.
635///
636/// Ordered by [`NavController::depth`] rather than by registration, because a host that builds its
637/// pages before registering itself lands in the registry after what those pages contain, so an
638/// absolute `section/detail` would otherwise anchor on the section and find nothing beyond it.
639/// Depth only orders here, never filters: a subtree rebuilt outside its original build scope (a
640/// `when` arm re-derived on a size-class change) registers with a depth of zero, and equal depths
641/// keep registration order, which is the right answer in that case.
642fn nested_after(list: &[Rc<NavController>], anchor: usize) -> Vec<Rc<NavController>> {
643 let mut order: Vec<usize> = (0..list.len()).collect();
644 order.sort_by_key(|i| list[*i].depth);
645 let at = order.iter().position(|i| *i == anchor).unwrap_or(0);
646 order[at + 1..].iter().map(|i| list[*i].clone()).collect()
647}
648
649/// Anchor + descend for a multi-segment path. See [`navigate`].
650///
651/// Signal writes may propagate synchronously (an un-batched set cascades immediately), so the
652/// surfaces an anchor switch mounts can register, and must find their segments waiting,
653/// before the anchoring `push` even returns. Hence: queue the tail first, then anchor.
654fn navigate_absolute(segments: &[String]) -> bool {
655 let snapshot = || -> Vec<Rc<NavController>> {
656 NAV_STACK.with(|s| s.borrow().iter().map(|(_, c)| c.clone()).collect())
657 };
658 let controllers = snapshot();
659 let first = &segments[0];
660
661 // Already anchored: some surface is showing `first`. Reset everything inside it to its
662 // root (innermost-first, so stacks pop cleanly), then feed the remaining segments to the
663 // surviving inner surfaces in nesting order. Consult the live registry after the resets,
664 // because a reset can dispose deeper surfaces (a popped page takes its sub-surfaces with it).
665 if let Some(anchor) = controllers.iter().position(|c| (c.current)() == *first) {
666 PENDING.with(|p| *p.borrow_mut() = segments[1..].to_vec());
667 for c in nested_after(&controllers, anchor).iter().rev() {
668 let _ = (c.push)("");
669 }
670 let live = snapshot();
671 if let Some(anchor) = live.iter().position(|c| (c.current)() == *first) {
672 for c in nested_after(&live, anchor) {
673 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
674 if !(c.enter)(&front) {
675 break;
676 }
677 // `enter` may itself have consumed the segment: a push that mounts a surface
678 // registers it, and `register_nav` takes pending segments as it does. Only drop
679 // the head when it is still there.
680 PENDING.with(|p| {
681 let mut p = p.borrow_mut();
682 if !p.is_empty() {
683 p.remove(0);
684 }
685 });
686 }
687 }
688 }
689 return true;
690 }
691
692 // Switching: queue the tail so surfaces that mount during the (possibly synchronous)
693 // cascade consume it as they register, then anchor at the outermost surface that accepts
694 // the first segment.
695 PENDING.with(|p| *p.borrow_mut() = segments[1..].to_vec());
696 for c in controllers.iter() {
697 if (c.push)(first) {
698 // Tabs may have already mounted the destination's nested surfaces. They will not
699 // register again on selection, so deliver the remaining segments here as well.
700 // Lazily mounted surfaces still consume the tail in `register_nav`.
701 let live = snapshot();
702 if let Some(anchor) = live.iter().position(|nav| Rc::ptr_eq(nav, c)) {
703 let nested: Vec<Rc<NavController>> = nested_after(&live, anchor)
704 .into_iter()
705 .filter(|nav| (nav.active)())
706 .collect();
707 // An explicit deeper path is the nested surfaces' whole state (set-semantics,
708 // as in the anchored branch above): a resident stack that still holds the
709 // pages of an earlier visit pops to its root before the tail lands, so
710 // `settings/general` followed later by `settings/privacy` reads
711 // `settings/privacy`, not `settings/general/privacy`. A bare section switch
712 // leaves what the user had open.
713 if PENDING.with(|p| !p.borrow().is_empty()) {
714 for child in nested.iter().rev() {
715 let _ = (child.push)("");
716 }
717 }
718 for child in nested {
719 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
720 if !(child.enter)(&front) {
721 break;
722 }
723 // `enter` may itself have consumed the segment: a push that mounts a surface
724 // registers it, and `register_nav` takes pending segments as it does. Only drop
725 // the head when it is still there.
726 PENDING.with(|p| {
727 let mut p = p.borrow_mut();
728 if !p.is_empty() {
729 p.remove(0);
730 }
731 });
732 }
733 }
734 }
735 return true;
736 }
737 }
738 // No mounted surface knows the first segment: offer the path to the fallbacks, each of
739 // which takes the rest of it itself.
740 for c in active_fallbacks() {
741 if (c.push)(first) {
742 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
743 if !(c.enter)(&front) {
744 break;
745 }
746 PENDING.with(|p| {
747 let mut p = p.borrow_mut();
748 if !p.is_empty() {
749 p.remove(0);
750 }
751 });
752 }
753 return true;
754 }
755 }
756 PENDING.with(|p| p.borrow_mut().clear());
757 false
758}
759
760/// Pop one level, day-initiated (the toolkit presents the pop). Native-initiated pops arrive as
761/// `Event::NavBack` and go through the owning host's `pop` directly.
762///
763/// A back no surface takes runs the app's Back handler ([`BackHandler`]), as the platform's
764/// system back does, so dayscript's `nav_back` and a desktop's own Back control reach it too.
765pub fn nav_back() -> bool {
766 let ok = dispatch(|nav| (nav.pop)(false)) || run_back_handler();
767 maybe_notify_route_change();
768 ok
769}
770
771/// A navigation observer (§14.6): called with the new full route each time it changes, from any
772/// source: imperative `navigate`/`nav_back`, a nav_link or sidebar row (which navigate from an
773/// event handler, bypassing the event observer), a stack push, or a native back gesture. `""` is
774/// the root. Installed by the recorder in day-script; day-core only fires it.
775pub type NavObserver = dyn Fn(&str, Option<&str>);
776
777/// Install (or clear, with `None`) the navigation observer. Resets the dedup baseline so the next
778/// change fires regardless of where recording started.
779pub fn set_nav_observer(observer: Option<Box<NavObserver>>) {
780 NAV_OBSERVER.with(|o| *o.borrow_mut() = observer.map(Rc::from));
781 // Seed the baseline with the normalized route (an unmounted surface is `None` == `""`), so the
782 // first real navigation, not the None→"" transition at install, is what fires.
783 LAST_ROUTE.with(|r| *r.borrow_mut() = current_route().unwrap_or_default());
784}
785
786/// Announce a navigation to `route` from its source: a nav host (the sidebar nav host) calls
787/// this the instant it changes the bound selection, so the observer sees it synchronously instead
788/// of waiting for the route to settle into `NAV_STACK` a frame later (which `maybe_notify_route_change`
789/// reads). Deduped like the pump-boundary path. `route` is the host's local key, which replays as a
790/// relative `navigate` (innermost-first), correct for both a top-level sidebar and a nested one.
791pub fn note_navigation(route: &str, label: Option<&str>) {
792 let changed = LAST_ROUTE.with(|r| {
793 let mut r = r.borrow_mut();
794 if *r == route {
795 false
796 } else {
797 *r = route.to_string();
798 true
799 }
800 });
801 if !changed {
802 return;
803 }
804 let observer = NAV_OBSERVER.with(|o| o.borrow().clone());
805 if let Some(obs) = observer {
806 obs(route, label);
807 }
808}
809
810/// Fire the navigation observer if the full route changed since it was last told. Called at the
811/// tail of the event pump and of the imperative nav helpers; the dedup makes the redundant call a
812/// cheap no-op. The observer handle is cloned out first so it may re-enter (read the route, stop
813/// recording) without holding a borrow (mirrors the event observer in tree.rs).
814pub(crate) fn maybe_notify_route_change() {
815 let now = current_route().unwrap_or_default();
816 let changed = LAST_ROUTE.with(|r| {
817 let mut r = r.borrow_mut();
818 if *r == now {
819 false
820 } else {
821 *r = now.clone();
822 true
823 }
824 });
825 if !changed {
826 return;
827 }
828 let observer = NAV_OBSERVER.with(|o| o.borrow().clone());
829 if let Some(obs) = observer {
830 // No control context here (this is the settled-route fallback path); the source-notifying
831 // `note_navigation` supplies a label when a nav host has one.
832 obs(&now, None);
833 }
834}
835
836/// The full current route: every mounted surface's contribution, outermost to innermost,
837/// `/`-joined (docs/navigation.md). `None` = no surface mounted; `Some("")` = everything at
838/// its root. Round-trips through [`navigate`], so persisting navigation state is
839/// `save(current_route())` on the way out and `navigate(&saved)` on the way back in.
840pub fn current_route() -> Option<String> {
841 let controllers: Vec<Rc<NavController>> =
842 NAV_STACK.with(|s| s.borrow().iter().map(|(_, c)| c.clone()).collect());
843 if controllers.is_empty() {
844 return None;
845 }
846 // Outermost first, which is nesting order rather than registration order: a host that builds
847 // its pages before registering itself lands after what those pages contain
848 // (`NavController::depth`). Ties keep registration order, which is what siblings want.
849 let mut ordered = controllers;
850 ordered.sort_by_key(|c| c.depth);
851 let mut parts: Vec<String> = Vec::new();
852 for c in ordered {
853 // Only what is on screen. A resident page the host is not showing keeps its surfaces
854 // registered, and joining those in would append every unselected tab's state to the route.
855 if !(c.active)() {
856 continue;
857 }
858 parts.extend((c.segments)());
859 }
860 Some(encode_route(&parts, &[]))
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866
867 #[test]
868 fn route_parsing_round_trips() {
869 let (segs, params) = parse_route("mail/inbox/msg-42?hint=linked&x=1");
870 assert_eq!(segs, vec!["mail", "inbox", "msg-42"]);
871 assert_eq!(
872 params,
873 vec![("hint".into(), "linked".into()), ("x".into(), "1".into())]
874 );
875 assert_eq!(
876 encode_route(&segs, ¶ms),
877 "mail/inbox/msg-42?hint=linked&x=1"
878 );
879
880 // Reserved characters survive a round trip.
881 let segs = vec!["a/b".to_string()];
882 let params = vec![("q".to_string(), "1&2=3".to_string())];
883 let encoded = encode_route(&segs, ¶ms);
884 let (s2, p2) = parse_route(&encoded);
885 assert_eq!(s2, segs);
886 assert_eq!(p2, params);
887 }
888
889 #[test]
890 fn route_parsing_edge_cases() {
891 assert_eq!(parse_route(""), (vec![], vec![]));
892 assert_eq!(parse_route("a"), (vec!["a".to_string()], vec![]));
893 assert_eq!(parse_route("a//b").0, vec!["a", "b"]); // empty segments dropped
894 assert_eq!(
895 parse_route("?flag").1,
896 vec![("flag".to_string(), String::new())]
897 );
898 }
899
900 /// A controller that accepts the keys in `knows`, logging every call it answers.
901 fn recording(
902 knows: &'static [&'static str],
903 log: &Rc<RefCell<Vec<String>>>,
904 tag: &'static str,
905 ) -> NavController {
906 let (push_log, enter_log) = (log.clone(), log.clone());
907 NavController {
908 push: Box::new(move |route| {
909 let ok = knows.contains(&route);
910 if ok {
911 push_log.borrow_mut().push(format!("{tag} push {route}"));
912 }
913 ok
914 }),
915 pop: Box::new(|_| false),
916 current: Box::new(String::new),
917 enter: Box::new(move |segment| {
918 let ok = knows.contains(&segment);
919 if ok {
920 enter_log
921 .borrow_mut()
922 .push(format!("{tag} enter {segment}"));
923 }
924 ok
925 }),
926 segments: Box::new(Vec::new),
927 depth: 0,
928 layer: Box::new(|| 0),
929 active: Box::new(|| true),
930 }
931 }
932
933 /// A fallback registered before the app's navigation still loses a route the navigation
934 /// knows, whether the path is one segment or several.
935 #[test]
936 fn a_fallback_answers_only_what_no_surface_accepts() {
937 clear_controllers();
938 let log: Rc<RefCell<Vec<String>>> = Rc::default();
939 let cover = register_nav_fallback(recording(&["settings", "search"], &log, "cover"));
940 register_nav(recording(&["home", "settings"], &log, "app"));
941
942 assert!(navigate("settings/search"));
943 assert!(navigate("settings"));
944 assert_eq!(*log.borrow(), ["app push settings", "app push settings"]);
945 log.borrow_mut().clear();
946
947 // Nothing mounted knows `search`: the fallback takes it, alone or as a path's head.
948 assert!(navigate("search"));
949 assert_eq!(*log.borrow(), ["cover push search"]);
950 log.borrow_mut().clear();
951
952 unregister_nav(cover);
953 assert!(!navigate("search"));
954 assert!(log.borrow().is_empty());
955 clear_controllers();
956 }
957
958 /// With no surface that knows the head, the fallback takes the head and then the rest of the
959 /// path, and contributes nothing to the current route.
960 #[test]
961 fn a_fallback_takes_the_whole_path() {
962 clear_controllers();
963 let log: Rc<RefCell<Vec<String>>> = Rc::default();
964 register_nav(recording(&["home"], &log, "app"));
965 register_nav_fallback(recording(&["settings", "search"], &log, "cover"));
966
967 assert!(navigate("settings/search"));
968 assert_eq!(*log.borrow(), ["cover push settings", "cover enter search"]);
969 assert!(!navigate("elsewhere/search"));
970 clear_controllers();
971 }
972
973 /// `REQUESTED_ROUTE` is process-global (it must be; see `request_route`), so the tests that
974 /// touch it cannot run in parallel with each other. Serialize them rather than making the
975 /// production type thread-local, which would defeat the purpose of the buffer.
976 static ROUTE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
977
978 fn route_test<T>(f: impl FnOnce() -> T) -> T {
979 let _guard = ROUTE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
980 let _ = take_requested_route();
981 let out = f();
982 let _ = take_requested_route();
983 out
984 }
985
986 /// The route-buffering assertions below describe the state a cold-start notification tap
987 /// arrives in: a process where NO backend has installed the main poster yet. They cannot run
988 /// beside the rest of this binary's tests.
989 ///
990 /// `day_reactive::install_main_poster` is a process-wide `OnceLock` that is never cleared, and
991 /// `present::task_tests` installs one: its executor wakers re-poll through `on_main`, so those
992 /// tests need it. Once installed, `request_route` takes its posting branch and the
993 /// inline poster runs `apply_route_request` immediately, draining the very buffer these
994 /// assertions are about. libtest gives no ordering guarantee between the two groups, so this
995 /// was a coin flip: the same commit passed on linux-aarch64 and failed on linux-x86_64.
996 ///
997 /// So they run in a child process. This test re-executes the test binary selecting only the
998 /// ignored test below, which is the whole set of assertions; nothing else runs there, so no
999 /// poster exists and the precondition holds by construction rather than by luck.
1000 #[test]
1001 fn route_buffering_before_launch() {
1002 let exe = std::env::current_exe().expect("the running test binary has a path");
1003 let out = std::process::Command::new(exe)
1004 .args([
1005 "--exact",
1006 "--ignored",
1007 "--nocapture",
1008 "--test-threads=1",
1009 "nav::tests::route_buffering_in_a_poster_free_process",
1010 ])
1011 .output()
1012 .expect("re-run this test binary for the child case");
1013 assert!(
1014 out.status.success(),
1015 "the poster-free route assertions failed in the child process:\n{}{}",
1016 String::from_utf8_lossy(&out.stdout),
1017 String::from_utf8_lossy(&out.stderr),
1018 );
1019 }
1020
1021 /// Every assertion that depends on no backend having started. Ignored so it runs only in the
1022 /// child process [`route_buffering_before_launch`] spawns; see that test for why.
1023 #[test]
1024 #[ignore = "needs a process with no main poster; run by route_buffering_before_launch"]
1025 fn route_buffering_in_a_poster_free_process() {
1026 assert!(
1027 !day_reactive::has_main_poster(),
1028 "this test must run in a process where no backend installed the poster; \
1029 it is meaningless otherwise, so failing loudly beats passing vacuously",
1030 );
1031
1032 // A tap that cold-starts the process buffers a route, and the launch path sees it.
1033 // Without this, `launch_deeplink()` would miss it and the app would open on its default
1034 // screen.
1035 route_test(|| {
1036 assert_eq!(launch_deeplink(), None);
1037 request_route("clock/timer");
1038 assert_eq!(launch_deeplink().as_deref(), Some("clock/timer"));
1039 // Peeked, not taken: a nav surface's `.restore` asks this so a tap beats restored state.
1040 assert!(has_launch_deeplink());
1041 assert_eq!(take_requested_route().as_deref(), Some("clock/timer"));
1042 assert_eq!(take_requested_route(), None);
1043 });
1044
1045 // The newest tap wins: a user who taps a second notification before launch completes gets
1046 // the second destination, not the first.
1047 route_test(|| {
1048 request_route("mail/inbox");
1049 request_route("clock/alarm");
1050 assert_eq!(take_requested_route().as_deref(), Some("clock/alarm"));
1051 });
1052
1053 // An empty route is not a navigation request: `navigate("")` means "pop to root", which a
1054 // missing intent extra must never trigger.
1055 route_test(|| {
1056 request_route("");
1057 assert_eq!(take_requested_route(), None);
1058 });
1059
1060 // `request_route` must not panic when no backend has started, which is exactly the state a
1061 // cold-start notification tap arrives in (`on_main` panics without a poster).
1062 route_test(|| {
1063 request_route("some/route"); // would panic if it posted unconditionally
1064 let _ = take_requested_route();
1065 });
1066 }
1067}