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 ¶ms
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/// Ask the app to navigate, from anywhere, at any time.
476///
477/// Cold start (a tap that launches the process) and warm tap (the app is already running) are the
478/// same call: before launch the route is buffered and `launch_with` applies it after the first
479/// mount, so it lands once routes actually exist; after launch it is applied on the UI thread.
480/// An empty route is ignored, and the newest request wins: a user who taps twice gets the second
481/// destination.
482///
483/// The buffer is day-process's ([`day_process::routes`]), so a part with no UI dependency makes
484/// the same request through it.
485pub fn request_route(route: &str) {
486 install_route_notifier();
487 day_process::routes::request(route);
488}
489
490/// Hear about requests made straight through `day_process::routes`. Installed at launch and on
491/// the first [`request_route`].
492pub(crate) fn install_route_notifier() {
493 day_process::routes::set_notifier(|| {
494 // Before a backend installs the poster there is no UI thread to post to; the launch
495 // drain 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
506/// Take the buffered route, if any. `launch_with` drains it after the first mount.
507pub(crate) fn take_requested_route() -> Option<String> {
508 day_process::routes::take()
509}
510
511/// Apply a route the backend or a part asked for. Echoes of our own `set_route` match the current
512/// route and are dropped.
513pub(crate) fn apply_route_request(route: &str) {
514 if current_route().as_deref() != Some(route) && !navigate(route) {
515 log::warn!("requested route {route:?} did not match");
516 }
517}
518
519/// Whether a launch deep link is pending (`DAY_DEEPLINK` or a platform hint). A nav surface's
520/// `.restore` reads this so a deep link wins over restored state (docs/navigation.md).
521#[must_use]
522pub fn has_launch_deeplink() -> bool {
523 launch_deeplink().is_some()
524}
525
526/// A key/value sink a nav surface's `.restore` persists its state through, so navigation
527/// survives a relaunch or an Android process death (docs/navigation.md). `day::launch` installs
528/// the preferences store (`day::prefs::install_nav_store`) unless the app installed one
529/// first; an app marks the surfaces it wants remembered with `.restore(key)`. With no store installed,
530/// `.restore` is a silent no-op, so a surface's `.restore` call never fails to build.
531///
532/// Keys are opaque to day-core and namespaced by the surface's `.restore(key)` argument; the
533/// store implementation is responsible for keeping them clear of the app's own data.
534pub trait NavStore {
535 /// The last value saved under `key`, or `None` if nothing was stored (first launch).
536 fn load(&self, key: &str) -> Option<String>;
537 /// Persist `value` under `key`, replacing any prior value.
538 fn save(&self, key: &str, value: &str);
539}
540
541/// Install the app's navigation persistence store (docs/navigation.md). Call once at startup,
542/// before the UI mounts, so a `.restore` surface reads it on first build. A later call replaces
543/// the store.
544pub fn set_nav_store(store: Rc<dyn NavStore>) {
545 NAV_STORE.with(|s| *s.borrow_mut() = Some(store));
546}
547
548/// Whether a [`NavStore`] is installed. `day::launch` installs the preferences store when the
549/// app has not installed one of its own.
550#[must_use]
551pub fn has_nav_store() -> bool {
552 NAV_STORE.with(|s| s.borrow().is_some())
553}
554
555/// Read a `.restore` key through the installed [`NavStore`] (`None` if none is installed or the
556/// key was never saved).
557#[must_use]
558pub fn nav_store_load(key: &str) -> Option<String> {
559 if let Some(st) = NAV_STORE.with(|s| s.borrow().clone()) {
560 st.load(key)
561 } else {
562 warn_no_nav_store(key);
563 None
564 }
565}
566
567/// Debug-build diagnostic, once per process: a surface asked to `.restore(key)` while no
568/// [`NavStore`] is installed persists nothing, and does so silently: the surface still builds,
569/// the app still runs, and the setting never survives a relaunch. That follows from the
570/// design (`.restore` must never fail to build), but it reads as a bug, so say it out loud where
571/// a developer will see it.
572fn warn_no_nav_store(key: &str) {
573 if !cfg!(debug_assertions) {
574 return;
575 }
576 thread_local! {
577 // Android-only false positive, as with day-spec's `APP_TEMP_DIR`: already a `const` block.
578 #[allow(clippy::missing_const_for_thread_local)]
579 static WARNED: Cell<bool> = const { Cell::new(false) };
580 }
581 WARNED.with(|w| {
582 if !w.replace(true) {
583 log::warn!(
584 ".restore({key:?}) has no NavStore installed — navigation state will not \
585 persist. `day::launch` installs the preferences store unless the `day` \
586 crate's `prefs` feature is off; otherwise call `day_core::set_nav_store` \
587 before the UI mounts (docs/navigation.md)."
588 );
589 }
590 });
591}
592
593/// Write a `.restore` key through the installed [`NavStore`] (a no-op if none is installed).
594pub fn nav_store_save(key: &str, value: &str) {
595 if let Some(st) = NAV_STORE.with(|s| s.borrow().clone()) {
596 st.save(key, value);
597 }
598}
599
600/// The launch deep link: the `DAY_DEEPLINK` environment variable, else the platform's
601/// [`set_launch_deeplink`] hint. Consumed by `launch_with` after the first mount.
602pub(crate) fn launch_deeplink() -> Option<String> {
603 std::env::var("DAY_DEEPLINK")
604 .ok()
605 .filter(|r| !r.is_empty())
606 // A route buffered by `request_route` before launch: a notification tap that cold-started
607 // the process. Peeked, not taken, so `has_launch_deeplink()` keeps answering true for a
608 // nav surface's `.restore` (a tap must beat restored state); `launch_with` takes it.
609 .or_else(day_process::routes::requested)
610 .or_else(|| LAUNCH_DEEPLINK.with(|l| l.borrow().clone()))
611 .filter(|r| !r.is_empty())
612}
613
614/// Navigate to a route (docs/navigation.md).
615///
616/// * `""`: pop the innermost stack to its root (falls through outward).
617/// * A single key is relative: innermost surface first, falling through outward.
618/// * `a/b/c` is absolute: anchor at the outermost surface that knows `a`, reset every surface
619/// inside the anchor to its root, then feed `b`, `c`, … inward (surfaces that mount during
620/// the cascade consume the rest as they register).
621/// * A trailing `?name=value&…` carries [`route_params`] to the destination builders.
622///
623/// False = no mounted surface recognized the (first) segment.
624pub fn navigate(route: &str) -> bool {
625 let (segments, params) = parse_route(route);
626 PENDING.with(|p| p.borrow_mut().clear());
627 PARAMS.with(|p| *p.borrow_mut() = Rc::new(params));
628 let ok = match segments.len() {
629 0 => dispatch(|nav| (nav.push)("")),
630 1 => dispatch(|nav| (nav.push)(&segments[0])),
631 _ => navigate_absolute(&segments),
632 };
633 maybe_notify_route_change();
634 ok
635}
636
637/// The surfaces inside `list[anchor]`, outermost first.
638///
639/// Ordered by [`NavController::depth`] rather than by registration, because a host that builds its
640/// pages before registering itself lands in the registry after what those pages contain, so an
641/// absolute `section/detail` would otherwise anchor on the section and find nothing beyond it.
642/// Depth only orders here, never filters: a subtree rebuilt outside its original build scope (a
643/// `when` arm re-derived on a size-class change) registers with a depth of zero, and equal depths
644/// keep registration order, which is the right answer in that case.
645fn nested_after(list: &[Rc<NavController>], anchor: usize) -> Vec<Rc<NavController>> {
646 let mut order: Vec<usize> = (0..list.len()).collect();
647 order.sort_by_key(|i| list[*i].depth);
648 let at = order.iter().position(|i| *i == anchor).unwrap_or(0);
649 order[at + 1..].iter().map(|i| list[*i].clone()).collect()
650}
651
652/// Anchor + descend for a multi-segment path. See [`navigate`].
653///
654/// Signal writes may propagate synchronously (an un-batched set cascades immediately), so the
655/// surfaces an anchor switch mounts can register, and must find their segments waiting,
656/// before the anchoring `push` even returns. Hence: queue the tail first, then anchor.
657fn navigate_absolute(segments: &[String]) -> bool {
658 let snapshot = || -> Vec<Rc<NavController>> {
659 NAV_STACK.with(|s| s.borrow().iter().map(|(_, c)| c.clone()).collect())
660 };
661 let controllers = snapshot();
662 let first = &segments[0];
663
664 // Already anchored: some surface is showing `first`. Reset everything inside it to its
665 // root (innermost-first, so stacks pop cleanly), then feed the remaining segments to the
666 // surviving inner surfaces in nesting order. Consult the live registry after the resets,
667 // because a reset can dispose deeper surfaces (a popped page takes its sub-surfaces with it).
668 if let Some(anchor) = controllers.iter().position(|c| (c.current)() == *first) {
669 PENDING.with(|p| *p.borrow_mut() = segments[1..].to_vec());
670 for c in nested_after(&controllers, anchor).iter().rev() {
671 let _ = (c.push)("");
672 }
673 let live = snapshot();
674 if let Some(anchor) = live.iter().position(|c| (c.current)() == *first) {
675 for c in nested_after(&live, anchor) {
676 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
677 if !(c.enter)(&front) {
678 break;
679 }
680 // `enter` may itself have consumed the segment: a push that mounts a surface
681 // registers it, and `register_nav` takes pending segments as it does. Only drop
682 // the head when it is still there.
683 PENDING.with(|p| {
684 let mut p = p.borrow_mut();
685 if !p.is_empty() {
686 p.remove(0);
687 }
688 });
689 }
690 }
691 }
692 return true;
693 }
694
695 // Switching: queue the tail so surfaces that mount during the (possibly synchronous)
696 // cascade consume it as they register, then anchor at the outermost surface that accepts
697 // the first segment.
698 PENDING.with(|p| *p.borrow_mut() = segments[1..].to_vec());
699 for c in &controllers {
700 if (c.push)(first) {
701 // Tabs may have already mounted the destination's nested surfaces. They will not
702 // register again on selection, so deliver the remaining segments here as well.
703 // Lazily mounted surfaces still consume the tail in `register_nav`.
704 let live = snapshot();
705 if let Some(anchor) = live.iter().position(|nav| Rc::ptr_eq(nav, c)) {
706 let nested: Vec<Rc<NavController>> = nested_after(&live, anchor)
707 .into_iter()
708 .filter(|nav| (nav.active)())
709 .collect();
710 // An explicit deeper path is the nested surfaces' whole state (set-semantics,
711 // as in the anchored branch above): a resident stack that still holds the
712 // pages of an earlier visit pops to its root before the tail lands, so
713 // `settings/general` followed later by `settings/privacy` reads
714 // `settings/privacy`, not `settings/general/privacy`. A bare section switch
715 // leaves what the user had open.
716 if PENDING.with(|p| !p.borrow().is_empty()) {
717 for child in nested.iter().rev() {
718 let _ = (child.push)("");
719 }
720 }
721 for child in nested {
722 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
723 if !(child.enter)(&front) {
724 break;
725 }
726 // `enter` may itself have consumed the segment: a push that mounts a surface
727 // registers it, and `register_nav` takes pending segments as it does. Only drop
728 // the head when it is still there.
729 PENDING.with(|p| {
730 let mut p = p.borrow_mut();
731 if !p.is_empty() {
732 p.remove(0);
733 }
734 });
735 }
736 }
737 }
738 return true;
739 }
740 }
741 // No mounted surface knows the first segment: offer the path to the fallbacks, each of
742 // which takes the rest of it itself.
743 for c in active_fallbacks() {
744 if (c.push)(first) {
745 while let Some(front) = PENDING.with(|p| p.borrow().first().cloned()) {
746 if !(c.enter)(&front) {
747 break;
748 }
749 PENDING.with(|p| {
750 let mut p = p.borrow_mut();
751 if !p.is_empty() {
752 p.remove(0);
753 }
754 });
755 }
756 return true;
757 }
758 }
759 PENDING.with(|p| p.borrow_mut().clear());
760 false
761}
762
763/// Pop one level, day-initiated (the toolkit presents the pop). Native-initiated pops arrive as
764/// `Event::NavBack` and go through the owning host's `pop` directly.
765///
766/// A back no surface takes runs the app's Back handler ([`BackHandler`]), as the platform's
767/// system back does, so dayscript's `nav_back` and a desktop's own Back control reach it too.
768pub fn nav_back() -> bool {
769 let ok = dispatch(|nav| (nav.pop)(false)) || run_back_handler();
770 maybe_notify_route_change();
771 ok
772}
773
774/// A navigation observer (§14.6): called with the new full route each time it changes, from any
775/// source: imperative `navigate`/`nav_back`, a `nav_link` or sidebar row (which navigate from an
776/// event handler, bypassing the event observer), a stack push, or a native back gesture. `""` is
777/// the root. Installed by the recorder in day-script; day-core only fires it.
778pub type NavObserver = dyn Fn(&str, Option<&str>);
779
780/// Install (or clear, with `None`) the navigation observer. Resets the dedup baseline so the next
781/// change fires regardless of where recording started.
782pub fn set_nav_observer(observer: Option<Box<NavObserver>>) {
783 NAV_OBSERVER.with(|o| *o.borrow_mut() = observer.map(Rc::from));
784 // Seed the baseline with the normalized route (an unmounted surface is `None` == `""`), so the
785 // first real navigation, not the None→"" transition at install, is what fires.
786 LAST_ROUTE.with(|r| *r.borrow_mut() = current_route().unwrap_or_default());
787}
788
789/// Announce a navigation to `route` from its source: a nav host (the sidebar nav host) calls
790/// this the instant it changes the bound selection, so the observer sees it synchronously instead
791/// of waiting for the route to settle into `NAV_STACK` a frame later (which `maybe_notify_route_change`
792/// reads). Deduped like the pump-boundary path. `route` is the host's local key, which replays as a
793/// relative `navigate` (innermost-first), correct for both a top-level sidebar and a nested one.
794pub fn note_navigation(route: &str, label: Option<&str>) {
795 let changed = LAST_ROUTE.with(|r| {
796 let mut r = r.borrow_mut();
797 if *r == route {
798 false
799 } else {
800 *r = route.to_string();
801 true
802 }
803 });
804 if !changed {
805 return;
806 }
807 let observer = NAV_OBSERVER.with(|o| o.borrow().clone());
808 if let Some(obs) = observer {
809 obs(route, label);
810 }
811}
812
813/// Fire the navigation observer if the full route changed since it was last told. Called at the
814/// tail of the event pump and of the imperative nav helpers; the dedup makes the redundant call a
815/// cheap no-op. The observer handle is cloned out first so it may re-enter (read the route, stop
816/// recording) without holding a borrow (mirrors the event observer in tree.rs).
817pub(crate) fn maybe_notify_route_change() {
818 let now = current_route().unwrap_or_default();
819 let changed = LAST_ROUTE.with(|r| {
820 let mut r = r.borrow_mut();
821 if *r == now {
822 false
823 } else {
824 (*r).clone_from(&now);
825 true
826 }
827 });
828 if !changed {
829 return;
830 }
831 let observer = NAV_OBSERVER.with(|o| o.borrow().clone());
832 if let Some(obs) = observer {
833 // No control context here (this is the settled-route fallback path); the source-notifying
834 // `note_navigation` supplies a label when a nav host has one.
835 obs(&now, None);
836 }
837}
838
839/// The full current route: every mounted surface's contribution, outermost to innermost,
840/// `/`-joined (docs/navigation.md). `None` = no surface mounted; `Some("")` = everything at
841/// its root. Round-trips through [`navigate`], so persisting navigation state is
842/// `save(current_route())` on the way out and `navigate(&saved)` on the way back in.
843#[must_use]
844pub fn current_route() -> Option<String> {
845 let controllers: Vec<Rc<NavController>> =
846 NAV_STACK.with(|s| s.borrow().iter().map(|(_, c)| c.clone()).collect());
847 if controllers.is_empty() {
848 return None;
849 }
850 // Outermost first, which is nesting order rather than registration order: a host that builds
851 // its pages before registering itself lands after what those pages contain
852 // (`NavController::depth`). Ties keep registration order, which is what siblings want.
853 let mut ordered = controllers;
854 ordered.sort_by_key(|c| c.depth);
855 let mut parts: Vec<String> = Vec::new();
856 for c in ordered {
857 // Only what is on screen. A resident page the host is not showing keeps its surfaces
858 // registered, and joining those in would append every unselected tab's state to the route.
859 if !(c.active)() {
860 continue;
861 }
862 parts.extend((c.segments)());
863 }
864 Some(encode_route(&parts, &[]))
865}
866
867#[cfg(test)]
868mod tests {
869 use super::*;
870
871 #[test]
872 fn route_parsing_round_trips() {
873 let (segs, params) = parse_route("mail/inbox/msg-42?hint=linked&x=1");
874 assert_eq!(segs, vec!["mail", "inbox", "msg-42"]);
875 assert_eq!(
876 params,
877 vec![("hint".into(), "linked".into()), ("x".into(), "1".into())]
878 );
879 assert_eq!(
880 encode_route(&segs, ¶ms),
881 "mail/inbox/msg-42?hint=linked&x=1"
882 );
883
884 // Reserved characters survive a round trip.
885 let segs = vec!["a/b".to_string()];
886 let params = vec![("q".to_string(), "1&2=3".to_string())];
887 let encoded = encode_route(&segs, ¶ms);
888 let (s2, p2) = parse_route(&encoded);
889 assert_eq!(s2, segs);
890 assert_eq!(p2, params);
891 }
892
893 #[test]
894 fn route_parsing_edge_cases() {
895 assert_eq!(parse_route(""), (vec![], vec![]));
896 assert_eq!(parse_route("a"), (vec!["a".to_string()], vec![]));
897 assert_eq!(parse_route("a//b").0, vec!["a", "b"]); // empty segments dropped
898 assert_eq!(
899 parse_route("?flag").1,
900 vec![("flag".to_string(), String::new())]
901 );
902 }
903
904 /// A controller that accepts the keys in `knows`, logging every call it answers.
905 fn recording(
906 knows: &'static [&'static str],
907 log: &Rc<RefCell<Vec<String>>>,
908 tag: &'static str,
909 ) -> NavController {
910 let (push_log, enter_log) = (log.clone(), log.clone());
911 NavController {
912 push: Box::new(move |route| {
913 let ok = knows.contains(&route);
914 if ok {
915 push_log.borrow_mut().push(format!("{tag} push {route}"));
916 }
917 ok
918 }),
919 pop: Box::new(|_| false),
920 current: Box::new(String::new),
921 enter: Box::new(move |segment| {
922 let ok = knows.contains(&segment);
923 if ok {
924 enter_log
925 .borrow_mut()
926 .push(format!("{tag} enter {segment}"));
927 }
928 ok
929 }),
930 segments: Box::new(Vec::new),
931 depth: 0,
932 layer: Box::new(|| 0),
933 active: Box::new(|| true),
934 }
935 }
936
937 /// A fallback registered before the app's navigation still loses a route the navigation
938 /// knows, whether the path is one segment or several.
939 #[test]
940 fn a_fallback_answers_only_what_no_surface_accepts() {
941 clear_controllers();
942 let log: Rc<RefCell<Vec<String>>> = Rc::default();
943 let cover = register_nav_fallback(recording(&["settings", "search"], &log, "cover"));
944 let _ = register_nav(recording(&["home", "settings"], &log, "app"));
945
946 assert!(navigate("settings/search"));
947 assert!(navigate("settings"));
948 assert_eq!(*log.borrow(), ["app push settings", "app push settings"]);
949 log.borrow_mut().clear();
950
951 // Nothing mounted knows `search`: the fallback takes it, alone or as a path's head.
952 assert!(navigate("search"));
953 assert_eq!(*log.borrow(), ["cover push search"]);
954 log.borrow_mut().clear();
955
956 unregister_nav(cover);
957 assert!(!navigate("search"));
958 assert!(log.borrow().is_empty());
959 clear_controllers();
960 }
961
962 /// With no surface that knows the head, the fallback takes the head and then the rest of the
963 /// path, and contributes nothing to the current route.
964 #[test]
965 fn a_fallback_takes_the_whole_path() {
966 clear_controllers();
967 let log: Rc<RefCell<Vec<String>>> = Rc::default();
968 let _ = register_nav(recording(&["home"], &log, "app"));
969 let _ = register_nav_fallback(recording(&["settings", "search"], &log, "cover"));
970
971 assert!(navigate("settings/search"));
972 assert_eq!(*log.borrow(), ["cover push settings", "cover enter search"]);
973 assert!(!navigate("elsewhere/search"));
974 clear_controllers();
975 }
976
977 /// The route buffer is process-global (it must be; see `request_route`), so the tests that
978 /// touch it cannot run in parallel with each other. Serialize them rather than making the
979 /// production type thread-local, which would defeat the purpose of the buffer.
980 static ROUTE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
981
982 fn route_test<T>(f: impl FnOnce() -> T) -> T {
983 let _guard = ROUTE_TEST_LOCK
984 .lock()
985 .unwrap_or_else(std::sync::PoisonError::into_inner);
986 let _ = take_requested_route();
987 let out = f();
988 let _ = take_requested_route();
989 out
990 }
991
992 /// The route-buffering assertions below describe the state a cold-start notification tap
993 /// arrives in: a process where NO backend has installed the main poster yet. They cannot run
994 /// beside the rest of this binary's tests.
995 ///
996 /// `day_reactive::install_main_poster` is a process-wide `OnceLock` that is never cleared, and
997 /// `present::task_tests` installs one: its executor wakers re-poll through `on_main`, so those
998 /// tests need it. Once installed, `request_route` takes its posting branch and the
999 /// inline poster runs `apply_route_request` immediately, draining the very buffer these
1000 /// assertions are about. libtest gives no ordering guarantee between the two groups, so this
1001 /// was a coin flip: the same commit passed on linux-aarch64 and failed on linux-x86_64.
1002 ///
1003 /// So they run in a child process. This test re-executes the test binary selecting only the
1004 /// ignored test below, which is the whole set of assertions; nothing else runs there, so no
1005 /// poster exists and the precondition holds by construction rather than by luck.
1006 #[test]
1007 fn route_buffering_before_launch() {
1008 let exe = std::env::current_exe().expect("the running test binary has a path");
1009 let out = std::process::Command::new(exe)
1010 .args([
1011 "--exact",
1012 "--ignored",
1013 "--nocapture",
1014 "--test-threads=1",
1015 "nav::tests::route_buffering_in_a_poster_free_process",
1016 ])
1017 .output()
1018 .expect("re-run this test binary for the child case");
1019 assert!(
1020 out.status.success(),
1021 "the poster-free route assertions failed in the child process:\n{}{}",
1022 String::from_utf8_lossy(&out.stdout),
1023 String::from_utf8_lossy(&out.stderr),
1024 );
1025 }
1026
1027 /// Every assertion that depends on no backend having started. Ignored so it runs only in the
1028 /// child process [`route_buffering_before_launch`] spawns; see that test for why.
1029 #[test]
1030 #[ignore = "needs a process with no main poster; run by route_buffering_before_launch"]
1031 fn route_buffering_in_a_poster_free_process() {
1032 assert!(
1033 !day_reactive::has_main_poster(),
1034 "this test must run in a process where no backend installed the poster; \
1035 it is meaningless otherwise, so failing loudly beats passing vacuously",
1036 );
1037
1038 // A tap that cold-starts the process buffers a route, and the launch path sees it.
1039 // Without this, `launch_deeplink()` would miss it and the app would open on its default
1040 // screen.
1041 route_test(|| {
1042 assert_eq!(launch_deeplink(), None);
1043 request_route("clock/timer");
1044 assert_eq!(launch_deeplink().as_deref(), Some("clock/timer"));
1045 // Peeked, not taken: a nav surface's `.restore` asks this so a tap beats restored state.
1046 assert!(has_launch_deeplink());
1047 assert_eq!(take_requested_route().as_deref(), Some("clock/timer"));
1048 assert_eq!(take_requested_route(), None);
1049 });
1050
1051 // The newest tap wins: a user who taps a second notification before launch completes gets
1052 // the second destination, not the first.
1053 route_test(|| {
1054 request_route("mail/inbox");
1055 request_route("clock/alarm");
1056 assert_eq!(take_requested_route().as_deref(), Some("clock/alarm"));
1057 });
1058
1059 // An empty route is not a navigation request: `navigate("")` means "pop to root", which a
1060 // missing intent extra must never trigger.
1061 route_test(|| {
1062 request_route("");
1063 assert_eq!(take_requested_route(), None);
1064 });
1065
1066 // `request_route` must not panic when no backend has started, which is exactly the state a
1067 // cold-start notification tap arrives in (`on_main` panics without a poster).
1068 route_test(|| {
1069 request_route("some/route"); // would panic if it posted unconditionally
1070 let _ = take_requested_route();
1071 });
1072
1073 // A part with no UI dependency records its tap through day-process, never calling into
1074 // this crate. The launch path must see that request exactly as it sees `request_route`'s.
1075 route_test(|| {
1076 day_process::routes::request("mail/inbox");
1077 assert_eq!(launch_deeplink().as_deref(), Some("mail/inbox"));
1078 assert!(has_launch_deeplink());
1079 assert_eq!(take_requested_route().as_deref(), Some("mail/inbox"));
1080 });
1081
1082 // The same holds when the request comes from another thread before launch: it is
1083 // buffered, and nothing is posted because there is no UI thread to post to yet.
1084 route_test(|| {
1085 install_route_notifier();
1086 std::thread::spawn(|| day_process::routes::request("clock/alarm"))
1087 .join()
1088 .expect("the requesting thread finishes");
1089 assert_eq!(take_requested_route().as_deref(), Some("clock/alarm"));
1090 });
1091 }
1092
1093 /// After launch, a request made through day-process on a worker thread is handed to the UI
1094 /// thread: the worker only posts, and the route is taken when the UI thread runs the post.
1095 /// A child process for the same reason as above: this installs the process-wide poster.
1096 #[test]
1097 fn route_from_a_worker_after_launch() {
1098 let exe = std::env::current_exe().expect("the running test binary has a path");
1099 let out = std::process::Command::new(exe)
1100 .args([
1101 "--exact",
1102 "--ignored",
1103 "--nocapture",
1104 "--test-threads=1",
1105 "nav::tests::route_handoff_in_a_launched_process",
1106 ])
1107 .output()
1108 .expect("re-run this test binary for the child case");
1109 assert!(
1110 out.status.success(),
1111 "the route handoff assertions failed in the child process:\n{}{}",
1112 String::from_utf8_lossy(&out.stdout),
1113 String::from_utf8_lossy(&out.stderr),
1114 );
1115 }
1116
1117 #[test]
1118 #[ignore = "installs the process-wide main poster; run by route_from_a_worker_after_launch"]
1119 fn route_handoff_in_a_launched_process() {
1120 type Posted = Box<dyn FnOnce() + Send>;
1121 static QUEUE: std::sync::Mutex<Vec<Posted>> = std::sync::Mutex::new(Vec::new());
1122
1123 // What a backend does at launch: a poster that queues work for the UI thread, and the
1124 // notifier that listens for requests made below the UI.
1125 day_reactive::install_main_poster(|work| QUEUE.lock().unwrap().push(work));
1126 install_route_notifier();
1127
1128 route_test(|| {
1129 std::thread::spawn(|| day_process::routes::request("mail/inbox"))
1130 .join()
1131 .expect("the requesting thread finishes");
1132
1133 // The worker posted once and applied nothing itself: the route is still buffered.
1134 assert_eq!(QUEUE.lock().unwrap().len(), 1);
1135 assert_eq!(
1136 day_process::routes::requested().as_deref(),
1137 Some("mail/inbox")
1138 );
1139
1140 // The UI thread runs the post, which takes the route to apply it.
1141 let posted: Vec<Posted> = std::mem::take(&mut *QUEUE.lock().unwrap());
1142 for work in posted {
1143 work();
1144 }
1145 assert_eq!(day_process::routes::requested(), None);
1146 });
1147
1148 // Two requests before the UI thread gets a turn: both post, the newest wins, and the
1149 // second post finds nothing left to apply.
1150 route_test(|| {
1151 for route in ["mail/inbox", "clock/alarm"] {
1152 std::thread::spawn(move || day_process::routes::request(route))
1153 .join()
1154 .expect("the requesting thread finishes");
1155 }
1156 assert_eq!(
1157 day_process::routes::requested().as_deref(),
1158 Some("clock/alarm")
1159 );
1160 let posted: Vec<Posted> = std::mem::take(&mut *QUEUE.lock().unwrap());
1161 assert_eq!(posted.len(), 2);
1162 for work in posted {
1163 work();
1164 }
1165 assert_eq!(day_process::routes::requested(), None);
1166 });
1167 }
1168}