Skip to main content

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