day_pieces/nav.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Navigation. Imperative helpers (`navigate`, `nav_back`, `current_route`, `nav_link`); typed
5//! routes (the `Route` trait, the `routes!` macro, `RoutePath`); and the host pieces that project
6//! an app-owned `Signal` into native navigation: `nav` (tabs/sidebar), `nav_stack` (push/pop),
7//! and `cover` (modal), including nested-stack merging.
8
9use std::cell::{Cell, RefCell};
10use std::rc::Rc;
11
12use day_core::*;
13use day_reactive::{AnyBinding, Scope, Signal, bind, bind_seeded};
14use day_spec::{Event, Size, kinds};
15
16use crate::*;
17
18// ---------------------------------------------------------------------------
19// Navigation (docs/navigation.md): nav + stack, each a
20// projection of an app-owned Signal.
21// ---------------------------------------------------------------------------
22
23/// Navigate to a route (docs/navigation.md).
24///
25/// * A single key (`navigate("inbox")`) is relative: the innermost route surface is tried
26/// first, falling through outward; `""` pops the innermost stack to its root.
27/// * A `/`-separated path (`navigate("mail/inbox/msg-42")`) is absolute: anchored at the
28/// outermost surface that knows the first segment, everything inside reset, the remaining
29/// segments consumed inward (surfaces mounting during the cascade take theirs as they appear).
30/// * A trailing `?name=value&…` carries [`route_params`] to the destination builders.
31///
32/// False = no surface recognized the (first) segment.
33pub fn navigate(path: &str) -> bool {
34 day_core::navigate(path)
35}
36
37/// Pop one navigation level. False = nothing to pop.
38pub fn nav_back() -> bool {
39 day_core::nav_back()
40}
41
42/// The full current route: every mounted surface's contribution, outermost to innermost,
43/// `/`-joined. Round-trips through [`navigate`]: persist it on exit, `navigate(&saved)` on
44/// launch (docs/navigation.md).
45pub fn current_route() -> Option<String> {
46 day_core::current_route()
47}
48
49/// The query params of the most recent [`navigate`] (`?name=value&…`), read inside a
50/// destination builder. See docs/navigation.md for when params apply.
51pub fn route_params() -> std::rc::Rc<Vec<(String, String)>> {
52 day_core::route_params()
53}
54
55/// One query param of the most recent [`navigate`] (`None` = not present).
56pub fn route_param(name: &str) -> Option<String> {
57 day_core::route_param(name)
58}
59
60/// A tappable link that navigates to `path` when pressed.
61pub fn nav_link<M>(label: impl IntoText<M>, path: &str) -> Button {
62 let path = path.to_string();
63 button(label).action(move || {
64 let _ = day_core::navigate(&path);
65 })
66}
67
68// ---------------------------------------------------------------------------
69// Typed routes (docs/navigation.md): routes as data instead of string encoding.
70// ---------------------------------------------------------------------------
71
72/// A typed route key, the compile-checked alternative to raw string keys.
73///
74/// Implement on an enum (one variant per destination) and use it everywhere a key goes:
75/// `nav(Signal<Option<Section>>)` + `.item(Section::Controls, …)`,
76/// `nav_stack(Signal<Vec<Drill>>, …)` + `.destination(|d: &Drill| …)`, [`navigate_to`], [`route`].
77/// The string layer stays the wire format (deep links, dayscript, and [`current_route`]
78/// still speak [`Route::key`] strings), but app code never assembles or splits them.
79///
80/// Variants can carry data (`Item { id: u32 }` ↔ `"item-42"`): encode it in [`Route::key`],
81/// parse it back in [`Route::from_key`], and destination builders receive the typed value.
82/// For plain data-free enums the [`routes!`] macro writes both sides.
83pub trait Route: Clone + PartialEq + 'static {
84 /// The path segment this value occupies in a route string. Must round-trip through
85 /// [`Route::from_key`] and must not be empty; `""` means "no selection" (see the
86 /// `Option<R>` impl).
87 fn key(&self) -> String;
88 /// Parse a path segment back into the typed value; `None` = not one of this type's routes.
89 fn from_key(key: &str) -> Option<Self>;
90 /// The human-readable title shown in the native navigation bar when this route is the top of
91 /// a [`nav_stack`]. Defaults to [`key`](Route::key); override it to show a display name (e.g. an
92 /// app's name) instead of the wire key.
93 fn title(&self) -> String {
94 self.key()
95 }
96}
97
98/// Raw string keys, the untyped baseline. Every segment parses.
99impl Route for String {
100 fn key(&self) -> String {
101 self.clone()
102 }
103 fn from_key(key: &str) -> Option<Self> {
104 Some(key.to_string())
105 }
106}
107
108/// `None` ↔ `""` (no selection): the key type for a sidebar [`nav`], whose collapsed
109/// mobile state is "nothing selected". `.item(Section::X, …)` still takes the bare value
110/// (`Section: Into<Option<Section>>`).
111impl<R: Route> Route for Option<R> {
112 fn key(&self) -> String {
113 match self {
114 Some(r) => r.key(),
115 None => String::new(),
116 }
117 }
118 fn from_key(key: &str) -> Option<Self> {
119 if key.is_empty() {
120 Some(None)
121 } else {
122 R::from_key(key).map(Some)
123 }
124 }
125}
126
127/// Define a plain routes enum and its [`Route`] impl in one shot:
128///
129/// ```ignore
130/// day::routes! {
131/// pub enum Section { Controls => "controls", Text => "text" }
132/// }
133/// nav(section).item(Section::Controls, tr("controls"), controls_page)
134/// ```
135///
136/// A variant may add its display title after the key, anything a label takes (a string, or a
137/// localized `tr(…)` resolved when the page is pushed). It is what a [`nav_stack`] shows in the
138/// navigation bar for that route; a variant without one shows its key:
139///
140/// ```ignore
141/// day::routes! {
142/// enum Demo { Basics => "basics" (tr("demo-basics")), Stress => "stress" }
143/// }
144/// ```
145///
146/// Variants that carry data (`Item { id: u32 }` ↔ `"item-42"`) implement [`Route`] by hand.
147#[macro_export]
148macro_rules! routes {
149 ($(#[$meta:meta])* $vis:vis enum $name:ident {
150 $($(#[$vmeta:meta])* $variant:ident => $key:literal $(($title:expr))?),+ $(,)?
151 }) => {
152 $(#[$meta])*
153 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
154 $vis enum $name { $($(#[$vmeta])* $variant),+ }
155 impl $crate::Route for $name {
156 fn key(&self) -> String {
157 match self { $(Self::$variant => ($key).to_string()),+ }
158 }
159 fn from_key(key: &str) -> Option<Self> {
160 match key { $($key => Some(Self::$variant),)+ _ => None }
161 }
162 fn title(&self) -> String {
163 match self { $(Self::$variant => $crate::__route_title!($key $(, $title)?)),+ }
164 }
165 }
166 };
167}
168
169/// A [`routes!`] variant's title: its display title when it has one, else its key.
170#[doc(hidden)]
171#[macro_export]
172macro_rules! __route_title {
173 ($key:literal) => {
174 ($key).to_string()
175 };
176 ($key:literal, $title:expr) => {
177 $crate::route_title_text($title)
178 };
179}
180
181/// Resolve a [`routes!`] display title to the string the navigation bar shows.
182#[doc(hidden)]
183pub fn route_title_text<M>(title: impl crate::IntoText<M>) -> String {
184 title.into_text().initial()
185}
186
187/// A typed absolute route: segments built from [`Route`] values plus query params.
188/// `route(&Section::Stack).then(&Drill::Item { id: 42 }).param("hint", "linked")` encodes to
189/// `"stack/item-42?hint=linked"`; [`RoutePath::navigate`] it, or hand it to [`nav_link_to`].
190#[derive(Clone, Debug, Default)]
191pub struct RoutePath {
192 segments: Vec<String>,
193 params: Vec<(String, String)>,
194}
195
196/// Start a typed [`RoutePath`] at the outermost segment.
197pub fn route(first: &impl Route) -> RoutePath {
198 RoutePath {
199 segments: vec![first.key()],
200 params: Vec::new(),
201 }
202}
203
204impl RoutePath {
205 /// Append the next-inner segment.
206 pub fn then(mut self, next: &impl Route) -> Self {
207 self.segments.push(next.key());
208 self
209 }
210 /// Append a query param (the destination reads it via [`route_param`]).
211 pub fn param(mut self, name: &str, value: impl std::fmt::Display) -> Self {
212 self.params.push((name.to_string(), value.to_string()));
213 self
214 }
215 /// The encoded route string (percent-escaped where needed), the form [`navigate`] accepts.
216 pub fn to_route(&self) -> String {
217 day_core::encode_route(&self.segments, &self.params)
218 }
219 /// Navigate to this path. False = no surface recognized the first segment.
220 pub fn navigate(&self) -> bool {
221 day_core::navigate(&self.to_route())
222 }
223}
224
225impl std::fmt::Display for RoutePath {
226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 f.write_str(&self.to_route())
228 }
229}
230
231/// Navigate to a single typed key, relative (innermost surface first): the typed
232/// `navigate(&r.key())`, percent-escaped. For absolute paths chain a [`route`].
233pub fn navigate_to(r: &impl Route) -> bool {
234 day_core::navigate(&day_core::encode_route(std::slice::from_ref(&r.key()), &[]))
235}
236
237/// A tappable link that navigates to a typed [`RoutePath`] when pressed.
238pub fn nav_link_to<M>(label: impl IntoText<M>, path: RoutePath) -> Button {
239 let path = path.to_route();
240 button(label).action(move || {
241 let _ = day_core::navigate(&path);
242 })
243}
244
245// ---------------------------------------------------------------------------
246// Nested-nav merge (docs/navigation.md): a `nav_stack()` built inside a page of an enclosing NAV
247// host that presents as a push stack (mobile, `split == false`) pushes its pages onto that host
248// instead of minting a second native container: one native nav chain, one back button. The
249// enclosing host is threaded to nested pieces at build time via a thread-local context stack;
250// `owners` is the per-host ordered stack of "what a back on the topmost page does".
251// ---------------------------------------------------------------------------
252
253/// Performs the topmost page's back action. Arg = the toolkit already popped natively (iOS/Android
254/// system back), so the owner must not re-issue a pop.
255type PopOwner = Rc<dyn Fn(bool)>;
256
257#[derive(Clone)]
258struct NavHostCx {
259 host: RNode,
260 sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>>,
261 /// One entry per page pushed above the root, in native order; the host's single `NavBack`
262 /// handler invokes the last.
263 owners: Rc<RefCell<Vec<PopOwner>>>,
264 /// The enclosing host presents as split panes. A nested stack does not merge into a split
265 /// host; it keeps its own detail-pane stack. Shared and mutable because the host can
266 /// re-present under us: a page built while the window is narrow should merge, and one built
267 /// after it widens should not.
268 split: Rc<Cell<bool>>,
269 /// Votes to route this host's native back through Day (`NavPatch::GuardTop`): a guarded stack
270 /// above its root holds one, and so does a detail shown beside its composed list. Counted, so
271 /// one voter withdrawing never disarms another.
272 guards: Rc<Cell<usize>>,
273}
274
275impl NavHostCx {
276 /// Add (`true`) or withdraw (`false`) one vote to route the native back through Day. The
277 /// patch goes out only when the count crosses zero.
278 fn vote_guard(&self, on: bool) {
279 let was = self.guards.get();
280 let now = if on { was + 1 } else { was.saturating_sub(1) };
281 self.guards.set(now);
282 if (was == 0) != (now == 0) {
283 let host = self.host;
284 with_tree(|t| {
285 t.patch(
286 host,
287 Box::new(day_spec::props::NavPatch::GuardTop(now > 0)),
288 false,
289 )
290 });
291 }
292 }
293}
294
295day_reactive::tls_slots! { nav;
296 /// Increasing presentation order for fullscreen navigation layers.
297 static NEXT_COVER_LAYER: Cell<u64> = const { Cell::new(1) };
298 /// Build-time stack of enclosing nav hosts. `None` is a barrier (a resident container such as
299 /// tabs) that a nested stack must not merge through.
300 static NAV_HOST_CX: RefCell<Vec<Option<NavHostCx>>> = const { RefCell::new(Vec::new()) };
301 /// Build-time stack of "is the page I am being built into the one its host shows?", one entry
302 /// per enclosing resident page. Only a chrome host (a tab bar, a rail) pushes one: everywhere
303 /// else the outgoing page is torn down, so a surface that still exists is by definition the
304 /// one on screen. A surface captures the whole stack at registration and is on screen only
305 /// when every gate above it answers true.
306 static NAV_PAGE_ACTIVE: RefCell<Vec<Rc<dyn Fn() -> bool>>> = const { RefCell::new(Vec::new()) };
307
308 /// How many routed one-of-N surfaces (`nav`/tabs) are live at each nesting depth. Two at
309 /// the same depth are siblings whose keys both flow into `current_route()`, the case that
310 /// wants `.local()` (docs/navigation.md). Used only to warn; never changes behavior.
311 static ROUTED_ONE_OF_N: RefCell<std::collections::HashMap<usize, usize>> =
312 RefCell::new(std::collections::HashMap::new());
313}
314
315/// Build `f` with `gate` deciding whether what it builds counts as on screen (`NAV_PAGE_ACTIVE`).
316fn with_page_active<R>(gate: Rc<dyn Fn() -> bool>, f: impl FnOnce() -> R) -> R {
317 NAV_PAGE_ACTIVE.with(|s| s.borrow_mut().push(gate));
318 let r = f();
319 NAV_PAGE_ACTIVE.with(|s| {
320 s.borrow_mut().pop();
321 });
322 r
323}
324
325/// A document can leave the resident container for its own native window. Replace
326/// its selection gate while retaining enclosing navigation gates and nested-page gates.
327pub(crate) fn with_document_active<R>(gate: Rc<dyn Fn() -> bool>, f: impl FnOnce() -> R) -> R {
328 struct Restore(Option<Rc<dyn Fn() -> bool>>);
329 impl Drop for Restore {
330 fn drop(&mut self) {
331 NAV_PAGE_ACTIVE.with(|s| {
332 let mut s = s.borrow_mut();
333 s.pop();
334 if let Some(previous) = self.0.take() {
335 s.push(previous);
336 }
337 });
338 }
339 }
340 let previous = NAV_PAGE_ACTIVE.with(|s| {
341 let mut s = s.borrow_mut();
342 let previous = s.pop();
343 s.push(gate);
344 previous
345 });
346 let _restore = Restore(previous);
347 f()
348}
349
350/// Run `f` with `cx` as the innermost nav-host context (a barrier when `None`), restoring after.
351fn with_nav_host<R>(cx: Option<NavHostCx>, f: impl FnOnce() -> R) -> R {
352 NAV_HOST_CX.with(|s| s.borrow_mut().push(cx));
353 let r = f();
354 NAV_HOST_CX.with(|s| {
355 s.borrow_mut().pop();
356 });
357 r
358}
359
360/// The innermost mergeable nav host, if any (a barrier or an empty stack yields `None`).
361fn current_nav_host() -> Option<NavHostCx> {
362 NAV_HOST_CX.with(|s| s.borrow().last().cloned().flatten())
363}
364
365/// Create a NAV_PAGE under `host` and wire its FrameChanged size reports into `sizes`
366/// (the native container owns each page's frame; Day lays content out at the reported size).
367fn nav_page(
368 host: RNode,
369 props: &day_spec::props::NavPageProps,
370 sizes: &Rc<RefCell<std::collections::HashMap<RNode, Size>>>,
371) -> RNode {
372 let mut cx = BuildCx::new(host);
373 let page = cx.native(
374 kinds::NAV_PAGE,
375 props,
376 Rc::new(PassThrough),
377 Flex::default(),
378 Boundary::Yes,
379 );
380 let sizes = sizes.clone();
381 cx.on(page, move |ev| {
382 if let Event::FrameChanged(sz) = ev {
383 let changed = sizes.borrow().get(&page) != Some(sz);
384 if changed {
385 sizes.borrow_mut().insert(page, *sz);
386 with_tree(|t| {
387 t.mark_needs_measure(page);
388 t.mark_layout_dirty();
389 t.layout_if_needed();
390 });
391 }
392 }
393 });
394 page
395}
396
397/// Whether a list layer is the thing the user is looking at (docs/toolbars.md).
398///
399/// One rule, three sites: the native content-list pane, and the composed gated flow's two shapes.
400/// A list's commands (add, filter, sort) act on rows the user can see, so they leave the
401/// window's bar the moment something covers them. Two ways that happens: the destination
402/// collapses the pane (`content_list_for`), or a detail is pushed over it on a shape that shows
403/// one layer at a time. Side by side, both layers are up and both keep their commands.
404fn list_layer_gate(
405 visible: Option<Signal<bool>>,
406 detail_open: Option<AnyBinding<bool>>,
407 pres: Option<Signal<day_spec::props::NavPresentation>>,
408) -> Rc<dyn Fn() -> bool> {
409 // `try_get` throughout: a gate is asked at merge time, which can be a window's
410 // teardown, so a disposed signal answers "not showing" rather than panicking.
411 Rc::new(move || {
412 let shown = visible.is_none_or(|v| v.try_get().unwrap_or(false));
413 let side_by_side = pres.is_some_and(|p| p.try_get().is_some_and(|p| p.is_split()));
414 shown && (side_by_side || detail_open.is_none_or(|d| !d.try_get().unwrap_or(false)))
415 })
416}
417
418/// The navigation page being built, captured so a piece built later (a `when` arm a morph
419/// re-runs) can build inside it again: its commands then land on that page's chrome, under
420/// its gate (docs/toolbars.md).
421#[derive(Clone)]
422struct PageContext {
423 chrome: day_core::Chrome,
424 gate: Option<Rc<dyn Fn() -> bool>>,
425 column: day_spec::ToolbarColumn,
426 window: RNode,
427}
428
429impl PageContext {
430 fn current() -> PageContext {
431 PageContext {
432 chrome: day_core::current_chrome(),
433 gate: day_core::current_page_gate(),
434 column: day_core::current_page_column(),
435 window: day_core::current_page_window(),
436 }
437 }
438
439 /// `piece`, built inside the captured page (as is, before one was captured).
440 fn enter(at: &Rc<RefCell<Option<PageContext>>>, piece: impl Piece + 'static) -> AnyPiece {
441 let at = at.clone();
442 AnyPiece::new(piece_fn(move |cx| {
443 let ctx = at.borrow().clone();
444 match ctx {
445 Some(PageContext {
446 chrome: day_core::Chrome::Page(page),
447 gate,
448 column,
449 window,
450 }) => day_core::with_page_in(page, gate, column, window, || piece.build(cx)),
451 _ => piece.build(cx),
452 }
453 }))
454 }
455}
456
457/// `gate`, and the gate of the page being built (a tab's "selected"), when it has one: a list
458/// registered inline in a page shows its commands only while that page does too.
459fn within_page_gate(gate: Rc<dyn Fn() -> bool>) -> Rc<dyn Fn() -> bool> {
460 match day_core::current_page_gate() {
461 Some(outer) => Rc::new(move || outer() && gate()),
462 None => gate,
463 }
464}
465
466/// Whether a destination page is the one showing: the selection is on it (docs/toolbars.md).
467fn destination_gate<K: Route, S: Binding<K> + 'static>(
468 selection: S,
469 key: String,
470) -> Rc<dyn Fn() -> bool> {
471 Rc::new(move || selection.read().key() == key)
472}
473
474// Scope context survives reactive content rebuilds after the build-time nav stack unwinds.
475#[derive(Clone, Default)]
476struct NavLayer {
477 order: Rc<Cell<u64>>,
478 depth: usize,
479}
480
481/// Register a string-route adapter over a route surface's own signal, so `navigate()` /
482/// deep links / dayscript keep working by key. This is a convenience layer: the surface
483/// itself is driven by the signal, not by this registry (docs/navigation.md).
484///
485/// `enter` consumes one segment of an absolute path (`navigate("a/b/c")`); `segments` is the
486/// surface's contribution to the full [`current_route`].
487fn register_route_surface(
488 push: impl Fn(&str) -> bool + 'static,
489 pop: impl Fn(bool) -> bool + 'static,
490 current: impl Fn() -> String + 'static,
491 enter: impl Fn(&str) -> bool + 'static,
492 segments: impl Fn() -> Vec<String> + 'static,
493) {
494 register_route_surface_in_layer(
495 Scope::current()
496 .use_context::<NavLayer>()
497 .unwrap_or_default(),
498 push,
499 pop,
500 current,
501 enter,
502 segments,
503 );
504}
505
506fn register_route_surface_in_layer(
507 layer: NavLayer,
508 push: impl Fn(&str) -> bool + 'static,
509 pop: impl Fn(bool) -> bool + 'static,
510 current: impl Fn() -> String + 'static,
511 enter: impl Fn(&str) -> bool + 'static,
512 segments: impl Fn() -> Vec<String> + 'static,
513) {
514 // The nesting depth day-core descends by. `NAV_HOST_CX` is the stack of hosts this build is
515 // inside, so its length is how deep this surface sits, and unlike registration order it does
516 // not depend on whether a host registers before or after building its pages.
517 let depth = layer.depth + NAV_HOST_CX.with(|s| s.borrow().len());
518 // The resident pages this surface is built inside, captured now because the stack unwinds as
519 // soon as the build returns. Empty for a surface at the window root, which is then always on
520 // screen, since `all` over nothing is true.
521 let gates: Vec<Rc<dyn Fn() -> bool>> = NAV_PAGE_ACTIVE.with(|s| s.borrow().clone());
522 let token = day_core::register_nav(day_core::NavController {
523 depth,
524 layer: Box::new(move || layer.order.get()),
525 push: Box::new(push),
526 pop: Box::new(pop),
527 current: Box::new(current),
528 enter: Box::new(enter),
529 segments: Box::new(segments),
530 active: Box::new(move || gates.iter().all(|g| g())),
531 });
532 Scope::current().on_cleanup(move || day_core::unregister_nav(token));
533}
534
535/// Register an app-level Back handler for [`Decorate::on_system_back`] under `at`, the node the
536/// decorated piece is built under (docs/navigation.md "Handling the system Back"). Records the
537/// containing cover's layer and the resident pages around the handler; day-core ranks by layer,
538/// then by `at`'s depth in the piece tree, then by recency. Lives as long as the current scope.
539pub(crate) fn install_back_handler(at: RNode, enabled: Reactive<bool>, handler: Rc<dyn Fn()>) {
540 let order = Scope::current()
541 .use_context::<NavLayer>()
542 .unwrap_or_default()
543 .order;
544 // Captured now, as `register_route_surface_in_layer` does: a handler in a tab the bar is not
545 // showing must not take the back.
546 let gates: Rc<[Rc<dyn Fn() -> bool>]> = NAV_PAGE_ACTIVE.with(|s| s.borrow().clone()).into();
547 let on_screen = move || gates.iter().all(|g| g());
548 let wants = enabled.clone();
549 let token = day_core::register_back_handler(day_core::BackHandler {
550 node: at,
551 layer: Box::new(move || order.get()),
552 active: Box::new(on_screen.clone()),
553 enabled: Box::new(move || wants.get_untracked()),
554 run: Box::new(move || handler()),
555 });
556 Scope::current().on_cleanup(move || day_core::unregister_nav(token));
557 // Re-arm the system back whenever this handler's answer can change: its own `enabled`, or the
558 // selection of a resident page around it. A tab selected from code (a signal write,
559 // `navigate`) passes through no event, so the event pump's own re-check never sees it.
560 bind(
561 move || on_screen() && enabled.get(),
562 |_: &bool| day_core::sync_system_back(),
563 );
564}
565
566/// Note a routed nav/tabs at the current nav depth and, in debug builds, warn if it is a
567/// sibling of another routed one-of-N surface, the case `.local()` exists for
568/// (docs/navigation.md). The count is decremented when the surface's scope disposes, so
569/// switching sections doesn't leak. A stack is exempt (its whole path is one surface's
570/// contribution; sibling stacks are a documented layout), as is a cover (its segment is empty
571/// unless presented).
572fn note_routed_one_of_n(kind: &str) {
573 let depth = NAV_HOST_CX.with(|s| s.borrow().len());
574 let count = ROUTED_ONE_OF_N.with(|m| {
575 let mut m = m.borrow_mut();
576 let c = m.entry(depth).or_insert(0);
577 *c += 1;
578 *c
579 });
580 if count > 1 {
581 warn_sibling_selectors(kind);
582 }
583 Scope::current().on_cleanup(move || {
584 ROUTED_ONE_OF_N.with(|m| {
585 if let Some(c) = m.borrow_mut().get_mut(&depth) {
586 *c = c.saturating_sub(1);
587 }
588 });
589 });
590}
591
592#[cfg(debug_assertions)]
593fn warn_sibling_selectors(kind: &str) {
594 log::warn!(
595 "two routed one-of-N surfaces ({kind}) are mounted at the same navigation level. \
596 Their keys both flow into current_route(), so you'll see `section/childA/childB` and \
597 `navigate(\"child\")` is ambiguous. Mark all but the primary one `.local()` \
598 (docs/navigation.md)."
599 );
600}
601
602#[cfg(not(debug_assertions))]
603fn warn_sibling_selectors(_kind: &str) {}
604
605// ===========================================================================
606// Nav: one-of-N, bound to a Signal<String> of the active key.
607// ===========================================================================
608
609/// How a [`nav`] presents its one-of-N choice (docs/navigation.md).
610///
611/// The default is [`Self::Automatic`]: unless you say otherwise, a nav wears whatever the
612/// platform wears at the window's current width, and changes as the window does.
613#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
614pub enum NavStyle {
615 /// **The default.** The platform's own answer at this size: a tab bar on a phone-shaped
616 /// window, a rail in the middle, a sidebar beside the detail when there is room, and it
617 /// re-presents live as the window crosses a breakpoint (docs/size-classes.md).
618 ///
619 /// This is `.tabViewStyle(.sidebarAdaptable)`'s job, and the native containers it maps to
620 /// are the ones the platforms built for it: `UITabBarController` in `.tabSidebar` mode, a
621 /// `NavigationView` driving its own `PaneDisplayMode`, a Material navigation bar / rail /
622 /// drawer. A toolkit that cannot draw a tab bar (`Cap::NavTabs`) degrades to [`Self::Sidebar`]
623 /// rather than to a hole.
624 #[default]
625 Automatic,
626 /// Pinned: a tab bar at every size, however wide the window gets. Reach for it when the
627 /// content is peer sections that should never become a sidebar.
628 Tabs,
629 /// Pinned: a NavigationSplitView, a sidebar list + a detail. Wide windows show both panes
630 /// (on GTK an `AdwNavigationSplitView`); narrow ones collapse to a list that pushes the
631 /// detail, which is the one shape [`Self::Automatic`] never produces on its own.
632 Sidebar,
633}
634
635/// A built detail page of a nav, and what it takes to tear it down. Exactly one of these
636/// exists per shown page in a split or stacked presentation; one per visited page in a
637/// presentation whose rows are chrome, where pages are resident (docs/navigation.md).
638struct ResidentPage {
639 /// The item key this page was built for, the identity a re-selection matches on.
640 key: String,
641 /// The page's own reactive scope; disposing it runs the content's cleanup.
642 scope: Scope,
643 /// The `NAV_PAGE` node, in the host's detail-child attach order. Its index in the owning
644 /// `Vec` is what `NavPatch::Select` addresses.
645 node: RNode,
646}
647
648/// Builds the page for a data-driven key (`&K` → piece): a nav's `.destination` fallback
649/// or a stack's `.destination`.
650type DestFn<K> = Rc<dyn Fn(&K) -> AnyPiece>;
651
652/// Which destinations show the content-list pane (`Nav::content_list_for`).
653type ListPred<K> = Rc<dyn Fn(&K) -> bool>;
654
655/// Completions for a search field's current text (`Nav::search_suggestions`).
656type SuggestFn = Rc<dyn Fn(&str) -> Vec<String>>;
657
658/// The toolbar item id a `.searchable()` surface's field carries when its placement resolves to
659/// the window toolbar (docs/search.md). Reserved and stable: dayscript's `toolbar:` step addresses
660/// the field by this id, and it is Day's own rather than the app's, since the app never declares
661/// the item.
662pub const SEARCH_ITEM_ID: &str = day_spec::SEARCH_ITEM_ID;
663
664/// The flattened live rows a nav's dynamic blocks derive to: per-row key strings, typed
665/// keys, titles, and icons (index-aligned). Carried through the reconcile `bind`.
666/// One tracked derive of a nav's rows: (key strings, typed keys, titles, icons, badges,
667/// section headers). Compared by equality to gate the re-patch, so every decoration a backend
668/// renders has to ride along; a badge that changed but was not carried here would not repaint.
669type DerivedRows<K> = (
670 Vec<String>,
671 Vec<K>,
672 Vec<String>,
673 Vec<Option<String>>,
674 Vec<Option<String>>,
675 Vec<Option<String>>,
676 Vec<Option<day_spec::Color>>,
677 Vec<Vec<day_spec::MenuItem>>,
678 Vec<Option<String>>,
679 Vec<Option<day_spec::Color>>,
680);
681
682/// The rows the native menu last received, to tell a value change (`rows_changed`) from a new
683/// row set.
684struct ShownRows {
685 keys: Vec<String>,
686 titles: Vec<String>,
687 icons: Vec<Option<String>>,
688 badges: Vec<Option<String>>,
689 badge_icons: Vec<Option<String>>,
690 badge_tints: Vec<Option<day_spec::Color>>,
691 sections: Vec<Option<String>>,
692 tints: Vec<Option<day_spec::Color>>,
693 menus: Vec<Vec<day_spec::MenuItem>>,
694}
695
696impl<K: Route> NavRows<K> {
697 fn shown(&self) -> ShownRows {
698 ShownRows {
699 keys: self.keys.iter().map(|k| k.key()).collect(),
700 titles: self.titles.clone(),
701 icons: self.icons.clone(),
702 badges: self.badges.clone(),
703 badge_icons: self.badge_icons.clone(),
704 badge_tints: self.badge_tints.clone(),
705 sections: self.sections.clone(),
706 tints: self.tints.clone(),
707 menus: self.menus.clone(),
708 }
709 }
710}
711
712#[derive(Clone)]
713#[doc(hidden)]
714pub struct SectionHeader {
715 id: Option<String>,
716 title: TextSource,
717}
718
719#[doc(hidden)]
720pub struct SelItem<K> {
721 key: K,
722 title: TextSource,
723 /// Optional bundled-image name for the item's native icon (docs/navigation.md).
724 icon: Option<String>,
725 /// Optional per-row icon tint (docs/vectors.md).
726 tint: Option<day_spec::Color>,
727 /// Per-row context menu (docs/menus.md), already lowered: items carry registered
728 /// action ids. Empty = no menu.
729 menu: Vec<day_spec::MenuItem>,
730 /// Trailing accessory (an unread count). A `TextSource` so a live count retitles on its
731 /// own signal, and so a localized badge follows `set_locale`.
732 badge: Option<TextSource>,
733 /// Trailing accessory glyph, in the same slot as `badge` (docs/navigation.md).
734 badge_icon: Option<String>,
735 /// Tint for `badge_icon`; `None` leaves it at the backend's neutral template tint.
736 badge_tint: Option<day_spec::Color>,
737 /// Header introducing the group this item opens (docs/navigation.md).
738 section: Option<SectionHeader>,
739 /// Immersive-chrome page (docs/navigation.md): keeps the floating transparent bar on
740 /// backends with an immersive nav mode; standard opaque bar otherwise.
741 immersive: bool,
742 /// The item's own page builder ([`NavItem::page`]); an item without one is built by the
743 /// nav's `.destination` fallback.
744 build: Option<PageFn>,
745}
746
747/// A page builder, shared between an item and the nav's builder map.
748type PageFn = Rc<dyn Fn() -> AnyPiece>;
749
750/// One nav item (docs/navigation.md): a key, a title, and its decorations, built by [`item`].
751/// The same value describes a static destination (`item("home", title).page(home_page)`) and
752/// a row of a data-driven block (`nav_items(move || feeds(), |f| item(f.id, f.name))`).
753pub struct NavItem<K = String> {
754 key: K,
755 title: TextSource,
756 icon: Option<String>,
757 icon_tint: Option<day_spec::Color>,
758 menu: Vec<day_spec::MenuItem>,
759 badge: Option<TextSource>,
760 badge_icon: Option<String>,
761 badge_tint: Option<day_spec::Color>,
762 section: Option<SectionHeader>,
763 immersive: bool,
764 page: Option<PageFn>,
765}
766
767/// A nav item: `item("today", res::str::today()).icon(res::images::today).page(today_page)`
768/// (docs/navigation.md). Goes into a [`Nav::items`] or [`Nav::section`] block, alone, in a
769/// tuple, or from a [`nav_items`] mapper; an item without a [`page`](NavItem::page) is built by
770/// the nav's [`Nav::destination`]. For a typed nav over `Option<Section>` pass the bare
771/// `Section::X`.
772pub fn item<M, K, I: Into<K>>(key: I, title: impl IntoText<M>) -> NavItem<K> {
773 NavItem {
774 key: key.into(),
775 icon_tint: None,
776 menu: Vec::new(),
777 title: title.into_text(),
778 icon: None,
779 badge: None,
780 badge_icon: None,
781 badge_tint: None,
782 section: None,
783 immersive: false,
784 page: None,
785 }
786}
787
788impl<K> NavItem<K> {
789 /// The page this item opens; `build` runs when the item is first shown. An item without
790 /// one is built by the nav's [`Nav::destination`], the usual choice for a data-driven block
791 /// whose rows share one page shape.
792 pub fn page<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
793 self.page = Some(Rc::new(move || AnyPiece::new(build())));
794 self
795 }
796 /// A bundled-image name for the item's native icon (typed [`ImageName`](day_spec::ImageName),
797 /// resolved like [`image()`], e.g. `res::images::nav_home`), or an absolute local image path
798 /// supplied as an owned string. Shown beside the label where the backend's nav supports it
799 /// (the Windows NavigationView, the iOS/macOS source list); backends that can't decorate
800 /// rows ignore it. AppKit/UIKit preserve the colors of local files; bundled glyphs remain
801 /// templates.
802 pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
803 self.icon = Some(icon.into().as_str().to_owned());
804 self
805 }
806 /// Tint this row's icon (docs/vectors.md): the glyph recolors to `color` instead of the
807 /// backend's neutral template tint. Backends without per-row tinting keep the neutral look.
808 pub fn icon_tint(mut self, color: day_spec::Color) -> Self {
809 self.icon_tint = Some(color);
810 self
811 }
812 /// Attach a context menu to this row (docs/menus.md): shown on secondary-click /
813 /// long-press, the same `menu_item`/`sub_menu` builders as everywhere else. A chosen
814 /// entry runs its action exactly like a piece context menu. Backends without per-row
815 /// menus drop it (see the matrix in docs/menus.md).
816 pub fn context_menu(
817 mut self,
818 entries: impl IntoIterator<Item = crate::menus::MenuEntry>,
819 ) -> Self {
820 // Scoped: row menus are re-lowered on every derive; the previous build's closures
821 // are reclaimed when the registering scope (the nav's surface) is disposed.
822 self.menu = crate::menus::lower_menu_scoped(entries.into_iter().collect());
823 self
824 }
825 /// A trailing accessory for this row (an unread count, a status). Rendered right-aligned
826 /// and de-emphasized where the toolkit has an affordance for it, and dropped where it does
827 /// not (see docs/coverage-matrix.md). Empty text shows no badge, so a count can return `""`
828 /// at zero.
829 pub fn badge<M>(mut self, badge: impl IntoText<M>) -> Self {
830 self.badge = Some(badge.into_text());
831 self
832 }
833 /// A trailing accessory glyph for this row, in the same slot as [`Self::badge`] and drawn
834 /// after it. Takes a bundled image name exactly as [`Self::icon`] does, so a symbol
835 /// (`Symbol::Star`) or an app image both work.
836 ///
837 /// This is what a row-level status gets drawn with (a starred page's star) where `badge`
838 /// carries a count or a word. Pair it with [`Self::badge_tint`] when the glyph's color is
839 /// part of its meaning; left untinted it takes the backend's neutral template tint and reads
840 /// as another piece of chrome.
841 pub fn badge_icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
842 self.badge_icon = Some(icon.into().to_string());
843 self
844 }
845 /// The color for [`Self::badge_icon`]. `None` (the default) keeps the neutral template tint.
846 pub fn badge_tint(mut self, color: day_spec::Color) -> Self {
847 self.badge_tint = Some(color);
848 self
849 }
850 /// Open a new section with this header, immediately before this row.
851 pub fn section<M>(mut self, title: impl IntoText<M>) -> Self {
852 self.section = Some(SectionHeader {
853 id: None,
854 title: title.into_text(),
855 });
856 self
857 }
858 /// Open a section with an identity independent of its localized title or first row.
859 pub fn section_id<M>(mut self, id: impl Into<String>, title: impl IntoText<M>) -> Self {
860 self.section = Some(SectionHeader {
861 id: Some(id.into()),
862 title: title.into_text(),
863 });
864 self
865 }
866 /// Mark this item's pushed page immersive-chrome (docs/navigation.md): on backends with an
867 /// immersive nav mode (android edge-to-edge today) its pushed page keeps the floating
868 /// transparent bar over full-bleed content; unmarked pages get the standard opaque bar. A
869 /// no-op on every other backend.
870 pub fn immersive(mut self) -> Self {
871 self.immersive = true;
872 self
873 }
874
875 fn into_source(self) -> ItemSource<K> {
876 ItemSource::Static(SelItem {
877 key: self.key,
878 title: self.title,
879 icon: self.icon,
880 tint: self.icon_tint,
881 menu: self.menu,
882 badge: self.badge,
883 badge_icon: self.badge_icon,
884 badge_tint: self.badge_tint,
885 section: self.section,
886 immersive: self.immersive,
887 build: self.page,
888 })
889 }
890}
891
892/// A data-driven block of nav items (docs/navigation.md), built by [`nav_items`]: re-derives
893/// whenever the signal changes.
894pub struct NavItems<K> {
895 derive: Box<dyn Fn() -> Vec<SelItem<K>>>,
896}
897
898/// A data-driven item block: `nav_items(move || st.feeds.get(), |f| item(f.id, f.name).icon(…))`
899/// (docs/navigation.md). `items` is a tracked reader (a `Signal<Vec<T>>` via its `Fn()` deref,
900/// or a closure); the block re-derives whenever it changes: rows are added and removed on the
901/// native sidebar/tab widget, and if the selected key disappears the selection resets (to
902/// `None` for an `Option` key). Static items and blocks may be mixed; the final list is their
903/// declaration order. A row without its own [`page`](NavItem::page) is built by the nav's
904/// [`Nav::destination`].
905pub fn nav_items<T: Clone + 'static, K: 'static>(
906 items: impl Fn() -> Vec<T> + 'static,
907 map: impl Fn(&T) -> NavItem<K> + 'static,
908) -> NavItems<K> {
909 NavItems {
910 derive: Box::new(move || {
911 items()
912 .iter()
913 .map(|t| match map(t).into_source() {
914 ItemSource::Static(it) => it,
915 ItemSource::Dynamic(_) => unreachable!("an item maps to one row"),
916 })
917 .collect()
918 }),
919 }
920}
921
922/// What a [`Nav::items`] or [`Nav::section`] block takes: one [`NavItem`], a tuple of them, an
923/// `Option` (an item the platform may not want: `prefs.nav_item(key)`), a `Vec` or array, or a
924/// data-driven [`nav_items`] block. Any mix nests: `(item(..), nav_items(..), Some(item(..)))`.
925pub trait NavContent<K> {
926 /// Append this content's sources, in order.
927 fn push_sources(self, out: &mut Vec<ItemSource<K>>);
928}
929
930impl<K> NavContent<K> for NavItem<K> {
931 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
932 out.push(self.into_source());
933 }
934}
935
936impl<K: 'static> NavContent<K> for NavItems<K> {
937 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
938 out.push(ItemSource::Dynamic(self.derive));
939 }
940}
941
942impl<K, C: NavContent<K>> NavContent<K> for Option<C> {
943 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
944 if let Some(c) = self {
945 c.push_sources(out);
946 }
947 }
948}
949
950impl<K, C: NavContent<K>> NavContent<K> for Vec<C> {
951 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
952 for c in self {
953 c.push_sources(out);
954 }
955 }
956}
957
958impl<K, C: NavContent<K>, const N: usize> NavContent<K> for [C; N] {
959 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
960 for c in self {
961 c.push_sources(out);
962 }
963 }
964}
965
966impl<K> NavContent<K> for () {
967 fn push_sources(self, _out: &mut Vec<ItemSource<K>>) {}
968}
969
970macro_rules! impl_nav_content_tuple {
971 ($($name:ident),+) => {
972 impl<K, $($name: NavContent<K>),+> NavContent<K> for ($($name,)+) {
973 #[allow(non_snake_case)]
974 fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
975 let ($($name,)+) = self;
976 $($name.push_sources(out);)+
977 }
978 }
979 };
980}
981impl_nav_content_tuple!(A);
982impl_nav_content_tuple!(A, B);
983impl_nav_content_tuple!(A, B, C);
984impl_nav_content_tuple!(A, B, C, D);
985impl_nav_content_tuple!(A, B, C, D, E);
986impl_nav_content_tuple!(A, B, C, D, E, F);
987impl_nav_content_tuple!(A, B, C, D, E, F, G);
988impl_nav_content_tuple!(A, B, C, D, E, F, G, H);
989impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I);
990impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J);
991impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J, L);
992impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J, L, N);
993
994/// A source of nav items: a fixed item, or a signal-driven block that re-derives its items
995/// when the signal changes (docs/navigation.md).
996// Boxing `Static` would trade an allocation per row for a saving that is nominal here: these
997// enums live in one `Vec` built once when a nav is constructed, a few dozen entries at most,
998// and the static case is the overwhelmingly common one. The gap is only this wide because a row
999// carries its decorations inline (icon, tint, badge text, badge glyph, section, menu).
1000#[allow(clippy::large_enum_variant)]
1001#[doc(hidden)]
1002pub enum ItemSource<K> {
1003 Static(SelItem<K>),
1004 /// Reads a signal (tracked) and maps its elements to items. Called to (re)derive the block.
1005 Dynamic(Box<dyn Fn() -> Vec<SelItem<K>>>),
1006}
1007
1008// A nav's item sources reduced to what both `build_sidebar` and `build_tabs` need: a
1009// per-key page builder for static items, the ordered metadata sources (statics + dynamic
1010// blocks) that `derive` walks to produce the live row list, and the `.destination` fallback
1011// for data-driven keys. `derive` is called untracked for the first build and tracked inside a
1012// reactive effect that re-patches the native rows when a dynamic block's signal changes.
1013// Boxing `Static` would trade an allocation per row for a saving that is nominal here: these
1014// enums live in one `Vec` built once when a nav is constructed, a few dozen entries at most,
1015// and the static case is the overwhelmingly common one. The gap is only this wide because a row
1016// carries its decorations inline (icon, tint, badge text, badge glyph, section, menu).
1017#[allow(clippy::large_enum_variant)]
1018enum MetaSource<K> {
1019 Static(K, TextSource, RowMeta, bool),
1020 Dynamic(Box<dyn Fn() -> Vec<SelItem<K>>>),
1021}
1022
1023/// The non-title decorations of one nav row.
1024#[derive(Clone, Default)]
1025struct RowMeta {
1026 icon: Option<String>,
1027 tint: Option<day_spec::Color>,
1028 menu: Vec<day_spec::MenuItem>,
1029 badge: Option<TextSource>,
1030 badge_icon: Option<String>,
1031 badge_tint: Option<day_spec::Color>,
1032 section: Option<SectionHeader>,
1033}
1034
1035#[derive(Clone)]
1036struct NavReorder<K> {
1037 eligible: Rc<dyn Fn(&K) -> bool>,
1038 moved: Rc<dyn Fn(K, K)>,
1039}
1040
1041/// How a sidebar row drags under [`Nav::regroup_items`].
1042#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1043pub enum NavDrag {
1044 /// Doesn't drag, and nothing drops into its section.
1045 Fixed,
1046 /// Drags to another place in its own section or into another section.
1047 Reorder,
1048 /// Drags into another section only: its own section keeps the app's sorted order.
1049 Regroup,
1050}
1051
1052/// Where a dragged sidebar row landed ([`Nav::regroup_items`]).
1053#[derive(Clone, Debug, PartialEq)]
1054pub struct NavDrop<K> {
1055 /// The dragged row.
1056 pub moved: K,
1057 /// The destination section's id (`section_id`), `None` for a section declared without one
1058 /// and for the rows above the first header.
1059 pub section: Option<String>,
1060 /// The row it now sits before in that section; `None` at the section's end. Never `moved`.
1061 pub before: Option<K>,
1062}
1063
1064#[derive(Clone)]
1065struct NavRegroup<K> {
1066 drag: Rc<dyn Fn(&K) -> NavDrag>,
1067 dropped: Rc<dyn Fn(NavDrop<K>)>,
1068}
1069
1070/// A nav's sidebar dragging: [`Nav::reorder_items`] or [`Nav::regroup_items`], whichever was
1071/// declared last.
1072#[derive(Clone)]
1073enum SidebarDrag<K> {
1074 Reorder(NavReorder<K>),
1075 Regroup(NavRegroup<K>),
1076}
1077
1078impl<K> SidebarDrag<K> {
1079 /// How the row with this key drags; a reorder's eligible row reorders.
1080 fn drag(&self, key: &K) -> NavDrag {
1081 match self {
1082 SidebarDrag::Reorder(r) if (r.eligible)(key) => NavDrag::Reorder,
1083 SidebarDrag::Reorder(_) => NavDrag::Fixed,
1084 SidebarDrag::Regroup(g) => (g.drag)(key),
1085 }
1086 }
1087}
1088
1089/// One nav's rows as a regroup sees them, in item order: each key, whether a section header
1090/// opens before it, and that header's `section_id`. Rows above the first header form one
1091/// unnamed section.
1092struct RegroupRows<K> {
1093 keys: Vec<K>,
1094 opens: Vec<bool>,
1095 ids: Vec<Option<String>>,
1096}
1097
1098impl<K: Route> RegroupRows<K> {
1099 fn from_nav(rows: NavRows<K>) -> Self {
1100 RegroupRows {
1101 opens: rows.sections.iter().map(Option::is_some).collect(),
1102 ids: rows.section_ids,
1103 keys: rows.keys,
1104 }
1105 }
1106
1107 /// From the stand-in list's rows, where each header is a row of its own.
1108 fn from_sidebar(rows: &[SidebarRow<K>]) -> Self {
1109 let mut r = RegroupRows {
1110 keys: Vec::new(),
1111 opens: Vec::new(),
1112 ids: Vec::new(),
1113 };
1114 let mut header = None;
1115 for row in rows {
1116 match &row.key {
1117 None => header = Some(row.section_id.clone()),
1118 Some(key) => {
1119 r.keys.push(key.clone());
1120 r.opens.push(header.is_some());
1121 r.ids.push(header.take().flatten());
1122 }
1123 }
1124 }
1125 r
1126 }
1127
1128 /// The rows [`reorder_sidebar`]'s list has: `None` for a header, `Some(i)` for item `i`.
1129 fn display(&self) -> Vec<Option<usize>> {
1130 let mut rows = Vec::with_capacity(self.keys.len() * 2);
1131 for (i, opens) in self.opens.iter().enumerate() {
1132 if *opens {
1133 rows.push(None);
1134 }
1135 rows.push(Some(i));
1136 }
1137 rows
1138 }
1139
1140 /// The first item of the section holding item `i`.
1141 fn section_of(&self, i: usize) -> usize {
1142 (1..=i).rev().find(|s| self.opens[*s]).unwrap_or(0)
1143 }
1144
1145 /// A drop in item indices (`Event::NavRegroup`'s terms) checked against the regroup rules:
1146 /// `Ok(None)` for a drop back where the row started, which reports nothing.
1147 fn drop_at(
1148 &self,
1149 regroup: &NavRegroup<K>,
1150 from: usize,
1151 section: usize,
1152 before: Option<usize>,
1153 ) -> Result<Option<NavDrop<K>>, &'static str> {
1154 let len = self.keys.len();
1155 let drag = |i: usize| (regroup.drag)(&self.keys[i]);
1156 if from >= len || drag(from) == NavDrag::Fixed {
1157 return Err("regroup denied: the row is fixed or out of range");
1158 }
1159 if section >= len || (section > 0 && !self.opens[section]) {
1160 return Err("regroup denied: no section starts at that row");
1161 }
1162 let end = (section + 1..len).find(|i| self.opens[*i]).unwrap_or(len);
1163 if before.is_some_and(|b| b < section || b >= end || b == from) {
1164 return Err("regroup denied: the row it lands before is not in that section");
1165 }
1166 if (section..end).any(|i| drag(i) == NavDrag::Fixed) {
1167 return Err("regroup denied: a fixed row holds that section");
1168 }
1169 if self.section_of(from) == section {
1170 if drag(from) == NavDrag::Regroup {
1171 return Err("regroup denied: the row keeps its section's sorted order");
1172 }
1173 let next = (from + 1 < end).then_some(from + 1);
1174 if before == next {
1175 return Ok(None);
1176 }
1177 }
1178 Ok(Some(NavDrop {
1179 moved: self.keys[from].clone(),
1180 section: if self.opens[section] {
1181 self.ids[section].clone()
1182 } else {
1183 None
1184 },
1185 before: before.map(|b| self.keys[b].clone()),
1186 }))
1187 }
1188
1189 /// A move of display row `from` to display row `to` (the stand-in list's rotation: the
1190 /// row ends up at index `to`), as a checked drop. Moving down onto a header lands on that
1191 /// section's first row; moving up onto one lands at the end of the section above it.
1192 fn display_drop(
1193 &self,
1194 regroup: &NavRegroup<K>,
1195 from: usize,
1196 to: usize,
1197 ) -> Result<Option<NavDrop<K>>, &'static str> {
1198 let rows = self.display();
1199 let Some(Some(moved)) = rows.get(from).copied() else {
1200 return Err("regroup denied: the row is a section header or out of range");
1201 };
1202 if to >= rows.len() {
1203 return Err("regroup denied: the target is out of range");
1204 }
1205 // Display rows in their order after the move, named by their index before it.
1206 let mut order: Vec<usize> = (0..rows.len()).filter(|r| *r != from).collect();
1207 order.insert(to, from);
1208 let section = match order[..to].iter().rev().find(|r| rows[**r].is_none()) {
1209 // A header is always followed by its section's first row.
1210 Some(header) => rows.get(header + 1).copied().flatten(),
1211 None => rows[0],
1212 }
1213 .ok_or("regroup denied: no section above the first header")?;
1214 let before = order.get(to + 1).and_then(|r| rows[*r]);
1215 self.drop_at(regroup, moved, section, before)
1216 }
1217}
1218
1219#[derive(Clone, PartialEq)]
1220struct SidebarRow<K> {
1221 id: String,
1222 parent: Option<String>,
1223 key: Option<K>,
1224 /// A header row's `section_id`; `None` on item rows and on headers declared without one.
1225 section_id: Option<String>,
1226 title: String,
1227 icon: Option<String>,
1228 tint: Option<day_spec::Color>,
1229 badge: Option<String>,
1230 badge_icon: Option<String>,
1231 badge_tint: Option<day_spec::Color>,
1232 menu: Vec<day_spec::MenuItem>,
1233}
1234fn sidebar_rows<K: Route>(rows: NavRows<K>) -> Vec<SidebarRow<K>> {
1235 let mut result = Vec::new();
1236 let mut parent = None;
1237 for (i, key) in rows.keys.into_iter().enumerate() {
1238 if let Some(title) = &rows.sections[i] {
1239 let id = rows.section_ids[i].clone().unwrap_or_else(|| key.key());
1240 let header = format!("header:{id}");
1241 parent = Some(header.clone());
1242 result.push(SidebarRow {
1243 id: header,
1244 parent: None,
1245 key: None,
1246 section_id: rows.section_ids[i].clone(),
1247 title: title.clone(),
1248 icon: None,
1249 tint: None,
1250 badge: None,
1251 badge_icon: None,
1252 badge_tint: None,
1253 menu: vec![],
1254 });
1255 }
1256 result.push(SidebarRow {
1257 id: format!("item:{}", key.key()),
1258 parent: parent.clone(),
1259 key: Some(key),
1260 section_id: None,
1261 title: rows.titles[i].clone(),
1262 icon: rows.icons[i].clone(),
1263 tint: rows.tints[i],
1264 badge: rows.badges[i].clone(),
1265 badge_icon: rows.badge_icons[i].clone(),
1266 badge_tint: rows.badge_tints[i],
1267 menu: rows.menus[i].clone(),
1268 });
1269 }
1270 result
1271}
1272fn sidebar_image<K: Route>(slot: ItemSlot<SidebarRow<K>, String>, trailing: bool) -> AnyPiece {
1273 // Downloaded artwork keeps its colors. Rebuild when a recycled row switches between
1274 // a bundled placeholder and a local file: template is a realization-time property.
1275 when(
1276 move || {
1277 slot.field(|r| {
1278 let name = if trailing { &r.badge_icon } else { &r.icon };
1279 name.as_deref()
1280 .is_some_and(|name| std::path::Path::new(name).is_absolute())
1281 })
1282 },
1283 move || sidebar_image_view(slot, trailing, false),
1284 )
1285 .otherwise(move || sidebar_image_view(slot, trailing, true))
1286 .any()
1287}
1288fn sidebar_image_view<K: Route>(
1289 slot: ItemSlot<SidebarRow<K>, String>,
1290 trailing: bool,
1291 template: bool,
1292) -> AnyPiece {
1293 piece_fn(move |cx| {
1294 // A template glyph (docs/vectors.md): untinted, it draws in the row's own foreground
1295 // and follows the theme, as the native nav-menu rows draw theirs. As authored, the
1296 // bundled art is black on transparent — invisible on a dark sidebar. The row's tint
1297 // is realized with the view, not only patched in: a patch lands nowhere while the
1298 // cell holding this row has no native view yet.
1299 let tint_of = move || slot.field(|r| if trailing { r.badge_tint } else { r.tint });
1300 let seed = day_reactive::untrack(tint_of);
1301 let image = image(move || {
1302 day_spec::ImageSource::Named(slot.field(|r| {
1303 if trailing {
1304 r.badge_icon.clone()
1305 } else {
1306 r.icon.clone()
1307 }
1308 .unwrap_or_default()
1309 }))
1310 })
1311 .initial_tint(seed);
1312 let node = if template { image.template() } else { image }.build(cx);
1313 bind(tint_of, move |tint| {
1314 with_tree(|t| {
1315 t.patch(
1316 node,
1317 Box::new(day_spec::props::ImagePatch::Tint(*tint)),
1318 false,
1319 )
1320 });
1321 });
1322 node
1323 })
1324 .frame(20.0, 20.0)
1325 .any()
1326}
1327fn sidebar_progress<K: Route>(
1328 slot: ItemSlot<SidebarRow<K>, String>,
1329 progress: Option<IconProgressSource<K>>,
1330) -> AnyPiece {
1331 let activity = Rc::new(move || {
1332 let key = slot.field(|row| row.key.clone())?;
1333 progress.as_ref()?()
1334 .into_iter()
1335 .find(|(k, _)| k.key() == key.key())
1336 .map(|(_, fraction)| fraction)
1337 });
1338 let (visible, determinate, drawn) = (activity.clone(), activity.clone(), activity);
1339 when(
1340 move || visible().is_some(),
1341 move || {
1342 let (determinate, drawn) = (determinate.clone(), drawn.clone());
1343 when(
1344 move || determinate().flatten().is_some(),
1345 move || {
1346 let drawn = drawn.clone();
1347 canvas(move |draw, size| {
1348 let fraction = drawn().flatten().unwrap_or(0.0).clamp(0.0, 1.0);
1349 let color = slot
1350 .field(|r| r.tint)
1351 .unwrap_or(day_spec::Color::hex(0x0A84FF));
1352 let rect = day_spec::Rect::new(
1353 1.0,
1354 1.0,
1355 (size.width - 2.0).max(0.0),
1356 (size.height - 2.0).max(0.0),
1357 );
1358 draw.stroke(
1359 day_spec::Shape::Arc {
1360 rect,
1361 start_deg: -90.0,
1362 sweep_deg: 360.0 * fraction,
1363 },
1364 color,
1365 2.0,
1366 );
1367 })
1368 .frame(20.0, 20.0)
1369 },
1370 )
1371 .otherwise(|| spinner().frame(20.0, 20.0))
1372 },
1373 )
1374 .any()
1375}
1376fn section_sidebar<K: Route, S: Binding<K>>(
1377 rows: Rc<SelItems<K>>,
1378 selection: S,
1379 collapsed: AnyBinding<std::collections::HashSet<String>>,
1380 changed: Option<Rc<dyn Fn(String, bool)>>,
1381 progress: Option<IconProgressSource<K>>,
1382) -> AnyPiece {
1383 use crate::structure::{branches, tree};
1384 let snapshot = Signal::new(day_reactive::untrack(|| sidebar_rows(rows.derive())));
1385 bind(
1386 move || sidebar_rows(rows.derive()),
1387 move |v| snapshot.set_if_changed(v.clone()),
1388 );
1389 let open = Signal::new(std::collections::HashSet::new());
1390 bind(
1391 move || {
1392 let closed = collapsed.get();
1393 snapshot
1394 .get()
1395 .iter()
1396 .filter(|r| r.key.is_none())
1397 .filter(|r| !closed.contains(r.id.strip_prefix("header:").unwrap_or(&r.id)))
1398 .map(|r| r.id.clone())
1399 .collect::<std::collections::HashSet<_>>()
1400 },
1401 move |v| open.set_if_changed(v.clone()),
1402 );
1403 let selected = selection.clone();
1404 tree(
1405 branches(
1406 move || snapshot.get(),
1407 |r: &SidebarRow<K>| r.id.clone(),
1408 |r| r.parent.clone(),
1409 ),
1410 move |slot| {
1411 let progress = progress.clone();
1412 piece_fn(move |cx| {
1413 let node = when(
1414 move || slot.field(|r| r.key.is_none()),
1415 move || {
1416 row((label(move || slot.field(|r| r.title.clone()))
1417 .font(day_spec::Font::Caption)
1418 .single_line()
1419 .grow(Dimension::Width),))
1420 .align(VAlign::Center)
1421 .grow(Dimension::Both)
1422 .any()
1423 },
1424 )
1425 .otherwise(move || {
1426 let progress = progress.clone();
1427 row((
1428 when(
1429 move || slot.field(|r| r.icon.is_some()),
1430 move || {
1431 sidebar_image(slot, false)
1432 .overlay(sidebar_progress(slot, progress.clone()))
1433 },
1434 ),
1435 label(move || slot.field(|r| r.title.clone()))
1436 .single_line()
1437 .grow(Dimension::Width),
1438 label(move || slot.field(|r| r.badge.clone().unwrap_or_default()))
1439 .font(day_spec::Font::Caption),
1440 when(
1441 move || slot.field(|r| r.badge_icon.is_some()),
1442 move || sidebar_image(slot, true),
1443 ),
1444 ))
1445 .spacing(8.0)
1446 .align(VAlign::Center)
1447 // The surrounding `when` fills the native cell. Its content must
1448 // fill the height too, so centering uses the entire selection row.
1449 .grow(Dimension::Both)
1450 .any()
1451 })
1452 .grow(Dimension::Both)
1453 .build(cx);
1454 with_tree(|t| {
1455 t.set_context_menu_fn(node, Rc::new(move |_| slot.field(|r| r.menu.clone())))
1456 });
1457 node
1458 })
1459 },
1460 )
1461 .section_headers()
1462 .row_height(day_spec::props::RowHeight::Uniform(32.0))
1463 .expanded(open)
1464 .on_expansion(move |id, expanded| {
1465 let Some(id) = id.strip_prefix("header:") else {
1466 return;
1467 };
1468 collapsed.update(|s| {
1469 if expanded {
1470 s.remove(id);
1471 } else {
1472 s.insert(id.to_owned());
1473 }
1474 });
1475 if let Some(f) = &changed {
1476 f(id.to_owned(), expanded);
1477 }
1478 })
1479 .selected(move || vec![format!("item:{}", selected.read().key())])
1480 .on_selection(move |ids| {
1481 let Some(row) = snapshot
1482 .get()
1483 .into_iter()
1484 .find(|r| ids.contains(&r.id) && r.key.is_some())
1485 else {
1486 return;
1487 };
1488 if let Some(key) = row.key {
1489 day_core::note_navigation(&key.key(), Some(&row.title));
1490 selection.write(key);
1491 }
1492 })
1493 .type_ahead(move |id| {
1494 snapshot
1495 .get()
1496 .iter()
1497 .find(|r| &r.id == id)
1498 .map(|r| r.title.clone())
1499 .unwrap_or_default()
1500 })
1501 .row_id(|id| day_core::id!(sidebar, id))
1502 .id(day_core::id!(nav_sections))
1503 .grow(Dimension::Both)
1504 .any()
1505}
1506
1507/// A dayscript `reorder` of a toolkit's own sidebar (`Cap::NavReorder` Native), in the rows
1508/// [`reorder_sidebar`]'s list would have: a header row before each section, so one script
1509/// drives both. A row moves within the run of movable rows around it; `to` is where it lands,
1510/// the row whose place it takes in the order before the move. A regrouping nav's script goes
1511/// through [`RegroupRows::display_drop`] instead, the stand-in list's rule.
1512fn script_nav_reorder<K: Route>(
1513 keys: &[K],
1514 sections: &[Option<String>],
1515 reorder: &NavReorder<K>,
1516 from: usize,
1517 to: usize,
1518) -> Result<usize, &'static str> {
1519 let mut rows: Vec<Option<usize>> = Vec::with_capacity(keys.len() * 2);
1520 for i in 0..keys.len() {
1521 if sections.get(i).is_some_and(Option::is_some) {
1522 rows.push(None);
1523 }
1524 rows.push(Some(i));
1525 }
1526 let movable = |r: usize| {
1527 rows.get(r)
1528 .copied()
1529 .flatten()
1530 .is_some_and(|i| (reorder.eligible)(&keys[i]))
1531 };
1532 if !movable(from) || to >= rows.len() {
1533 return Err("reorder denied: the row is fixed or the target is out of range");
1534 }
1535 let (lo, hi) = (from.min(to), from.max(to));
1536 if !(lo..=hi).all(movable) {
1537 return Err("reorder denied: a fixed row or a section header is in the way");
1538 }
1539 if let (Some(Some(a)), Some(Some(b))) = (rows.get(from), rows.get(to))
1540 && a != b
1541 {
1542 (reorder.moved)(keys[*a].clone(), keys[*b].clone());
1543 }
1544 Ok(to)
1545}
1546
1547fn reorder_sidebar<K: Route, S: Binding<K>>(
1548 rows: Rc<SelItems<K>>,
1549 selection: S,
1550 drag: SidebarDrag<K>,
1551 progress: Option<IconProgressSource<K>>,
1552) -> AnyPiece {
1553 // Pure drag callbacks read the committed snapshot, never re-run application row builders.
1554 let snapshot = Signal::new(day_reactive::untrack(|| sidebar_rows(rows.derive())));
1555 bind(
1556 move || sidebar_rows(rows.derive()),
1557 move |value| snapshot.set_if_changed(value.clone()),
1558 );
1559 let source = Rc::new(move || snapshot.get());
1560 let selection_revision = Signal::new(0u64);
1561 let (read, guard, commit, selected) = (
1562 source.clone(),
1563 source.clone(),
1564 source.clone(),
1565 source.clone(),
1566 );
1567 let selected_binding = selection.clone();
1568 let tapped_selection = selection.clone();
1569 list(
1570 items(move || read(), |r: &SidebarRow<K>| r.id.clone()),
1571 move |slot| {
1572 let activity = progress.clone();
1573 let tapped_selection = tapped_selection.clone();
1574 piece_fn(move |cx| {
1575 let node = row((when(
1576 move || slot.field(|r| r.key.is_none()),
1577 move || {
1578 label(move || slot.field(|r| r.title.clone()))
1579 .font(day_spec::Font::Caption)
1580 .padding(day_spec::Insets::symmetric(8.0, 0.0))
1581 .grow(Dimension::Width)
1582 },
1583 )
1584 .otherwise(move || {
1585 let activity = activity.clone();
1586 row((
1587 when(
1588 move || slot.field(|r| r.icon.is_some()),
1589 move || {
1590 sidebar_image(slot, false)
1591 .overlay(sidebar_progress(slot, activity.clone()))
1592 },
1593 ),
1594 label(move || slot.field(|r| r.title.clone()))
1595 .single_line()
1596 .grow(Dimension::Width),
1597 label(move || slot.field(|r| r.badge.clone().unwrap_or_default()))
1598 .font(day_spec::Font::Caption),
1599 when(
1600 move || slot.field(|r| r.badge_icon.is_some()),
1601 move || sidebar_image(slot, true),
1602 ),
1603 ))
1604 .spacing(8.0)
1605 .align(VAlign::Center)
1606 .padding(day_spec::Insets::symmetric(8.0, 0.0))
1607 .grow(Dimension::Width)
1608 }),))
1609 .align(VAlign::Center)
1610 .grow(Dimension::Both)
1611 .id_of(move || day_core::id!(sidebar, slot.field(|r| r.id.clone())))
1612 .on_tap(move || {
1613 if let Some(key) = slot.field(|r| r.key.clone()) {
1614 let title = slot.field(|r| r.title.clone());
1615 day_core::note_navigation(&key.key(), Some(&title));
1616 tapped_selection.write(key);
1617 }
1618 })
1619 .build(cx);
1620 with_tree(|t| {
1621 t.set_context_menu_fn(node, Rc::new(move |_| slot.field(|r| r.menu.clone())))
1622 });
1623 node
1624 })
1625 },
1626 )
1627 .row_height(day_spec::props::RowHeight::Uniform(36.0))
1628 .on_select(move |id| {
1629 selection_revision.update(|n| *n = n.wrapping_add(1));
1630 if let Some(row) = source().into_iter().find(|r| r.id == id)
1631 && let Some(key) = row.key
1632 {
1633 day_core::note_navigation(&key.key(), Some(&row.title));
1634 selection.write(key);
1635 }
1636 })
1637 .selected_rows(move || {
1638 selection_revision.get();
1639 selected()
1640 .iter()
1641 .position(|r| {
1642 r.key
1643 .as_ref()
1644 .is_some_and(|k| k.key() == selected_binding.read().key())
1645 })
1646 .into_iter()
1647 .collect()
1648 })
1649 .reorderable(match drag {
1650 SidebarDrag::Reorder(reorder) => crate::Reorder::new(move |from, to| {
1651 let rows = commit();
1652 if let (Some(a), Some(b)) = (
1653 rows.get(from).and_then(|r| r.key.clone()),
1654 rows.get(to).and_then(|r| r.key.clone()),
1655 ) {
1656 (reorder.moved)(a, b);
1657 }
1658 })
1659 .guard(move |from, to| {
1660 let rows = guard();
1661 if from >= rows.len()
1662 || to >= rows.len()
1663 || rows[from.min(to)..=from.max(to)]
1664 .iter()
1665 .any(|r| r.key.as_ref().is_none_or(|k| !(reorder.eligible)(k)))
1666 {
1667 ReorderVerdict::Deny
1668 } else {
1669 ReorderVerdict::Allow
1670 }
1671 }),
1672 // Headers are rows here, so the list's move names a destination section by where the
1673 // row lands among them (`RegroupRows::display_drop`).
1674 SidebarDrag::Regroup(regroup) => {
1675 let check = regroup.clone();
1676 crate::Reorder::new(move |from, to| {
1677 let rows = RegroupRows::from_sidebar(&commit());
1678 if let Ok(Some(drop)) = rows.display_drop(®roup, from, to) {
1679 (regroup.dropped)(drop);
1680 }
1681 })
1682 .guard(move |from, to| {
1683 match RegroupRows::from_sidebar(&guard()).display_drop(&check, from, to) {
1684 Ok(_) => ReorderVerdict::Allow,
1685 Err(_) => ReorderVerdict::Deny,
1686 }
1687 })
1688 }
1689 })
1690 .id(day_core::id!(nav_reorder_list))
1691 .grow(Dimension::Both)
1692 .any()
1693}
1694
1695/// One nav's live rows, flattened across its static items and dynamic blocks.
1696struct NavRows<K> {
1697 keys: Vec<K>,
1698 titles: Vec<String>,
1699 icons: Vec<Option<String>>,
1700 badges: Vec<Option<String>>,
1701 badge_icons: Vec<Option<String>>,
1702 badge_tints: Vec<Option<day_spec::Color>>,
1703 sections: Vec<Option<String>>,
1704 section_ids: Vec<Option<String>>,
1705 tints: Vec<Option<day_spec::Color>>,
1706 menus: Vec<Vec<day_spec::MenuItem>>,
1707}
1708
1709struct SelItems<K> {
1710 static_builders: std::collections::HashMap<String, PageFn>,
1711 /// Page builders carried by the rows of data-driven blocks, refreshed on every derive.
1712 dynamic_builders: RefCell<std::collections::HashMap<String, PageFn>>,
1713 meta: Rc<Vec<MetaSource<K>>>,
1714 destination: Option<DestFn<K>>,
1715}
1716
1717impl<K: Route> SelItems<K> {
1718 fn from_sources(sources: Vec<ItemSource<K>>, destination: Option<DestFn<K>>) -> Self {
1719 let mut static_builders = std::collections::HashMap::new();
1720 let mut meta = Vec::new();
1721 for src in sources {
1722 match src {
1723 ItemSource::Static(it) => {
1724 if let Some(b) = it.build {
1725 static_builders.insert(it.key.key(), b);
1726 }
1727 meta.push(MetaSource::Static(
1728 it.key,
1729 it.title,
1730 RowMeta {
1731 icon: it.icon,
1732 tint: it.tint,
1733 menu: it.menu,
1734 badge: it.badge,
1735 badge_icon: it.badge_icon,
1736 badge_tint: it.badge_tint,
1737 section: it.section,
1738 },
1739 it.immersive,
1740 ));
1741 }
1742 ItemSource::Dynamic(f) => {
1743 meta.push(MetaSource::Dynamic(f));
1744 }
1745 }
1746 }
1747 SelItems {
1748 static_builders,
1749 dynamic_builders: RefCell::new(std::collections::HashMap::new()),
1750 meta: Rc::new(meta),
1751 destination,
1752 }
1753 }
1754
1755 /// The flat live rows: (typed keys, resolved titles, icons). Tracked, because reading
1756 /// a `Dynamic` block's signal subscribes the caller (the derive effect) to row changes,
1757 /// and resolving each title through [`TextSource::resolve`] subscribes it to the locale,
1758 /// so `set_locale` re-runs the effect and the native rows retitle (docs/navigation.md).
1759 fn derive(&self) -> NavRows<K> {
1760 let mut r = NavRows {
1761 keys: Vec::new(),
1762 titles: Vec::new(),
1763 icons: Vec::new(),
1764 badges: Vec::new(),
1765 badge_icons: Vec::new(),
1766 badge_tints: Vec::new(),
1767 sections: Vec::new(),
1768 section_ids: Vec::new(),
1769 tints: Vec::new(),
1770 menus: Vec::new(),
1771 };
1772 let mut push = |k: K, title: String, m: &RowMeta| {
1773 r.keys.push(k);
1774 r.titles.push(title);
1775 r.icons.push(m.icon.clone());
1776 // Empty text is no badge: a toolkit given `Some("")` draws a bare dot (UIKit does).
1777 r.badges.push(
1778 m.badge
1779 .as_ref()
1780 .map(|b| b.resolve())
1781 .filter(|b| !b.is_empty()),
1782 );
1783 r.badge_icons.push(m.badge_icon.clone());
1784 r.badge_tints.push(m.badge_tint);
1785 r.sections
1786 .push(m.section.as_ref().map(|s| s.title.resolve()));
1787 r.section_ids
1788 .push(m.section.as_ref().and_then(|s| s.id.clone()));
1789 r.tints.push(m.tint);
1790 r.menus.push(m.menu.clone());
1791 };
1792 for ms in self.meta.iter() {
1793 match ms {
1794 MetaSource::Static(k, t, m, _) => push(k.clone(), t.resolve(), m),
1795 MetaSource::Dynamic(f) => {
1796 for it in f() {
1797 if let Some(b) = it.build {
1798 self.dynamic_builders.borrow_mut().insert(it.key.key(), b);
1799 }
1800 let m = RowMeta {
1801 icon: it.icon,
1802 tint: it.tint,
1803 menu: it.menu,
1804 badge: it.badge,
1805 badge_icon: it.badge_icon,
1806 badge_tint: it.badge_tint,
1807 section: it.section,
1808 };
1809 let title = it.title.resolve();
1810 push(it.key, title, &m);
1811 }
1812 }
1813 }
1814 }
1815 r
1816 }
1817
1818 /// An item's immersive-chrome flag (docs/navigation.md). A data-driven key checks its
1819 /// block's current rows untracked: chrome is resolved at push time, not a dependency of
1820 /// the push (a tracked read here would re-run the selection effect on every list change).
1821 fn immersive_of(&self, key: &str) -> bool {
1822 self.meta.iter().any(|ms| match ms {
1823 MetaSource::Static(k, _, _, imm) => *imm && k.key() == key,
1824 MetaSource::Dynamic(f) => {
1825 day_reactive::untrack(|| f().iter().any(|it| it.immersive && it.key.key() == key))
1826 }
1827 })
1828 }
1829
1830 /// A static item's live title source (locale-reactive retitle); `None` for a data-driven
1831 /// key, whose title is a resolved snapshot from the derived list.
1832 fn static_title(&self, key: &str) -> Option<TextSource> {
1833 self.meta.iter().find_map(|ms| match ms {
1834 MetaSource::Static(k, t, _, _) if k.key() == key => Some(t.clone()),
1835 _ => None,
1836 })
1837 }
1838
1839 /// Build a key's page: the item's own builder (static, or carried by a data-driven row),
1840 /// else the `.destination` fallback, else a blank leaf (misconfigured: an item with neither).
1841 fn build_page(&self, key: &K) -> AnyPiece {
1842 let k = key.key();
1843 let dynamic = self.dynamic_builders.borrow().get(&k).cloned();
1844 if let Some(b) = self.static_builders.get(&k) {
1845 b()
1846 } else if let Some(b) = dynamic {
1847 b()
1848 } else if let Some(d) = &self.destination {
1849 d(key)
1850 } else {
1851 piece_fn(|cx| cx.layout_only(Rc::new(PassThrough), Flex::default(), Boundary::No)).any()
1852 }
1853 }
1854}
1855
1856type IconProgressSource<K> = Rc<dyn Fn() -> Vec<(K, Option<f64>)>>;
1857
1858/// A one-of-N nav whose active key is an app-owned signal (two-way, exactly like
1859/// `Picker`/`Toggle`). Deep links and dayscript address items by key (docs/navigation.md).
1860///
1861/// The key type is any [`Route`]: `String` for raw keys, or a typed enum; use
1862/// `Signal<Option<Section>>` for a sidebar (`None` = the collapsed mobile list) and
1863/// `Signal<Tab>` for tabs (always selected).
1864///
1865/// ```ignore
1866/// let section = Signal::new("home".to_string()); // or Signal::new(None::<Section>)
1867/// nav(section).style(NavStyle::Sidebar)
1868/// .item("home", tr("home"), home_page) // or .item(Section::Home, …)
1869/// .item("settings", tr("settings"), settings_page)
1870/// ```
1871type DocumentEvent = Rc<dyn Fn(&Event)>;
1872type RefreshSource = (Reactive<bool>, Rc<dyn Fn()>);
1873
1874pub struct Nav<S: Binding<K>, K: Route = String> {
1875 selection: S,
1876 documents: Option<day_spec::props::DocumentTabsConfig>,
1877 document_event: Option<DocumentEvent>,
1878 icon_progress: Option<IconProgressSource<K>>,
1879 refresh: Option<RefreshSource>,
1880 style: NavStyle,
1881 title: TextSource,
1882 header: Option<Box<dyn FnOnce() -> AnyPiece>>,
1883 footer: Option<Box<dyn FnOnce() -> AnyPiece>>,
1884 sources: Vec<ItemSource<K>>,
1885 /// Builds the page for a key with no static item (a data-driven item from `.items`).
1886 destination: Option<DestFn<K>>,
1887 /// Whether this nav contributes to the app route (deep links / dayscript). `false`
1888 /// (`.local()`) for a nav used as a self-contained widget, so it does not add a segment
1889 /// to `current_route` or intercept `navigate` (docs/navigation.md).
1890 routed: bool,
1891 /// The persistence key set by [`Nav::restore`]: the selected item's key is saved here on
1892 /// every change and restored at build (unless a launch deep link is pending). `None` = not
1893 /// persisted.
1894 restore: Option<String>,
1895 /// Keep a filtered-out selection while its underlying record still exists.
1896 retain_selection: Option<ListPred<K>>,
1897 /// Sidebar dragging ([`Nav::reorder_items`] or [`Nav::regroup_items`], the later wins).
1898 reorder_items: Option<SidebarDrag<K>>,
1899 collapsed_sections: Option<AnyBinding<std::collections::HashSet<String>>>,
1900 on_section_expansion: Option<Rc<dyn Fn(String, bool)>>,
1901 /// Items declared on this host's own chrome ([`Nav::toolbar`]).
1902 toolbar: Vec<crate::ToolbarSource>,
1903 /// Draw the platform's own sidebar toggle (off with [`Nav::no_sidebar_toggle`]).
1904 sidebar_toggle: bool,
1905 /// Search over this surface ([`Nav::searchable`]). `None` unless set.
1906 search: Option<SearchSpec>,
1907 /// The presentation pinned by [`Nav::presentation`]; `None` = automatic, resolved from
1908 /// the window's size class and re-resolved whenever it changes.
1909 presentation: Option<day_spec::props::NavPresentation>,
1910 /// The content-list pane builder ([`Nav::content_list`], docs/navigation.md): the
1911 /// Mail shape's middle column, built once and resident for the host's life. `None` = the
1912 /// classic two-pane nav.
1913 content_list: Option<Rc<dyn Fn() -> AnyPiece>>,
1914 /// Preferred width of the content-list pane in points.
1915 content_list_width: f64,
1916 /// Which destinations show the pane ([`Nav::content_list_for`]); `None` = all of them.
1917 content_list_pred: Option<ListPred<K>>,
1918 /// Whether the detail is showing, two-way ([`ContentList::detail_visible`]): what gates
1919 /// the detail push in a stacked presentation with a content list, and what native back
1920 /// writes `false` into. `None` = the detail behaves classically (pushed on selection).
1921 detail_visible: Option<AnyBinding<bool>>,
1922 /// The navigation-bar title of the detail layer a content list opens
1923 /// ([`ContentList::detail_title`]). `None` = the destination's own title.
1924 detail_title: Option<TextSource>,
1925}
1926
1927/// Search over a navigation surface (docs/search.md), declared with [`Nav::searchable`]:
1928/// `Search::new(query).prompt(res::str::search()).reveal(SearchReveal::OnPull)`.
1929///
1930/// Search is declared on the surface, not on the toolbar, the same move SwiftUI made with
1931/// `.searchable()`. That is what lets the platform choose where to draw the field: the window
1932/// toolbar on a wide window, attached to the navigation list on a narrow one, without the app
1933/// branching on either. The query and the scope are app-owned bindings, which is what lets the
1934/// field move between placements without the state moving with it. A `Search` holds those
1935/// bindings, so build it where the nav is built; it is not a value to share across windows.
1936pub struct Search {
1937 query: AnyBinding<String>,
1938 prompt: Option<TextSource>,
1939 placement: day_spec::props::SearchPlacement,
1940 reveal: SearchReveal,
1941 /// Scope titles and the binding holding the chosen index. Empty titles = no scope bar.
1942 scopes: Vec<TextSource>,
1943 scope: Option<AnyBinding<usize>>,
1944 /// Completions for the current text, re-derived whenever its reactive reads change.
1945 suggestions: Option<SuggestFn>,
1946 /// Runs with the field's text when the user presses its Return or Search key.
1947 submit: Option<SubmitFn>,
1948 /// Whether a page's field is offered right now; `None` = always.
1949 available: Option<crate::Reactive<bool>>,
1950}
1951
1952/// What [`Search::on_submit`] runs.
1953type SubmitFn = Rc<dyn Fn(&str)>;
1954
1955/// How a navigation surface's search field comes and goes on a phone (docs/search.md). The
1956/// desktop toolbar field is always there whatever this says.
1957#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1958pub enum SearchReveal {
1959 /// The field is always shown.
1960 #[default]
1961 Always,
1962 /// The field and the title chrome collapse as the root list scrolls.
1963 Scrolls,
1964 /// The field starts hidden and is revealed by pulling down on the list; it collapses on
1965 /// scroll afterwards (iOS owns the reveal/collapse transitions, with a compact title).
1966 OnPull,
1967}
1968
1969impl Search {
1970 /// Search bound two-way to `query` (a `Signal<String>` or any other binding).
1971 pub fn new(query: impl Binding<String>) -> Search {
1972 Search {
1973 query: AnyBinding::new(query),
1974 prompt: None,
1975 placement: day_spec::props::SearchPlacement::Automatic,
1976 reveal: SearchReveal::Always,
1977 scopes: Vec::new(),
1978 scope: None,
1979 suggestions: None,
1980 submit: None,
1981 available: None,
1982 }
1983 }
1984 /// The field's empty-state prompt.
1985 pub fn prompt<M>(mut self, prompt: impl IntoText<M>) -> Search {
1986 self.prompt = Some(prompt.into_text());
1987 self
1988 }
1989 /// Ask for a particular placement. A preference: a backend that cannot honor it falls back
1990 /// to its platform's own convention, so `Automatic` (the default) is almost always right.
1991 pub fn placement(mut self, placement: day_spec::props::SearchPlacement) -> Search {
1992 self.placement = placement;
1993 self
1994 }
1995 /// How the field comes and goes on a phone (default [`SearchReveal::Always`]).
1996 pub fn reveal(mut self, reveal: SearchReveal) -> Search {
1997 self.reveal = reveal;
1998 self
1999 }
2000 /// A one-of-N scope bar under the field, bound to `scope` (an index into `titles`).
2001 ///
2002 /// Native on UIKit alone; elsewhere it is a native component doing the same job (a
2003 /// Material `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
2004 /// `NSSegmentedControl`) or, on web and system XAML, one composed from primitives.
2005 pub fn scopes<M>(
2006 mut self,
2007 scope: impl Binding<usize>,
2008 titles: impl IntoIterator<Item = impl IntoText<M>>,
2009 ) -> Search {
2010 self.scopes = titles.into_iter().map(IntoText::into_text).collect();
2011 self.scope = Some(AnyBinding::new(scope));
2012 self
2013 }
2014 /// Completions for the current text, re-derived whenever a reactive read inside `f` changes.
2015 ///
2016 /// On a navigation surface these complete the field rather than replacing the list: the list
2017 /// is already the filtered result set, so an overlay of results would cover the very thing it
2018 /// is narrowing. Backends whose search widget does completions natively use it
2019 /// (`AutoSuggestBox`, `QCompleter`, `<datalist>`, `UISearchResultsUpdating`).
2020 pub fn suggestions(mut self, f: impl Fn(&str) -> Vec<String> + 'static) -> Search {
2021 self.suggestions = Some(Rc::new(f));
2022 self
2023 }
2024 /// Run `f` with the field's text when the user presses its Return or Search key: the
2025 /// trigger for a search that runs on demand (a server query) instead of narrowing as the
2026 /// text changes. `query` already holds the text when `f` runs.
2027 pub fn on_submit(mut self, f: impl Fn(&str) + 'static) -> Search {
2028 self.submit = Some(Rc::new(f));
2029 self
2030 }
2031 /// Offer a page's field only while `v` is true (default: always), for a page that learns
2032 /// whether it can be searched after it shows: a feed that has to load first. The field
2033 /// keeps its text while it is withdrawn. A navigation surface's search ignores this.
2034 pub fn available<M>(mut self, v: impl crate::IntoReactive<bool, M>) -> Search {
2035 self.available = Some(v.into_reactive());
2036 self
2037 }
2038}
2039
2040/// Install a navigation page's own search field (docs/search.md, "Page search"): the reserved
2041/// `day::search` item on the page's chrome, which each toolkit draws where its platform puts a
2042/// page's search (the window toolbar on a desktop, the page's navigation bar on iOS, its app bar
2043/// on Android). The field shows while its page does and leaves with it.
2044///
2045/// The same one-model rule as a surface's search: the item is a rendering of the app's
2046/// `query`, inbound edits write the signal, and one outbound binding patches the item.
2047pub(crate) fn install_page_search(search: Search) {
2048 let chrome = day_core::current_chrome();
2049 let active = day_core::current_page_gate();
2050 let column = day_core::current_page_column();
2051 let query = search.query;
2052 let text = query.get_untracked();
2053 // The prompt follows the locale (a `res::str` text re-resolves): the item is re-registered
2054 // below when it changes, so the field's placeholder is never left in the old language.
2055 let prompt_source = search.prompt.clone();
2056 let prompt: Rc<RefCell<String>> = Rc::new(RefCell::new(
2057 prompt_source
2058 .as_ref()
2059 .map(TextSource::initial)
2060 .unwrap_or_default(),
2061 ));
2062 let suggestions = search
2063 .suggestions
2064 .as_ref()
2065 .map(|f| day_reactive::untrack(|| f(&text)))
2066 .unwrap_or_default();
2067 // What the field shows, by value (see `SearchSpec::install`).
2068 let shown: Rc<RefCell<String>> = Rc::new(RefCell::new(text.clone()));
2069 let action = {
2070 let shown = shown.clone();
2071 let submit = search.submit.clone();
2072 day_core::register_toolbar_value(Rc::new(move |v: &day_spec::ToolbarValue| match v {
2073 day_spec::ToolbarValue::Text(t) => {
2074 *shown.borrow_mut() = t.clone();
2075 query.set(t.clone());
2076 }
2077 day_spec::ToolbarValue::Submit(t) => {
2078 if let Some(f) = &submit {
2079 f(t);
2080 }
2081 }
2082 _ => {}
2083 }))
2084 };
2085 let item_prompt = prompt.clone();
2086 let item = move |text: String, suggestions: Vec<String>| day_spec::ToolbarItem {
2087 id: day_core::id!(day::search).as_str().to_owned(),
2088 kind: day_spec::ToolbarItemKind::Search {
2089 text,
2090 placeholder: item_prompt.borrow().clone(),
2091 suggestions,
2092 },
2093 label: item_prompt.borrow().clone(),
2094 tooltip: None,
2095 icon: None,
2096 enabled: true,
2097 action,
2098 placement: day_spec::ToolbarPlacement::Secondary,
2099 label_style: day_spec::LabelStyle::Automatic,
2100 prominent: false,
2101 column,
2102 };
2103 let available = search.available.clone();
2104 let offered = available.as_ref().is_none_or(|v| v.get_untracked());
2105 let offered_now = Rc::new(Cell::new(offered));
2106 let item = Rc::new(item);
2107 let token = day_core::register_contribution_gated(
2108 chrome,
2109 if offered {
2110 vec![item(text.clone(), suggestions.clone())]
2111 } else {
2112 Vec::new()
2113 },
2114 active.clone(),
2115 );
2116 // Offered and withdrawn as the page learns whether it can be searched, seeded with what the
2117 // field showed so a field that comes back holds its text.
2118 if let Some(crate::Reactive::Dyn(f)) = available {
2119 let (shown, suggest, query) = (shown.clone(), search.suggestions.clone(), query);
2120 let (item, offered_now) = (item.clone(), offered_now.clone());
2121 bind_seeded(
2122 offered,
2123 move || f(),
2124 move |on: &bool| {
2125 offered_now.set(*on);
2126 let items = if *on {
2127 let text = shown.borrow().clone();
2128 let list = suggest
2129 .as_ref()
2130 .map(|f| day_reactive::untrack(|| f(&query.get_untracked())))
2131 .unwrap_or_default();
2132 vec![item(text, list)]
2133 } else {
2134 Vec::new()
2135 };
2136 day_core::update_contribution(token, items);
2137 },
2138 );
2139 }
2140 if let Some(TextSource::Dyn(read)) = prompt_source {
2141 let (shown, suggest, item) = (shown.clone(), search.suggestions.clone(), item.clone());
2142 let seed = prompt.borrow().clone();
2143 bind_seeded(
2144 seed,
2145 move || read(),
2146 move |p: &String| {
2147 *prompt.borrow_mut() = p.clone();
2148 if offered_now.get() {
2149 let text = shown.borrow().clone();
2150 let list = suggest
2151 .as_ref()
2152 .map(|f| day_reactive::untrack(|| f(&query.get_untracked())))
2153 .unwrap_or_default();
2154 day_core::update_contribution(token, vec![item(text, list)]);
2155 }
2156 },
2157 );
2158 }
2159 // Recompose as the page comes and goes, as `.toolbar(…)` does.
2160 if let Some(gate) = active {
2161 day_reactive::Effect::new(move || {
2162 let _ = gate();
2163 day_core::chrome_changed();
2164 });
2165 }
2166 Scope::current().on_cleanup(move || day_core::unregister_contribution(token));
2167 bind_seeded(
2168 text,
2169 move || query.get(),
2170 move |t: &String| {
2171 if *shown.borrow() == *t {
2172 return;
2173 }
2174 *shown.borrow_mut() = t.clone();
2175 day_core::patch_chrome(
2176 chrome,
2177 day_spec::ToolbarPatch::Text {
2178 item: SEARCH_ITEM_ID.to_string(),
2179 text: t.clone(),
2180 },
2181 );
2182 },
2183 );
2184 if let Some(f) = search.suggestions {
2185 bind_seeded(
2186 suggestions,
2187 move || f(&query.get()),
2188 move |list| {
2189 day_core::patch_chrome(
2190 chrome,
2191 day_spec::ToolbarPatch::Suggestions {
2192 item: SEARCH_ITEM_ID.to_string(),
2193 list: list.clone(),
2194 },
2195 )
2196 },
2197 );
2198 }
2199}
2200
2201/// The content-list pane of a Mail-shaped nav (docs/navigation.md), declared with
2202/// [`Nav::content_list`]: mailboxes, message list, message. `build` makes the middle column,
2203/// built once and resident for the host's life; its content follows the app's own signals
2204/// (the selection scoping it, the row chosen from it), never a rebuild.
2205///
2206/// Where the toolkit has a native pane (`Cap::NavContentList`) the list gets its own column
2207/// (an AppKit `contentList` split item, a UIKit supplementary column) and otherwise the nav
2208/// composes it beside (split) or in place of (stacked) each destination. Pair it with
2209/// [`detail_visible`](ContentList::detail_visible) so compact widths get the list-then-detail
2210/// push flow, and [`only_for`](ContentList::only_for) to give full-width destinations (a
2211/// settings page) the whole detail area.
2212pub struct ContentList<K = String> {
2213 build: Rc<dyn Fn() -> AnyPiece>,
2214 width: f64,
2215 pred: Option<ListPred<K>>,
2216 detail_visible: Option<AnyBinding<bool>>,
2217 detail_title: Option<TextSource>,
2218}
2219
2220impl<K> ContentList<K> {
2221 /// The pane, from its builder.
2222 pub fn new<P: Piece>(build: impl Fn() -> P + 'static) -> ContentList<K> {
2223 ContentList {
2224 build: Rc::new(move || AnyPiece::new(build())),
2225 width: day_spec::NAV_LIST_WIDTH,
2226 pred: None,
2227 detail_visible: None,
2228 detail_title: None,
2229 }
2230 }
2231 /// Preferred width of the pane in points (default [`day_spec::NAV_LIST_WIDTH`]). Where the
2232 /// divider is user-draggable this is the initial width, not a limit.
2233 pub fn width(mut self, width: f64) -> ContentList<K> {
2234 self.width = width;
2235 self
2236 }
2237 /// Which destinations show the pane (default: all of them). A destination answering
2238 /// `false` collapses the pane and takes the whole detail area: the settings page beside a
2239 /// mail-shaped app.
2240 pub fn only_for(mut self, pred: impl Fn(&K) -> bool + 'static) -> ContentList<K> {
2241 self.pred = Some(Rc::new(pred));
2242 self
2243 }
2244 /// Whether the detail is showing, two-way (a `Signal<bool>` or any other binding).
2245 /// Split-family presentations ignore it: the detail pane is always there, showing the
2246 /// app's empty state until a row is chosen. A stacked presentation (a phone, a collapsed
2247 /// split) uses it as the push gate: the list is the top of the stack until the app writes
2248 /// `true` (a row was opened), the detail pushes then, and the platform's back writes
2249 /// `false` on the way out.
2250 pub fn detail_visible(mut self, visible: impl Binding<bool>) -> ContentList<K> {
2251 self.detail_visible = Some(AnyBinding::new(visible));
2252 self
2253 }
2254 /// The detail shows while `selected` holds a value: [`detail_visible`](Self::detail_visible)
2255 /// for a list whose selection is the detail's subject. Writing `Some` opens the detail on a
2256 /// stacked presentation; the platform's back writes `None`, which clears the selection.
2257 ///
2258 /// ```ignore
2259 /// ContentList::new(item_list).detail_for(scene.selected)
2260 /// ```
2261 pub fn detail_for<T: Clone + 'static>(
2262 self,
2263 selected: impl Binding<Option<T>>,
2264 ) -> ContentList<K> {
2265 self.detail_visible(Presence(AnyBinding::new(selected)))
2266 }
2267 /// The navigation-bar title of the detail layer the list opens: the editor a phone pushes
2268 /// over the list, the detail column's bar where the toolkit titles one. Reactive like every
2269 /// title: pass a closure reading your own state to title the page after the item it shows.
2270 /// Unset, the detail layer keeps its destination's title.
2271 pub fn detail_title<M>(mut self, t: impl IntoText<M>) -> ContentList<K> {
2272 self.detail_title = Some(t.into_text());
2273 self
2274 }
2275}
2276
2277/// [`ContentList::detail_for`]'s gate: `true` while the binding holds a value. Writing `false`
2278/// clears it; `true` comes only from the app writing a value.
2279#[derive(Clone)]
2280struct Presence<T: 'static>(AnyBinding<Option<T>>);
2281
2282impl<T: Clone + 'static> Binding<bool> for Presence<T> {
2283 fn read(&self) -> bool {
2284 self.0.get().is_some()
2285 }
2286 fn peek(&self) -> bool {
2287 self.0.get_untracked().is_some()
2288 }
2289 fn write(&self, open: bool) {
2290 if !open && self.peek() {
2291 self.0.set(None);
2292 }
2293 }
2294 fn write_teardown(&self, _open: bool) {}
2295}
2296
2297/// Collapsible sidebar sections (docs/navigation.md), declared with [`Nav::sections`]. The
2298/// state is the set of COLLAPSED section ids; missing ids default to expanded, and temporarily
2299/// filtered-out ids are retained. Pair with [`Nav::section_id`] for stable identities; unkeyed
2300/// headings use their first route as a fallback identity. Takes precedence over
2301/// [`Nav::reorder_items`] and [`Nav::regroup_items`]; combined collapse/reordering is not
2302/// supported.
2303pub struct Sections {
2304 collapsed: AnyBinding<std::collections::HashSet<String>>,
2305 on_change: Option<Rc<dyn Fn(String, bool)>>,
2306}
2307
2308impl Sections {
2309 /// Sections whose collapsed set is app state (a `Signal<HashSet<String>>` or any binding).
2310 pub fn collapsible(collapsed: impl Binding<std::collections::HashSet<String>>) -> Sections {
2311 Sections {
2312 collapsed: AnyBinding::new(collapsed),
2313 on_change: None,
2314 }
2315 }
2316 /// Sections whose collapsed set is persisted under `key` through the installed `NavStore`,
2317 /// restored at build and saved on every change.
2318 pub fn restored(key: impl Into<String>) -> Sections {
2319 let key = key.into();
2320 let saved = day_core::nav_store_load(&key).unwrap_or_default();
2321 let mut rest = saved.as_str();
2322 let mut ids = std::collections::HashSet::new();
2323 while let Some((len, tail)) = rest.split_once(':') {
2324 let Some(len) = len.parse::<usize>().ok() else {
2325 break;
2326 };
2327 let Some(id) = tail.get(..len) else {
2328 break;
2329 };
2330 ids.insert(id.to_owned());
2331 rest = &tail[len..];
2332 }
2333 let state = Signal::new(ids);
2334 bind(
2335 move || state.get(),
2336 move |ids| {
2337 let mut ids: Vec<_> = ids.iter().collect();
2338 ids.sort();
2339 let saved = ids
2340 .iter()
2341 .map(|id| format!("{}:{id}", id.len()))
2342 .collect::<String>();
2343 day_core::nav_store_save(&key, &saved);
2344 },
2345 );
2346 Sections::collapsible(state)
2347 }
2348 /// Reports user/scripting disclosure after the collapsed set changed. Programmatic state
2349 /// writes and restoration do not call it.
2350 pub fn on_change(mut self, f: impl Fn(String, bool) + 'static) -> Sections {
2351 self.on_change = Some(Rc::new(f));
2352 self
2353 }
2354}
2355
2356/// The lowered form of a [`Search`], kept on the nav until build.
2357struct SearchSpec {
2358 query: AnyBinding<String>,
2359 prompt: Option<TextSource>,
2360 placement: day_spec::props::SearchPlacement,
2361 hides_on_scroll: bool,
2362 initially_hidden: bool,
2363 scopes: Vec<TextSource>,
2364 scope: Option<AnyBinding<usize>>,
2365 suggestions: Option<SuggestFn>,
2366 submit: Option<SubmitFn>,
2367}
2368
2369impl SearchSpec {
2370 /// Turn a requested placement into the one this toolkit will actually use (docs/search.md).
2371 ///
2372 /// `Automatic` asks the platform. Today the answer is the window toolbar wherever that
2373 /// toolbar can hold a search field, and inline (attached to the navigation surface) where it
2374 /// cannot, which is the phones: their bar is a row of actions. That needs no size class:
2375 /// "this toolkit's bar holds no field" is a static fact about the backend, not a question
2376 /// about the window's width. Resolving a narrow window on a toolkit whose bar does hold one
2377 /// is what waits on the size-class work.
2378 ///
2379 /// An explicit `Toolbar` falls back to `Inline` on those same backends, since a field the
2380 /// bar cannot draw would otherwise not be drawn at all.
2381 ///
2382 /// Never returns `Automatic`: the props carry the decision, so a backend reads a placement it
2383 /// can act on rather than re-deriving the policy itself.
2384 fn resolve(requested: day_spec::props::SearchPlacement) -> day_spec::props::SearchPlacement {
2385 use day_spec::props::SearchPlacement as P;
2386 use day_spec::{Cap, Support};
2387 let can = |cap| with_tree(|t| t.capability(cap)) != Support::Unsupported;
2388 match requested {
2389 P::Inline => P::Inline,
2390 P::Toolbar if can(Cap::ToolbarSearch) => P::Toolbar,
2391 P::Automatic if can(Cap::Toolbar) && can(Cap::ToolbarSearch) => P::Toolbar,
2392 P::Toolbar | P::Automatic => P::Inline,
2393 }
2394 }
2395
2396 /// The props the host is realized with: current values only. Everything live rides the
2397 /// bindings in [`SearchSpec::bind`].
2398 fn lower(&self) -> day_spec::props::SearchProps {
2399 let text = self.query.get_untracked();
2400 day_spec::props::SearchProps {
2401 suggestions: self
2402 .suggestions
2403 .as_ref()
2404 .map(|f| day_reactive::untrack(|| f(&text)))
2405 .unwrap_or_default(),
2406 text,
2407 prompt: self
2408 .prompt
2409 .as_ref()
2410 .map(TextSource::initial)
2411 .unwrap_or_default(),
2412 // The resolved placement, so a backend reads a decision rather than a request.
2413 placement: Self::resolve(self.placement),
2414 hides_on_scroll: self.hides_on_scroll,
2415 initially_hidden: self.initially_hidden,
2416 scopes: self.scopes.iter().map(TextSource::initial).collect(),
2417 scope: self.scope.map(|s| s.get_untracked()).unwrap_or(0),
2418 }
2419 }
2420
2421 /// Install the field and wire it, both directions (docs/search.md).
2422 ///
2423 /// One model, one writer. `SearchProps` on the nav host is the model for every
2424 /// placement; the toolbar item a desktop backend draws is a rendering of it, not a second
2425 /// representation with its own state. Both inbound transports (a toolbar value callback and
2426 /// `Event::SearchChanged` from an inline field) land on the same `apply` closure, and the
2427 /// single outbound binding patches whichever target the resolved placement renders into.
2428 ///
2429 /// That is what makes a future placement change tractable: the state does not live in the
2430 /// widget, so re-rendering into the other target is a patch rather than a rebuild. The
2431 /// remaining step for the size-class work is a `SearchPatch::Placement` that swaps the render
2432 /// target on a live host; see docs/search.md.
2433 fn install(&self, host: RNode, chrome: day_core::Chrome, seed: &day_spec::props::SearchProps) {
2434 use day_spec::props::{SearchPatch, SearchPlacement as P};
2435 let placement = Self::resolve(self.placement);
2436 let query = self.query;
2437 // Controlled input (§4.4), tracked by value rather than by origin.
2438 //
2439 // This used to be a one-shot origin guard: the inbound handler armed it with the text the
2440 // field reported, and the outbound binding consumed it to avoid patching that same text
2441 // back. One-shot is the wrong shape for a two-way sync. Whether it is armed at the moment
2442 // the binding runs depends on how many changes arrived first and whether the binding ran
2443 // at all, so it swallowed patches it should have sent (a cleared query that never reached
2444 // the field) and let through patches it should have skipped (rewriting the field mid-type,
2445 // which resets the caret and drops focus on AppKit).
2446 //
2447 // What the field holds is the fact that matters, and it is knowable: the field reports
2448 // every value it takes, and Day knows every value it pushes. Comparing against it is
2449 // idempotent and order-independent, with nothing to arm or consume and no way to get out
2450 // of step. Equal means the field already shows it, so there is nothing to push and no
2451 // caret to disturb.
2452 let shown: Rc<RefCell<String>> = Rc::new(RefCell::new(seed.text.clone()));
2453
2454 if placement == P::Toolbar {
2455 let g = shown.clone();
2456 let submit = self.submit.clone();
2457 let action = day_core::register_toolbar_value(Rc::new(
2458 move |v: &day_spec::ToolbarValue| match v {
2459 day_spec::ToolbarValue::Text(t) => {
2460 *g.borrow_mut() = t.clone();
2461 query.set(t.clone());
2462 }
2463 day_spec::ToolbarValue::Submit(t) => {
2464 if let Some(f) = &submit {
2465 f(t);
2466 }
2467 }
2468 _ => {}
2469 },
2470 ));
2471 // An ordinary contribution on this host's chrome, placed last (where every
2472 // desktop puts search) and withdrawn with the surface it filters.
2473 let suggestions = seed.suggestions.clone();
2474 let item = move |text: String, prompt: String| day_spec::ToolbarItem {
2475 id: day_core::id!(day::search).as_str().to_owned(),
2476 kind: day_spec::ToolbarItemKind::Search {
2477 text,
2478 placeholder: prompt.clone(),
2479 suggestions: suggestions.clone(),
2480 },
2481 label: prompt,
2482 tooltip: None,
2483 icon: None,
2484 enabled: true,
2485 action,
2486 placement: day_spec::ToolbarPlacement::Secondary,
2487 label_style: day_spec::LabelStyle::Automatic,
2488 prominent: false,
2489 // Desktop search belongs at the trailing edge of the window toolbar.
2490 column: day_spec::ToolbarColumn::Detail,
2491 };
2492 let token = day_core::register_contribution(
2493 chrome,
2494 vec![item(seed.text.clone(), seed.prompt.clone())],
2495 );
2496 // The prompt follows the locale: a changed text re-registers the field with it.
2497 if let Some(TextSource::Dyn(read)) = self.prompt.clone() {
2498 let shown = shown.clone();
2499 bind_seeded(
2500 seed.prompt.clone(),
2501 move || read(),
2502 move |p: &String| {
2503 let text = shown.borrow().clone();
2504 day_core::update_contribution(token, vec![item(text, p.clone())]);
2505 },
2506 );
2507 }
2508 Scope::current().on_cleanup(move || day_core::unregister_contribution(token));
2509 } else {
2510 // Inline: no bar item exists, so the reserved id is answered by the host itself.
2511 // That is what lets a dayscript `toolbar: { item: day::search, text }` reach the same
2512 // query on a phone as on a desktop (docs/search.md): day-core resolves the id to
2513 // this host and delivers `Event::SearchChanged`, the event the native field emits.
2514 day_core::register_search_host(host);
2515 Scope::current().on_cleanup(move || day_core::unregister_search_host(host));
2516 }
2517
2518 // The one outbound binding: the app writing its query reaches whichever target this
2519 // placement renders into. Seeded, because `lower` already put the value in the realize
2520 // props; re-applying it here would be the duplicate op §5.2 forbids.
2521 bind_seeded(
2522 seed.text.clone(),
2523 move || query.get(),
2524 move |t: &String| {
2525 if *shown.borrow() == *t {
2526 return; // the field already shows this; patching it back fights the caret
2527 }
2528 *shown.borrow_mut() = t.clone();
2529 match placement {
2530 // The patch mirrors into the owning contribution as well, so a later
2531 // re-lower of this chrome rebuilds the field with the text it is showing
2532 // rather than the one it was declared with.
2533 P::Toolbar => day_core::patch_chrome(
2534 chrome,
2535 day_spec::ToolbarPatch::Text {
2536 item: SEARCH_ITEM_ID.to_string(),
2537 text: t.clone(),
2538 },
2539 ),
2540 _ => {
2541 let p = SearchPatch::Text(t.clone());
2542 with_tree(|tr| tr.patch(host, Box::new(p), false));
2543 }
2544 }
2545 },
2546 );
2547
2548 if let Some(sig) = self.scope {
2549 let seed_scope = seed.scope;
2550 bind_seeded(
2551 seed_scope,
2552 move || sig.get(),
2553 move |i| {
2554 let p = SearchPatch::Scope(*i);
2555 with_tree(|tr| tr.patch(host, Box::new(p), false));
2556 },
2557 );
2558 }
2559 // Completions re-derive on every keystroke and on whatever else the closure reads.
2560 if let Some(f) = self.suggestions.clone() {
2561 bind_seeded(
2562 seed.suggestions.clone(),
2563 move || f(&query.get()),
2564 move |list| match placement {
2565 P::Toolbar => day_core::patch_chrome(
2566 chrome,
2567 day_spec::ToolbarPatch::Suggestions {
2568 item: SEARCH_ITEM_ID.to_string(),
2569 list: list.clone(),
2570 },
2571 ),
2572 _ => {
2573 let p = SearchPatch::Suggestions(list.clone());
2574 with_tree(|t| t.patch(host, Box::new(p), false));
2575 }
2576 },
2577 );
2578 }
2579 }
2580}
2581
2582pub fn nav<K: Route, S: Binding<K>>(selection: S) -> Nav<S, K> {
2583 Nav {
2584 selection,
2585 documents: None,
2586 document_event: None,
2587 icon_progress: None,
2588 refresh: None,
2589 style: NavStyle::default(),
2590 sidebar_toggle: true,
2591 title: TextSource::Static(String::new()),
2592 header: None,
2593 footer: None,
2594 sources: Vec::new(),
2595 destination: None,
2596 routed: true,
2597 restore: None,
2598 retain_selection: None,
2599 reorder_items: None,
2600 collapsed_sections: None,
2601 on_section_expansion: None,
2602 toolbar: Vec::new(),
2603 search: None,
2604 presentation: None,
2605 content_list: None,
2606 content_list_width: day_spec::NAV_LIST_WIDTH,
2607 content_list_pred: None,
2608 detail_visible: None,
2609 detail_title: None,
2610 }
2611}
2612
2613#[day_macros::builder(NavBuilder<K>)]
2614impl<K: Route, S: Binding<K>> Nav<S, K> {
2615 /// Add the platform's pull-to-refresh control to the sidebar rows (docs/navigation.md).
2616 /// UIKit uses UIRefreshControl, Android SwipeRefreshLayout. Other toolkits can ignore
2617 /// this affordance, so retain a Refresh command for keyboard/accessibility users.
2618 /// `refreshing` is app-owned: set it synchronously when accepting a request and clear it
2619 /// on completion, failure or cancellation. Repeated pulls while busy are ignored. A
2620 /// declined request stops the indicator immediately. Programmatic state writes never
2621 /// call `action`. The handler and state bindings live only as long as this navigation.
2622 pub fn refreshable<M>(
2623 mut self,
2624 refreshing: impl IntoReactive<bool, M>,
2625 action: impl Fn() + 'static,
2626 ) -> Self {
2627 self.refresh = Some((refreshing.into_reactive(), Rc::new(action)));
2628 self
2629 }
2630
2631 pub(crate) fn document_mode(
2632 mut self,
2633 config: day_spec::props::DocumentTabsConfig,
2634 event: impl Fn(&Event) + 'static,
2635 ) -> Self {
2636 self.documents = Some(config);
2637 self.document_event = Some(Rc::new(event));
2638 self
2639 }
2640 /// Collapsible sidebar sections (docs/navigation.md), as a [`Sections`] value:
2641 /// `nav(sel).sections(Sections::restored("nav.sections").on_change(f))`.
2642 pub fn sections(mut self, sections: Sections) -> Self {
2643 self.collapsed_sections = Some(sections.collapsed);
2644 self.on_section_expansion = sections.on_change;
2645 self
2646 }
2647 /// A section with a persistent identity independent of its localized title or first row,
2648 /// heading `content` (one item, a tuple, an `Option`, a [`nav_items`] block, or a mix).
2649 pub fn section_id<M>(
2650 mut self,
2651 id: impl Into<String>,
2652 title: impl IntoText<M>,
2653 content: impl NavContent<K>,
2654 ) -> Self {
2655 self.push_section(
2656 SectionHeader {
2657 id: Some(id.into()),
2658 title: title.into_text(),
2659 },
2660 content,
2661 );
2662 self
2663 }
2664 /// Append `content` under a section header (docs/navigation.md). Backends without grouped
2665 /// rows ignore the header and show one flat list, so a section is a grouping hint, never a
2666 /// source of items the user cannot otherwise reach.
2667 fn push_section(&mut self, header: SectionHeader, content: impl NavContent<K>) {
2668 let mut sources = Vec::new();
2669 content.push_sources(&mut sources);
2670 let mut sources = sources.into_iter();
2671 // The header rides the first row of the content: a static item carries it directly; a
2672 // data-driven block heads its first row with it, wherever the data starts.
2673 match sources.next() {
2674 Some(ItemSource::Static(mut it)) => {
2675 if it.section.is_none() {
2676 it.section = Some(header);
2677 }
2678 self.sources.push(ItemSource::Static(it));
2679 }
2680 Some(ItemSource::Dynamic(f)) => {
2681 self.sources.push(ItemSource::Dynamic(Box::new(move || {
2682 let mut rows = f();
2683 if let Some(first) = rows.first_mut()
2684 && first.section.is_none()
2685 {
2686 first.section = Some(header.clone());
2687 }
2688 rows
2689 })));
2690 }
2691 None => {}
2692 }
2693 self.sources.extend(sources);
2694 }
2695
2696 /// Enable dragging within contiguous runs of eligible sidebar items. Fixed items and
2697 /// section headers cannot be crossed. The callback receives the moved key and the key
2698 /// whose position it takes (indices refer to the order before removal).
2699 /// Uses the shared list reorder driver where `Cap::NavReorder` supports it; otherwise
2700 /// retains the native navigation widget. UIKit navigation remains fixed even though
2701 /// content lists support dragging. Tab/rail chrome remains fixed. Persist the order in the callback's backing data.
2702 pub fn reorder_items(
2703 mut self,
2704 eligible: impl Fn(&K) -> bool + 'static,
2705 moved: impl Fn(K, K) + 'static,
2706 ) -> Self {
2707 self.reorder_items = Some(SidebarDrag::Reorder(NavReorder {
2708 eligible: Rc::new(eligible),
2709 moved: Rc::new(moved),
2710 }));
2711 self
2712 }
2713
2714 /// Like [`Self::reorder_items`], but rows may also cross section headers: drag a feed from
2715 /// one collection's section into another's (docs/navigation.md "Moving rows between
2716 /// sections"). `drag` says how each row drags, re-asked whenever the rows change:
2717 /// [`NavDrag::Reorder`] rows move within their section and into others,
2718 /// [`NavDrag::Regroup`] rows only into others (their own section keeps the app's sorted
2719 /// order), and a section holding a [`NavDrag::Fixed`] row takes no drop at all. Rows above
2720 /// the first header form one unnamed section. `dropped` gets the moved key, the
2721 /// destination section's `section_id` and the row it now sits before; a drop back where
2722 /// the row started reports nothing. Apply the move to the app's data, which brings the new
2723 /// rows back. Declaring this and [`Self::reorder_items`] on one nav keeps the later one;
2724 /// collapsible [`Self::sections`] take precedence over both. Probe `Cap::NavReorder`.
2725 pub fn regroup_items(
2726 mut self,
2727 drag: impl Fn(&K) -> NavDrag + 'static,
2728 dropped: impl Fn(NavDrop<K>) + 'static,
2729 ) -> Self {
2730 self.reorder_items = Some(SidebarDrag::Regroup(NavRegroup {
2731 drag: Rc::new(drag),
2732 dropped: Rc::new(dropped),
2733 }));
2734 self
2735 }
2736
2737 /// Preserve the current destination when its row disappears and `keep` returns true.
2738 /// Useful for filtered sidebars: reading a feed's last unread article can hide its row
2739 /// without closing the article. The native sidebar then has no highlighted row.
2740 /// Return false for deleted records to retain the normal selection-reset behavior.
2741 /// Evaluated when the item list changes; pair with [`Self::destination`] for dynamic keys.
2742 pub fn retain_selection_when(mut self, keep: impl Fn(&K) -> bool + 'static) -> Self {
2743 self.retain_selection = Some(Rc::new(keep));
2744 self
2745 }
2746
2747 /// Progress over leading icons, without rebuilding rows or changing label geometry.
2748 /// Return active route keys with None while connecting/unknown-length, or Some(0..=1)
2749 /// for a known fraction. Omit finished keys. AppKit/UIKit animate in the compositor;
2750 /// other toolkits currently leave icons unchanged. Bind separately from `.items`.
2751 pub fn icon_progress(mut self, progress: impl Fn() -> Vec<(K, Option<f64>)> + 'static) -> Self {
2752 self.icon_progress = Some(Rc::new(progress));
2753 self
2754 }
2755
2756 pub fn style(mut self, style: NavStyle) -> Self {
2757 self.style = style;
2758 self
2759 }
2760 /// The sidebar / window title (Sidebar style).
2761 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
2762 self.title = t.into_text();
2763 self
2764 }
2765 /// A section: `content` (one item, a tuple, an `Option`, a [`nav_items`] block, or a mix)
2766 /// under a header. Backends without grouped rows ignore the header and show one flat list,
2767 /// so a section is a grouping hint, never a source of items the user cannot otherwise reach.
2768 ///
2769 /// ```ignore
2770 /// nav(sel)
2771 /// .section(res::str::smart_feeds(), (
2772 /// item("today", res::str::today()).icon(res::images::today).page(today_page),
2773 /// item("unread", res::str::unread()).icon(res::images::unread).page(unread_page),
2774 /// ))
2775 /// .section(res::str::feeds(), nav_items(move || st.feeds.get(), |f| item(f.id, f.name)))
2776 /// ```
2777 pub fn section<M>(mut self, title: impl IntoText<M>, content: impl NavContent<K>) -> Self {
2778 self.push_section(
2779 SectionHeader {
2780 id: None,
2781 title: title.into_text(),
2782 },
2783 content,
2784 );
2785 self
2786 }
2787 /// An optional piece shown above the sidebar list (a logo, app name…).
2788 pub fn header<P: Piece>(mut self, build: impl FnOnce() -> P + 'static) -> Self {
2789 self.header = Some(Box::new(move || AnyPiece::new(build())));
2790 self
2791 }
2792 /// An optional piece pinned below the sidebar list, outside its scroll area.
2793 /// It belongs to the root page: stacked destinations do not carry it along.
2794 /// Like [`Self::header`], this slot applies to sidebar navigation, not tab/rail chrome.
2795 pub fn footer<P: Piece>(mut self, build: impl FnOnce() -> P + 'static) -> Self {
2796 self.footer = Some(Box::new(move || AnyPiece::new(build())));
2797 self
2798 }
2799 /// Pin the presentation instead of letting the window's size decide (docs/size-classes.md).
2800 ///
2801 /// Leave this unset (the default) and the nav shows sidebar+detail on a window wide
2802 /// enough for both and stacks on one that is not, re-presenting live as the window is resized
2803 /// or the device rotated. Pin it when the content only works one way: a settings sidebar whose
2804 /// detail is meaningless alone, a wizard that must stay a stack.
2805 ///
2806 /// A pin is still a preference. A toolkit with no split container (the phones today) stacks
2807 /// whatever is asked for, exactly as it does for the automatic case.
2808 pub fn presentation(mut self, presentation: day_spec::props::NavPresentation) -> Self {
2809 self.presentation = Some(presentation);
2810 self
2811 }
2812 /// A content-list pane between the sidebar and the detail, the Mail shape (docs/navigation.md),
2813 /// as a [`ContentList`] value:
2814 ///
2815 /// ```ignore
2816 /// nav(scene.section).content_list(
2817 /// ContentList::new(pages::items::item_list_pane)
2818 /// .width(320.0)
2819 /// .only_for(|s: &Section| matches!(s, Section::Items))
2820 /// .detail_visible(scene.detail_open)
2821 /// .detail_title(move || pages::items::detail_title(scene)),
2822 /// )
2823 /// ```
2824 pub fn content_list(mut self, list: ContentList<K>) -> Self {
2825 self.content_list = Some(list.build);
2826 self.content_list_width = list.width;
2827 self.content_list_pred = list.pred;
2828 self.detail_visible = list.detail_visible;
2829 self.detail_title = list.detail_title;
2830 self
2831 }
2832 /// Add one destination: `item(key, title).page(build)` in one call. `key` addresses it
2833 /// (navigate / deep link / dayscript); `title` is its label; `build` runs when the item is
2834 /// first shown. For a typed nav over `Option<Section>` pass the bare `Section::X`. For an
2835 /// icon, a badge or a tint, build the [`item`] value and add it with [`items`](Self::items).
2836 pub fn item<M, P: Piece>(
2837 self,
2838 key: impl Into<K>,
2839 title: impl IntoText<M>,
2840 build: impl Fn() -> P + 'static,
2841 ) -> Self {
2842 self.items(crate::item(key, title).page(build))
2843 }
2844 /// Add items (docs/navigation.md): one [`item`], a tuple of them, an `Option`, a `Vec`, a
2845 /// data-driven [`nav_items`] block, or a mix. Static items and blocks may be mixed in any
2846 /// order; the final list is their declaration order.
2847 ///
2848 /// ```ignore
2849 /// nav(sel).items((
2850 /// item("home", res::str::home()).icon(res::images::home).page(home_page),
2851 /// nav_items(move || rooms.get(), |r| item(r.id.clone(), r.name.clone())),
2852 /// prefs.nav_item(Section::Settings),
2853 /// ))
2854 /// ```
2855 pub fn items(mut self, content: impl NavContent<K>) -> Self {
2856 content.push_sources(&mut self.sources);
2857 self
2858 }
2859 /// Build the page for a key whose item has no [`page`](NavItem::page) of its own (the rows
2860 /// of a data-driven block). Mirrors [`NavStack::destination`]; unused for a nav whose items
2861 /// all carry a page.
2862 pub fn destination<P: Piece>(mut self, build: impl Fn(&K) -> P + 'static) -> Self {
2863 self.destination = Some(Rc::new(move |k| AnyPiece::new(build(k))));
2864 self
2865 }
2866 /// Use this nav as a local widget: its selection is not part of the app route, so it
2867 /// neither adds a segment to `current_route` nor intercepts `navigate`/deep links.
2868 ///
2869 /// Reach for this when a page already routes and you embed a second one-of-N control in
2870 /// it (a filter tab strip, a secondary sidebar). Two routing selectors at the same level both
2871 /// feed `current_route()`, so you'd get `section/childA/childB` and `navigate("childB")` would
2872 /// be ambiguous; mark all but the primary one `.local()`. A nav nested one level deeper
2873 /// (a `Tabs` inside a `Sidebar` section) is a different case and should stay routed: its
2874 /// key belongs in the cascade. In debug builds, two routed one-of-N surfaces at the same
2875 /// level log a warning naming this fix (docs/navigation.md).
2876 pub fn local(mut self) -> Self {
2877 self.routed = false;
2878 self
2879 }
2880 /// Remember the selected item across launches (docs/navigation.md). The selected key is saved
2881 /// under `key` on every change and restored at build (so the app reopens on the tab/section
2882 /// the user last had) unless a launch deep link is pending, which wins. `day::launch`
2883 /// installs the preferences as the store (docs/navigation.md); a stale saved
2884 /// key (its item no longer exists) is ignored. Works whether or not the nav is
2885 /// [`routed`](Self::local).
2886 pub fn restore(mut self, key: impl Into<String>) -> Self {
2887 self.restore = Some(key.into());
2888 self
2889 }
2890 /// Declare toolbar items on this host's chrome (docs/toolbars.md): the sidebar column
2891 /// where the presentation has one, and the root list when it has collapsed to a stack.
2892 ///
2893 /// This is where a command that acts on the list belongs: "add an item", "sort", "filter".
2894 /// A command that acts on whatever page is open belongs on the page instead, declared with
2895 /// the same method on the piece that page builds, and then it comes and goes with that page
2896 /// rather than riding a list it cannot act on.
2897 ///
2898 /// Takes one item, a list of them, or a closure that derives the list and re-runs whenever
2899 /// its reactive reads change.
2900 ///
2901 /// ```ignore
2902 /// nav(section)
2903 /// .toolbar(toolbar_button(day_core::id!(add), tr("add")).icon(Symbol::Add).action(add_item))
2904 /// ```
2905 pub fn toolbar<M>(mut self, content: impl crate::ToolbarContent<M>) -> Self {
2906 self.toolbar.push(content.into_source());
2907 self
2908 }
2909
2910 /// Do not draw the platform's own show/hide-sidebar affordance on this host's chrome. It is
2911 /// on by default for a sidebar presentation, since every desktop expects one and the
2912 /// toolkit owns both the button and the behavior; this is for a window that should not
2913 /// offer it.
2914 pub fn no_sidebar_toggle(mut self) -> Self {
2915 self.sidebar_toggle = false;
2916 self
2917 }
2918
2919 /// Make this surface searchable (docs/search.md), as a [`Search`] value:
2920 ///
2921 /// ```ignore
2922 /// nav(section)
2923 /// .style(NavStyle::Sidebar)
2924 /// .searchable(Search::new(query).prompt(res::str::search()).reveal(SearchReveal::OnPull))
2925 /// .items(nav_items(move || destinations().filter(|d| matches_query(d, &query.get())), destination_row))
2926 /// ```
2927 pub fn searchable(mut self, search: Search) -> Self {
2928 let (hides_on_scroll, initially_hidden) = match search.reveal {
2929 SearchReveal::Always => (false, false),
2930 SearchReveal::Scrolls => (true, false),
2931 SearchReveal::OnPull => (true, true),
2932 };
2933 self.search = Some(SearchSpec {
2934 query: search.query,
2935 prompt: search.prompt,
2936 placement: search.placement,
2937 hides_on_scroll,
2938 initially_hidden,
2939 scopes: search.scopes,
2940 scope: search.scope,
2941 suggestions: search.suggestions,
2942 submit: search.submit,
2943 });
2944 self
2945 }
2946}
2947
2948impl<K: Route, S: Binding<K>> Piece for Nav<S, K> {
2949 fn build(self, cx: &mut BuildCx) -> RNode {
2950 // One builder for all three styles. The styles differ only in which presentations the
2951 // resolver may produce, and a presentation differs only in chrome and page residency,
2952 // so a tab bar is a `kinds::NAV` host wearing a different hat, not a second host kind
2953 // with its own props, patches, and nine backend implementations (docs/navigation.md).
2954 build_selector(self, cx)
2955 }
2956}
2957
2958/// Apply a nav's `.restore` at build: seed `selection` from the key saved under `restore`,
2959/// so the app reopens on the section/tab the user last chose. A pending launch deep link wins
2960/// (skip). Only a saved key that parses and is a current item is honored (plus the empty
2961/// "deselected" key, for a sidebar's collapsed state), so a stale key left by an older build is
2962/// ignored. A no-op when `restore` is unset or no [`NavStore`](day_core::NavStore) is installed.
2963fn restore_selection<K: Route, S: Binding<K>>(
2964 restore: &Option<String>,
2965 selection: &S,
2966 items: &[K],
2967) {
2968 if let Some(key) = restore.as_deref()
2969 && !day_core::has_launch_deeplink()
2970 && let Some(saved) = day_core::nav_store_load(key)
2971 && let Some(k) = K::from_key(&saved)
2972 && (saved.is_empty() || items.iter().any(|x| x.key() == saved))
2973 {
2974 selection.write(k);
2975 }
2976}
2977
2978/// Persist a nav's selection under its `.restore` key on every change (docs/navigation.md).
2979/// The binding lives in the current scope, so it stops with the surface. Consumes `restore`.
2980fn persist_selection<K: Route, S: Binding<K>>(restore: Option<String>, selection: &S) {
2981 if let Some(key) = restore {
2982 let s = selection.clone();
2983 bind(
2984 move || s.read().key(),
2985 move |k: &String| day_core::nav_store_save(&key, k),
2986 );
2987 }
2988}
2989
2990// ---------------------------------------------------------------------------
2991// The composed gated detail (docs/navigation.md): where the toolkit has no content-list pane,
2992// a list-backed destination with `detail_visible` is a two-layer navigation flow rather than
2993// an in-place swap. In a chrome presentation (a tab bar, a rail) the destination's page
2994// is a nested navigation host of its own: the platform's stack controller inside the tab,
2995// the list at its root, the detail pushed over it. In a stacked presentation the list renders
2996// inline in the destination's (already pushed) page and the detail pushes onto the enclosing
2997// host, exactly as a merged `nav_stack()`'s pages do. Both give the compact flow what the native
2998// idiom always had: a navigation bar, a title, and a back that pops.
2999// ---------------------------------------------------------------------------
3000
3001/// What the gated flow needs from its nav, cloneable into the `when` branches that build
3002/// one shape or the other as the presentation changes.
3003struct GatedDetail<K: Route> {
3004 /// Whether the detail layer is up: the nav's `detail_visible` binding, two-way.
3005 open: AnyBinding<bool>,
3006 /// Builds the content list, the root layer.
3007 list: Rc<dyn Fn() -> AnyPiece>,
3008 /// The nav's items: the detail content builder and the immersive flag.
3009 items: Rc<SelItems<K>>,
3010 key: K,
3011 /// The destination's resolved title (the root layer's bar) and its live source.
3012 title: String,
3013 retitle: Option<TextSource>,
3014 /// The pushed detail's title source (`Nav::detail_title`); `None` = `title`.
3015 detail_title: Option<TextSource>,
3016 /// The enclosing nav's host, the merge target while stacked.
3017 host_cx: NavHostCx,
3018 /// The nav's toolbar sources, re-homed onto the nested host in a chrome
3019 /// presentation, whose tabs chrome draws none of its own.
3020 toolbar: Vec<crate::ToolbarSource>,
3021}
3022
3023impl<K: Route> Clone for GatedDetail<K> {
3024 fn clone(&self) -> Self {
3025 GatedDetail {
3026 open: self.open,
3027 list: self.list.clone(),
3028 items: self.items.clone(),
3029 key: self.key.clone(),
3030 title: self.title.clone(),
3031 retitle: self.retitle.clone(),
3032 detail_title: self.detail_title.clone(),
3033 host_cx: self.host_cx.clone(),
3034 toolbar: self.toolbar.clone(),
3035 }
3036 }
3037}
3038
3039/// The gated flow's piece. The shape follows the live presentation, so a morph between a tab
3040/// bar and a stack rebuilds the right container.
3041///
3042/// The condition asks the full question (chrome rows and a compact window) rather than
3043/// leaning on the enclosing side-by-side `when` to have ruled the wide case out. The two
3044/// react to the same signals, and their evaluation order in one flush is not promised: a
3045/// `NavStack → Rail` morph on a desktop flips both at once, and a condition that only asked
3046/// "chrome?" would build a nested navigation host for the one evaluation before the outer
3047/// branch replaces it, a whole native host realized and torn down in a single flush, which
3048/// wedged Qt.
3049fn gated_detail_piece<K: Route>(
3050 cfg: GatedDetail<K>,
3051 pres: Signal<day_spec::props::NavPresentation>,
3052 window: RNode,
3053) -> AnyPiece {
3054 let (c1, c2) = (cfg.clone(), cfg);
3055 AnyPiece::new(
3056 when(
3057 move || {
3058 pres.get().rows_are_chrome()
3059 && !day_core::window_size_class(window).is_some_and(|c| c.prefers_split())
3060 },
3061 move || gated_detail_nested(c1.clone()),
3062 )
3063 .otherwise(move || gated_detail_merged(c2.clone())),
3064 )
3065}
3066
3067/// A chrome presentation's gated destination: a nested navigation host of its own (a
3068/// `UINavigationController` inside the tab, a Material toolbar over the fragment back stack),
3069/// which is what gives the tab a navigation bar, a title, and a native back. Standalone by
3070/// construction: a resident page is a merge barrier (docs/navigation.md).
3071fn gated_detail_nested<K: Route>(cfg: GatedDetail<K>) -> impl Piece {
3072 piece_fn(move |cx| {
3073 use day_spec::props::{NavPageProps, NavPresentation, NavProps, Pane};
3074 let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>> = Rc::default();
3075 let host = cx.native(
3076 kinds::NAV,
3077 &NavProps {
3078 documents: None,
3079 title: cfg.title.clone(),
3080 // A permanent stack, like the `nav_stack()` piece: the chrome above already
3081 // adapts, so this host must never try to.
3082 presentation: NavPresentation::Stack,
3083 adaptive: false,
3084 sidebar_toggle: false,
3085 search: None,
3086 list_width: None,
3087 list_visible: true,
3088 },
3089 Rc::new(NavLayout::stack(sizes.clone())),
3090 Flex {
3091 grow_w: true,
3092 grow_h: true,
3093 ..Default::default()
3094 },
3095 Boundary::Yes,
3096 );
3097 let owners: Rc<RefCell<Vec<PopOwner>>> = Rc::default();
3098 let target = NavHostCx {
3099 host,
3100 sizes: sizes.clone(),
3101 owners: owners.clone(),
3102 split: Rc::new(Cell::new(false)),
3103 guards: Rc::default(),
3104 };
3105 let root_page = nav_page(
3106 host,
3107 &NavPageProps {
3108 title: cfg.title.clone(),
3109 pane: Pane::Detail,
3110 },
3111 &sizes,
3112 );
3113 // The list is this host's root page, so a `nav_stack()` inside it merges here: a drill-down
3114 // from the list (a category, then its items) pushes onto the tab's own navigation
3115 // controller, and the gated detail lands on top of whatever it pushed
3116 // (docs/navigation.md). Only the native resident pane is a barrier.
3117 // This shape shows one layer at a time, so the list's commands leave once the detail is
3118 // pushed over it, the same rule the native pane follows. The enclosing page's own gate
3119 // still applies: a tab that is not selected takes the list's commands with it.
3120 let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
3121 with_nav_host(Some(target.clone()), || {
3122 day_core::with_page_gated(
3123 root_page,
3124 Some(covered),
3125 day_spec::ToolbarColumn::List,
3126 || {
3127 let mut pcx = BuildCx::new(root_page);
3128 let _ = (cfg.list)().grow(Dimension::Both).build(&mut pcx);
3129 },
3130 );
3131 });
3132 // The nav's items, re-homed: a chrome presentation draws no bar of its own, so this
3133 // nested host's root page is where the list's commands belong (docs/toolbars.md).
3134 for source in cfg.toolbar.clone() {
3135 crate::contribute(day_core::Chrome::Page(root_page), source);
3136 }
3137 // This host's one back dispatcher: the topmost owner, the detail layer's or a
3138 // stack's that merged inside the detail.
3139 {
3140 let owners = owners.clone();
3141 cx.on(host, move |ev| match ev {
3142 Event::NavBack { already_popped } => {
3143 let top = owners.borrow().last().cloned();
3144 if let Some(f) = top {
3145 f(*already_popped);
3146 }
3147 }
3148 Event::RouteRequested(route) => {
3149 let _ = day_core::navigate(route);
3150 }
3151 _ => {}
3152 });
3153 }
3154 wire_gated_detail(&cfg, target);
3155 host
3156 })
3157}
3158
3159/// A stacked presentation's gated destination: the list renders inline in the destination's
3160/// own page and the detail pushes onto the enclosing host, the same merge a nested `nav_stack()`
3161/// performs, so the whole chain stays one native stack with one back button
3162/// (docs/navigation.md).
3163fn gated_detail_merged<K: Route>(cfg: GatedDetail<K>) -> impl Piece {
3164 piece_fn(move |cx| {
3165 let target = cfg.host_cx.clone();
3166 // The list is inline in a page of the enclosing stack, so a `nav_stack()` inside it merges
3167 // there, as one inside any pushed page does (docs/navigation.md).
3168 // Same rule as the nested shape: the detail pushes over this list, so the list's own
3169 // commands leave the bar while it is covered (docs/toolbars.md), and while the page it is
3170 // inline in is not showing.
3171 let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
3172 // The page this list is inline in, whichever it is: the gate is what matters, and the
3173 // frame keeps the chrome it was already going to land on.
3174 let page = match day_core::current_chrome() {
3175 day_core::Chrome::Page(p) => p,
3176 day_core::Chrome::Window(w) => w,
3177 };
3178 let node = with_nav_host(Some(target.clone()), || {
3179 day_core::with_page_gated(page, Some(covered), day_spec::ToolbarColumn::List, || {
3180 (cfg.list)().grow(Dimension::Both).build(cx)
3181 })
3182 });
3183 wire_gated_detail(&cfg, target);
3184 node
3185 })
3186}
3187
3188/// Drive the detail layer from `detail_visible`, whichever host carries it: `true` pushes the
3189/// destination's page onto `target`, `false` (and the native back, which writes it) pops.
3190/// Registered in the current scope, so a section switch or a presentation morph tears the
3191/// layer down with the shape that built it.
3192fn wire_gated_detail<K: Route>(cfg: &GatedDetail<K>, target: NavHostCx) {
3193 use day_spec::props::{NavPageProps, NavPatch, Pane};
3194 /// The pushed layer: its page, and the scope its content lives in.
3195 struct Layer {
3196 scope: Scope,
3197 page: RNode,
3198 }
3199 let layer: Rc<RefCell<Option<Layer>>> = Rc::default();
3200 // Pops the toolkit already performed (an iOS swipe, the Android system back): the
3201 // answering `Popped` is absorbed rather than re-issued, same as a stack's.
3202 let native_popped: Rc<Cell<usize>> = Rc::default();
3203 let open = cfg.open;
3204 let owner_scope = Scope::current();
3205
3206 // The native back, while the detail is up: report it into the signal; the pop itself is
3207 // performed by the binding below, so a back and a programmatic `false` are one path.
3208 let owner: PopOwner = {
3209 let native_popped = native_popped.clone();
3210 Rc::new(move |already_popped: bool| {
3211 if already_popped {
3212 native_popped.set(native_popped.get() + 1);
3213 }
3214 open.set(false);
3215 })
3216 };
3217
3218 let detail_src = cfg.detail_title.clone();
3219 let root_title = cfg.title.clone();
3220 let push = {
3221 let (layer, target, owner) = (layer.clone(), target.clone(), owner.clone());
3222 let (items, key) = (cfg.items.clone(), cfg.key.clone());
3223 let (detail_src, root_title) = (detail_src.clone(), root_title.clone());
3224 move || {
3225 if layer.borrow().is_some() {
3226 return;
3227 }
3228 let title = detail_src
3229 .as_ref()
3230 .map(TextSource::initial)
3231 .unwrap_or_else(|| root_title.clone());
3232 let page = nav_page(
3233 target.host,
3234 &NavPageProps {
3235 title: title.clone(),
3236 pane: Pane::Detail,
3237 },
3238 &target.sizes,
3239 );
3240 // Before the content builds, so a stack that merges inside the detail lands its
3241 // owners on top of this one.
3242 target.owners.borrow_mut().push(owner.clone());
3243 let scope = owner_scope.enter(Scope::child);
3244 let tc = target.clone();
3245 scope.enter(|| {
3246 // The app's builder runs inside this page's scope, like the presentation site
3247 // further down: a page body runs app code (an ambient state read, a `Signal`,
3248 // a registration), and all of it belongs to the page's lifetime rather than to
3249 // whichever scope happened to be current when the push landed.
3250 let content = items.build_page(&key);
3251 with_nav_host(Some(tc), || {
3252 day_core::with_page(page, || {
3253 let mut c = BuildCx::new(page);
3254 let _ = content.grow(Dimension::Both).build(&mut c);
3255 });
3256 });
3257 });
3258 // Out here for the usual reason: `immersive_of` can run app code, which must not
3259 // happen inside `with_tree`.
3260 let immersive = items.immersive_of(&key.key());
3261 with_tree(|t| {
3262 t.patch(
3263 target.host,
3264 Box::new(NavPatch::Pushed { title, immersive }),
3265 false,
3266 );
3267 t.mark_layout_dirty();
3268 t.layout_if_needed();
3269 });
3270 *layer.borrow_mut() = Some(Layer { scope, page });
3271 }
3272 };
3273 let pop = {
3274 let (layer, target, native_popped) = (layer.clone(), target.clone(), native_popped.clone());
3275 move || {
3276 let taken = layer.borrow_mut().take();
3277 let Some(l) = taken else {
3278 return;
3279 };
3280 // Scope first: a merged inner stack's cleanup pops its pages (which sit on top
3281 // natively) before this pops the detail itself: top-down, the order native
3282 // stacks demand.
3283 l.scope.dispose();
3284 if native_popped.get() > 0 {
3285 native_popped.set(native_popped.get() - 1);
3286 } else {
3287 with_tree(|t| t.patch(target.host, Box::new(NavPatch::Popped), false));
3288 }
3289 target.owners.borrow_mut().pop();
3290 target.sizes.borrow_mut().remove(&l.page);
3291 with_tree(|t| {
3292 t.remove_subtree(l.page);
3293 t.mark_layout_dirty();
3294 t.layout_if_needed();
3295 });
3296 }
3297 };
3298 {
3299 let (push, pop) = (push, pop.clone());
3300 bind(
3301 move || open.get(),
3302 move |v: &bool| if *v { push() } else { pop() },
3303 );
3304 }
3305
3306 // The top layer's bar, live: the detail title while up (re-resolving as the state it
3307 // reads changes), the destination's while down. Seeded with what the build just drew, and
3308 // sent unconditionally: while the layer is down the enclosing top carries the same
3309 // destination title, so the patch is a no-op there rather than a wrong name.
3310 {
3311 let (retitle, host) = (cfg.retitle.clone(), target.host);
3312 let top_title = move || {
3313 let root = || {
3314 retitle
3315 .as_ref()
3316 .map_or_else(|| root_title.clone(), TextSource::resolve)
3317 };
3318 if open.get() {
3319 detail_src.as_ref().map_or_else(root, TextSource::resolve)
3320 } else {
3321 root()
3322 }
3323 };
3324 let seed = day_reactive::untrack(&top_title);
3325 bind_seeded(seed, top_title, move |t: &String| {
3326 with_tree(|tr| tr.patch(host, Box::new(NavPatch::Title(t.clone())), false));
3327 });
3328 }
3329
3330 // `nav_back()` and a dayscript back reach the layer first: a pop-only route surface that
3331 // claims the back while the detail is up and falls through outward otherwise. It adds no
3332 // segments, so `current_route()` reads the same across every presentation.
3333 {
3334 let (o_push, o_pop) = (open, open);
3335 register_route_surface(
3336 move |k| {
3337 if k.is_empty() && o_push.peek() {
3338 o_push.set(false);
3339 true
3340 } else {
3341 false
3342 }
3343 },
3344 move |_| {
3345 if o_pop.peek() {
3346 o_pop.set(false);
3347 true
3348 } else {
3349 false
3350 }
3351 },
3352 String::new,
3353 |_| false,
3354 Vec::new,
3355 );
3356 }
3357
3358 // The layer's page can ride a host this scope does not own (the merged shape), so that
3359 // host's teardown will not reach it; pop it, top-down, when this shape is left: a
3360 // section switch, a presentation morph. Guarded for app teardown, like a merged stack.
3361 owner_scope.on_cleanup(move || {
3362 let alive = with_tree(|t| t.node_kind(target.host).is_some());
3363 if alive {
3364 pop();
3365 } else if let Some(l) = layer.borrow_mut().take() {
3366 l.scope.dispose();
3367 }
3368 });
3369}
3370
3371fn build_selector<K: Route, S: Binding<K>>(sel: Nav<S, K>, cx: &mut BuildCx) -> RNode {
3372 use day_spec::props::{
3373 NavMenuPatch, NavMenuProps, NavPageProps, NavPatch, NavPresentation, NavProps, Pane,
3374 };
3375 // Presentation (docs/size-classes.md). Resolved from the window's size class on every change,
3376 // not fixed at build time; `NavPatch::Presentation` re-presents the live host. The window
3377 // root is captured here: the effect below re-runs long after this build, when the ambient
3378 // window would answer the primary one instead of ours.
3379 let icon_progress = sel.icon_progress;
3380 let progress_revision = Signal::new(0u64);
3381 let window = day_core::window_being_built();
3382 let can_split =
3383 with_tree(|t| t.capability(day_spec::Cap::NavSplit)) == day_spec::Support::Native;
3384 // Who decides the presentation (docs/size-classes.md), which is what `Cap::NavRepresent`'s
3385 // three answers distinguish:
3386 // Native: we do, and we patch the host when the class changes.
3387 // Emulated: the toolkit's adaptive container does, and reports back.
3388 // Unsupported: nobody; it is fixed at build time from `Cap::NavSplit` alone, because a
3389 // toolkit that cannot change presentation must not have it decided by something that
3390 // can: a window launched narrow would be stuck stacked.
3391 // Can the toolkit draw the rows as its own chrome (a tab bar, and a rail where it has one)?
3392 // `Emulated` counts: Qt and web-dom compose theirs, and a composed tab bar is still a tab bar
3393 // to the app. Only `Unsupported` sends `Automatic` down the sidebar path.
3394 let can_tabs =
3395 with_tree(|t| t.capability(day_spec::Cap::NavTabs)) != day_spec::Support::Unsupported;
3396 // A separate question from `can_tabs`: every desktop can draw a tab bar (an app may pin one)
3397 // but none of them should grow one as its window narrows. That is a statement about the
3398 // platform's idiom rather than its widget set, so it is the backend's to make.
3399 let adaptive_tabs = with_tree(|t| t.capability(day_spec::Cap::NavTabsAdaptive))
3400 != day_spec::Support::Unsupported;
3401 let represent = with_tree(|t| t.capability(day_spec::Cap::NavRepresent));
3402 let we_drive = represent == day_spec::Support::Native;
3403 let toolkit_drives = represent == day_spec::Support::Emulated;
3404 // The content-list pane (docs/navigation.md). `Native`/`Emulated` = the toolkit places the
3405 // `Pane::List` page itself; `Unsupported` = the wrapper below composes it around each
3406 // destination and the backend never hears of it.
3407 let list_cap = with_tree(|t| t.capability(day_spec::Cap::NavContentList));
3408 // Either way the window's size decides the initial value: a backend that morphs itself still
3409 // starts wherever its container will land, so seeding from the class avoids a first frame in
3410 // the wrong presentation followed by a correcting report.
3411 let size_decides = we_drive || toolkit_drives;
3412 let requested = sel.presentation;
3413 // `Automatic` on a toolkit with no tab bar becomes `Sidebar`, the behavior every backend had
3414 // before adaptive navigation existed. Degrading to the old shape rather than to a hole is what
3415 // lets this land one backend at a time (docs/navigation.md).
3416 let style = match sel.style {
3417 NavStyle::Automatic if !can_tabs => NavStyle::Sidebar,
3418 s => s,
3419 };
3420 // The resolver owns every "can this toolkit do it" question, so `NavProps` always carries a
3421 // presentation the backend can draw.
3422 let resolve = move |class: Option<day_spec::SizeClass>| -> NavPresentation {
3423 // A pin is still a preference (docs/size-classes.md): a toolkit with no split container
3424 // stacks whatever it is asked for, and one with no tab bar cannot wear a pinned `Tabs`.
3425 if let Some(p) = requested {
3426 return match p {
3427 NavPresentation::Split if !can_split => NavPresentation::Stack,
3428 NavPresentation::Tabs | NavPresentation::Rail if !can_tabs => {
3429 if can_split {
3430 NavPresentation::Split
3431 } else {
3432 NavPresentation::Stack
3433 }
3434 }
3435 p => p,
3436 };
3437 }
3438 match style {
3439 // Pinned tabs: the same bar at every size, so the window never enters into it.
3440 NavStyle::Tabs => NavPresentation::Tabs,
3441 // Today's resolution, unchanged: split where there is room, stacked where there isn't.
3442 NavStyle::Sidebar => match class {
3443 _ if !can_split => NavPresentation::Stack,
3444 Some(c) if size_decides && !c.prefers_split() => NavPresentation::Stack,
3445 _ => NavPresentation::Split,
3446 },
3447 // The adaptive ladder: a tab bar at the narrow end, a rail in the middle, a sidebar
3448 // beside the detail when there is room.
3449 //
3450 // Only the bottom rung is platform-specific. Where a tab bar is the idiomatic compact
3451 // answer (the phones, the web) that is what a narrow window gets; on a desktop it
3452 // collapses to a stack instead, which is what `Sidebar` has always done and what a
3453 // Mac or GNOME app does when you drag it narrow. The rail and the split are the same
3454 // everywhere.
3455 NavStyle::Automatic => {
3456 let compact = if adaptive_tabs {
3457 NavPresentation::Tabs
3458 } else {
3459 NavPresentation::Stack
3460 };
3461 if !size_decides {
3462 // Nobody re-presents, so this is decided once and must not be decided by
3463 // something that changes underneath (docs/size-classes.md). Prefer the
3464 // roomier container the toolkit has.
3465 return if can_split {
3466 NavPresentation::Split
3467 } else {
3468 compact
3469 };
3470 }
3471 if !can_split {
3472 return compact;
3473 }
3474 match class.map(|c| c.width) {
3475 Some(day_spec::WidthClass::Compact) => compact,
3476 Some(day_spec::WidthClass::Medium) => NavPresentation::Rail,
3477 _ => NavPresentation::Split,
3478 }
3479 }
3480 }
3481 };
3482 let presentation = resolve(day_core::window_size_class_untracked(window));
3483 // What the host props carry is a different question from what this build currently shows.
3484 // An Emulated toolkit's adaptive container collapses and expands itself, so its host is
3485 // lowered as `Split` ("build the adaptive container") even when the window is compact
3486 // right now. `NavStack` in props is thereby reserved for hosts that are stacks at every size
3487 // (a pinned request, a toolkit that cannot split, the `nav_stack()` piece), which a backend
3488 // may take literally and realize as a plain navigation container: nesting an adaptive
3489 // split container inside a pane is exactly what breaks (docs/size-classes.md).
3490 // An Emulated toolkit's adaptive container collapses and expands itself, so it is lowered the
3491 // roomiest presentation the app's style admits ("build the adaptive container") even when
3492 // the window is compact right now. `NavStack` in props is thereby reserved for hosts that are
3493 // stacks at every size (a pinned request, a toolkit that cannot split, the `nav_stack()` piece),
3494 // which a backend may take literally: nesting an adaptive container inside a pane is exactly
3495 // what breaks (docs/size-classes.md). `adaptive` carries whether it may morph at all.
3496 let adaptive = requested.is_none();
3497 let lowered =
3498 if toolkit_drives && adaptive && can_tabs && adaptive_tabs && style != NavStyle::Sidebar {
3499 // The toolkit has an adaptive container that wears both chromes itself; iOS 18's
3500 // `UITabBarController` in `.tabSidebar` mode is the archetype: one controller that draws
3501 // a tab bar when compact and a sidebar when not, with its own animation and its own
3502 // user-facing toggle. Lowering `Tabs` says "build that", and the toolkit reports what it
3503 // settled on. Its pages are resident at every size, which is why such a host stays in the
3504 // chrome-rows model rather than flipping to push/pop as it widens.
3505 //
3506 // Only for a style that admits a tab bar. `Sidebar` is an app's explicit "this is a
3507 // list beside a detail", and its compact answer has always been the stack: one
3508 // navigation controller the list pushes onto, which is what a phone app with more
3509 // sections than fit a tab bar looks like. Handing that app a tab container instead
3510 // puts a bar under every page and (below iOS 18, where there is no sidebar mode to
3511 // switch to) leaves it there.
3512 NavPresentation::Tabs
3513 } else if toolkit_drives && adaptive && can_split && style != NavStyle::Tabs {
3514 NavPresentation::Split
3515 } else {
3516 presentation
3517 };
3518 // A `.tabSidebar`-style host is a tabs host at every width (its pages are resident whether
3519 // it is drawing a bar or a sidebar), so the resolved presentation has to agree with what the
3520 // backend was told to build. Left disagreeing, day-core would model push/pop while the
3521 // toolkit modeled resident tabs: the first page built would merge into a host that has no
3522 // stack to merge into, and land zero-sized.
3523 let presentation = if lowered == NavPresentation::Tabs && toolkit_drives && adaptive {
3524 NavPresentation::Tabs
3525 } else {
3526 presentation
3527 };
3528 // Whether the backend gets a `Pane::List` page of its own, decided only now that the host's
3529 // shape is known. A chrome-rows host has no column to put one in: UIKit's `.tabSidebar`
3530 // builds a `UITabBarController` and never the split, so a list page handed to it becomes an
3531 // extra tab beside the app's own sections. Where there is no pane, the wrapper below composes
3532 // the list into its destination instead, exactly as it does on a backend that has no pane at
3533 // all (docs/navigation.md).
3534 let native_list = sel.content_list.is_some()
3535 && list_cap != day_spec::Support::Unsupported
3536 && lowered != NavPresentation::Tabs;
3537 // A merged-pane backend (uikit) folds the list into the stack when it collapses; that is
3538 // the only shape where the detail push is gated on `detail_visible`.
3539 let merged_list = native_list && list_cap == day_spec::Support::Emulated;
3540 let split = presentation.is_split();
3541 let presentation_cell = Rc::new(Cell::new(presentation));
3542 // The same fact as a signal, for content the composed list wrapper builds inside the
3543 // pages: a re-present re-runs its `when` where a Cell could only be re-read on rebuild.
3544 let presentation_sig = Signal::new(presentation);
3545 let split_cell = Rc::new(Cell::new(split));
3546 let sidebar_cell: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
3547 let list_cell: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
3548 // ListVisible / ListInStack bookkeeping (both start where the backend starts: the pane
3549 // visible, the stack without the list). `list_shown` is shared with NavLayout so a
3550 // collapsed pane stops narrowing the detail's fallback at once.
3551 let list_shown = Rc::new(Cell::new(true));
3552 let list_in_stack = Rc::new(Cell::new(false));
3553 let selection = sel.selection;
3554 let routed = sel.routed;
3555 let restore = sel.restore;
3556 let title_s = sel.title.initial();
3557 // This host's toolbar items (docs/toolbars.md). They land on the sidebar page's chrome
3558 // below, which is the sidebar column while split and the root list while collapsed, the two
3559 // shapes of "the chrome over the list".
3560 let host_toolbar = sel.toolbar;
3561 // Cloned for the composed gated flow below: its nested host re-homes them in a chrome
3562 // presentation, where the tabs chrome draws none of its own (docs/navigation.md).
3563 let gated_toolbar = host_toolbar.clone();
3564 // Automatic resolves to a sidebar wherever the window is wide enough, so the affordance
3565 // follows what the toolkit can present rather than what the app spelled out: an app that
3566 // never wrote `.style(Sidebar)` still gets the platform's own toggle on a desktop.
3567 let sidebar_toggle =
3568 sel.sidebar_toggle && matches!(sel.style, NavStyle::Sidebar | NavStyle::Automatic);
3569 let detail_title = sel.detail_title;
3570 // Search over this surface (docs/search.md). Lowered to the host's props with its current
3571 // values; the live bindings below keep the field in step through targeted patches, so the
3572 // app writing the query never rebuilds (and refocuses) the field mid-word.
3573 let search_spec = sel.search;
3574 // Lowered once: the bindings below need these same values as their seeds, and `lower` runs
3575 // the app's suggestion closure, which should not run twice per build.
3576 let search_seed = search_spec.as_ref().map(SearchSpec::lower);
3577 let search = search_seed.clone();
3578 let items = Rc::new(SelItems::from_sources(sel.sources, sel.destination));
3579 // The live row set is reactive: `typed` (index → key) and `titles` are shared mutable state
3580 // the derive effect updates; the initial derive is untracked (the effect below owns the
3581 // subscription).
3582 let rows0 = day_reactive::untrack(|| items.derive());
3583 let shown0 = rows0.shown();
3584 let (typed0, titles0, icons0) = (rows0.keys, rows0.titles, rows0.icons);
3585 // Restore the last-selected section (before the detail's initial `show` runs).
3586 restore_selection(&restore, &selection, &typed0);
3587 let typed: Rc<RefCell<Vec<K>>> = Rc::new(RefCell::new(typed0));
3588 let titles: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(titles0));
3589
3590 // The pane's state for the destination that opens first: the restored selection if there is
3591 // one, else the first row, which is what the auto-select below will choose. The backend needs
3592 // it at realize; see `NavProps::list_visible`.
3593 let initial_list_visible = match sel.content_list_pred.as_ref() {
3594 Some(pred) if native_list => {
3595 let restored = selection.peek();
3596 let first = if restored.key().is_empty() {
3597 typed.borrow().first().cloned()
3598 } else {
3599 Some(restored)
3600 };
3601 first.as_ref().is_none_or(|k| pred(k))
3602 }
3603 _ => true,
3604 };
3605 list_shown.set(initial_list_visible);
3606
3607 let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>> = Rc::default();
3608 let host = cx.native(
3609 kinds::NAV,
3610 &NavProps {
3611 documents: sel.documents.clone(),
3612 title: title_s.clone(),
3613 presentation: lowered,
3614 adaptive,
3615 sidebar_toggle,
3616 search,
3617 list_width: native_list.then_some(sel.content_list_width),
3618 list_visible: initial_list_visible,
3619 },
3620 Rc::new(NavLayout {
3621 sizes: sizes.clone(),
3622 presentation: presentation_cell.clone(),
3623 sidebar: sidebar_cell.clone(),
3624 list: list_cell.clone(),
3625 list_width: sel.content_list_width,
3626 list_visible: list_shown.clone(),
3627 }),
3628 Flex {
3629 grow_w: true,
3630 grow_h: true,
3631 ..Default::default()
3632 },
3633 Boundary::Yes,
3634 );
3635
3636 if let Some(event) = sel.document_event.clone() {
3637 cx.on(host, move |ev| event(ev));
3638 }
3639
3640 // The per-host back-owner stack (docs/navigation.md): the detail page pushes its "deselect"
3641 // owner, and a nested stack that merges into this host pushes its page owners on top. The
3642 // context is threaded to nested pieces built under our pages.
3643 let owners: Rc<RefCell<Vec<PopOwner>>> = Rc::default();
3644 let host_cx = NavHostCx {
3645 host,
3646 sizes: sizes.clone(),
3647 owners: owners.clone(),
3648 split: split_cell.clone(),
3649 guards: Rc::default(),
3650 };
3651
3652 // Sidebar / root page. `Pane::Sidebar` is unconditional: it says what this page is in the
3653 // model, not how the host happens to draw it today, which is what lets a re-present re-home
3654 // it between the sidebar pane and the root of the stack (docs/size-classes.md).
3655 let root_page = nav_page(
3656 host,
3657 &NavPageProps {
3658 title: title_s.clone(),
3659 pane: Pane::Sidebar,
3660 },
3661 &sizes,
3662 );
3663 sidebar_cell.set(Some(root_page));
3664
3665 // Search, both directions (docs/search.md). The app's writes patch the live field; the user's
3666 // edits arrive as events against this host and write the app's own signals. Nothing here
3667 // touches the widget directly, which is what lets a later placement change relocate the field
3668 // without disturbing the query.
3669 if let Some((spec, seed)) = search_spec.as_ref().zip(search_seed.as_ref()) {
3670 spec.install(host, day_core::Chrome::Page(root_page), seed);
3671 let query = spec.query;
3672 let scope_sig = spec.scope;
3673 let submit = spec.submit.clone();
3674 cx.on(host, move |ev| match ev {
3675 Event::SearchChanged(text) => query.set(text.clone()),
3676 Event::SearchSubmitted(text) => {
3677 if let Some(f) = &submit {
3678 f(text);
3679 }
3680 }
3681 Event::SearchScopeChanged(i) => {
3682 if let Some(s) = scope_sig {
3683 s.set(*i);
3684 }
3685 }
3686 _ => {}
3687 });
3688 }
3689
3690 // This host's items (docs/toolbars.md): the sidebar column's chrome while split, the
3691 // root list's while collapsed. Registered under the build's scope, so they are withdrawn if
3692 // the whole surface goes.
3693 // The sidebar affordance the host supplies for itself, ahead of the app's own items. Every
3694 // desktop expects one and the toolkit owns the behavior, so an app that used to declare the
3695 // button by hand now declares nothing (docs/toolbars.md).
3696 // The host's chrome is the sidebar column (docs/toolbars.md): a three-pane desktop draws
3697 // these over the sidebar, against the divider they act on.
3698 day_core::with_page_in(
3699 root_page,
3700 None,
3701 day_spec::ToolbarColumn::Sidebar,
3702 window,
3703 || {
3704 if sidebar_toggle
3705 && with_tree(|t| t.capability(day_spec::Cap::Toolbar))
3706 != day_spec::Support::Unsupported
3707 {
3708 crate::contribute(
3709 day_core::Chrome::Page(root_page),
3710 crate::ToolbarSource::Fixed(vec![crate::sidebar_toggle_item(host)]),
3711 );
3712 }
3713 for source in host_toolbar {
3714 crate::contribute(day_core::Chrome::Page(root_page), source);
3715 }
3716 },
3717 );
3718 let menu_holder: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
3719 // Reordering (docs/navigation.md): a toolkit whose own sidebar drags rows
3720 // (`Cap::NavReorder` Native) keeps it and marks the movable rows; one that cannot stands a
3721 // reorderable list in for it (`reorder_sidebar`). Collapsible sections win over both.
3722 let nav_reorder = day_core::capability(day_spec::Cap::NavReorder);
3723 let native_reorder = sel
3724 .reorder_items
3725 .clone()
3726 .filter(|_| nav_reorder == day_spec::Support::Native && sel.collapsed_sections.is_none());
3727 // Which rows drag, re-asked whenever the rows change.
3728 let movable_of = native_reorder.clone();
3729 {
3730 let (mh, ks, s, ts) = (
3731 menu_holder.clone(),
3732 typed.clone(),
3733 selection.clone(),
3734 titles.clone(),
3735 );
3736 let (titles_init, icons_init) = (titles.borrow().clone(), icons0.clone());
3737 // The selection the host is already on, not `None`. `sync_menu` pushes it a moment later
3738 // as `NavMenuPatch::Selected`, and every backend that draws a resting highlight used to
3739 // depend on that patch landing after its view existed, which held on UIKit and did not
3740 // on Android, where the sidebar came up marking nothing at all. Seeding the props means
3741 // the first realization is already right and the patch is only ever a change.
3742 let selected_init = {
3743 let key = selection.peek().key().to_string();
3744 typed
3745 .borrow()
3746 .iter()
3747 .position(|k| k.key() == key)
3748 .filter(|_| !key.is_empty())
3749 };
3750 let (badges_init, sections_init) = (rows0.badges.clone(), rows0.sections.clone());
3751 let (badge_icons_init, badge_tints_init) =
3752 (rows0.badge_icons.clone(), rows0.badge_tints.clone());
3753 let tints_init = rows0.tints.clone();
3754 let menus_init = rows0.menus.clone();
3755 let reorders_natively = native_reorder.is_some();
3756 let rows_script = items.clone();
3757 let movable_init: Vec<bool> = movable_of
3758 .as_ref()
3759 .map(|r| {
3760 typed
3761 .borrow()
3762 .iter()
3763 .map(|k| r.drag(k) != NavDrag::Fixed)
3764 .collect()
3765 })
3766 .unwrap_or_default();
3767 let regroup_init = matches!(movable_of, Some(SidebarDrag::Regroup(_)));
3768 let sorted_init: Vec<bool> = match &movable_of {
3769 Some(r @ SidebarDrag::Regroup(_)) => typed
3770 .borrow()
3771 .iter()
3772 .map(|k| r.drag(k) == NavDrag::Regroup)
3773 .collect(),
3774 _ => Vec::new(),
3775 };
3776 let document_keys = if sel.documents.is_some() {
3777 typed.borrow().iter().map(Route::key).collect()
3778 } else {
3779 Vec::new()
3780 };
3781 let document_event = sel.document_event.clone();
3782 let refresh = sel.refresh;
3783 let list_pred_click = sel.content_list_pred.clone();
3784 let pres_click = presentation_cell.clone();
3785 let detail_visible_click = sel.detail_visible;
3786 let menu_piece = if let Some(collapsed) = sel.collapsed_sections {
3787 section_sidebar(
3788 items.clone(),
3789 selection.clone(),
3790 collapsed,
3791 sel.on_section_expansion,
3792 icon_progress.clone(),
3793 )
3794 } else if let Some(reorder) = sel
3795 .reorder_items
3796 .filter(|_| nav_reorder == day_spec::Support::Emulated)
3797 {
3798 reorder_sidebar(
3799 items.clone(),
3800 selection.clone(),
3801 reorder,
3802 icon_progress.clone(),
3803 )
3804 } else {
3805 piece_fn(move |mcx| {
3806 let node = mcx.native(
3807 kinds::NAV_MENU,
3808 &NavMenuProps {
3809 document_keys,
3810 items: titles_init,
3811 icons: icons_init,
3812 badges: badges_init,
3813 badge_icons: badge_icons_init,
3814 badge_tints: badge_tints_init,
3815 sections: sections_init,
3816 tints: tints_init,
3817 menus: menus_init,
3818 movable: movable_init,
3819 regroup: regroup_init,
3820 sorted: sorted_init,
3821 selected: selected_init,
3822 },
3823 Rc::new(LeafLayout),
3824 Flex {
3825 grow_w: true,
3826 grow_h: true,
3827 ..Default::default()
3828 },
3829 Boundary::No,
3830 );
3831 mh.set(Some(node));
3832 // The dayscript `reorder` step drives this sidebar in the rows the stand-in list
3833 // has, section headers counted, so one script reorders both.
3834 match native_reorder.clone() {
3835 Some(SidebarDrag::Reorder(reorder)) => {
3836 let rows = rows_script.clone();
3837 day_core::set_scripted_reorder(node, move |from, to| {
3838 let NavRows { keys, sections, .. } =
3839 day_reactive::untrack(|| rows.derive());
3840 script_nav_reorder(&keys, §ions, &reorder, from, to)
3841 });
3842 }
3843 Some(SidebarDrag::Regroup(regroup)) => {
3844 let rows = rows_script.clone();
3845 day_core::set_scripted_reorder(node, move |from, to| {
3846 let rows =
3847 RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
3848 if let Some(drop) = rows.display_drop(®roup, from, to)? {
3849 (regroup.dropped)(drop);
3850 }
3851 Ok(to)
3852 });
3853 }
3854 None => {}
3855 }
3856 if let Some((refreshing, action)) = refresh {
3857 let refreshing = Rc::new(refreshing);
3858 let state = refreshing.clone();
3859 bind(
3860 move || state.get(),
3861 move |busy| {
3862 with_tree(|t| {
3863 t.patch(
3864 node,
3865 Box::new(day_spec::props::RefreshPatch { refreshing: *busy }),
3866 false,
3867 )
3868 });
3869 },
3870 );
3871 mcx.on(node, move |event| {
3872 if matches!(event, Event::RefreshRequested) {
3873 if !day_reactive::untrack(|| refreshing.get()) {
3874 action();
3875 }
3876 // Re-apply even when the state did not change: the user may have
3877 // pulled an empty/offline library and the app declined the work.
3878 let busy = day_reactive::untrack(|| refreshing.get());
3879 with_tree(|t| {
3880 t.patch(
3881 node,
3882 Box::new(day_spec::props::RefreshPatch { refreshing: busy }),
3883 false,
3884 )
3885 });
3886 }
3887 });
3888 }
3889 if let Some(event) = document_event {
3890 mcx.on(node, move |ev| event(ev));
3891 }
3892 // A row the sidebar itself dragged: `from` moved to where `to` stood, both
3893 // item indices into the keys as they were before the move.
3894 // A drop a regrouping sidebar committed, checked against the app's rules here,
3895 // whatever the toolkit offered.
3896 if let Some(SidebarDrag::Regroup(regroup)) = native_reorder.clone() {
3897 let rows = rows_script.clone();
3898 mcx.on(node, move |ev| {
3899 if let Event::NavRegroup {
3900 from,
3901 section,
3902 before,
3903 } = *ev
3904 {
3905 let rows =
3906 RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
3907 if let Ok(Some(drop)) = rows.drop_at(®roup, from, section, before) {
3908 (regroup.dropped)(drop);
3909 }
3910 }
3911 });
3912 }
3913 if let Some(SidebarDrag::Reorder(reorder)) = native_reorder {
3914 let keys = ks.clone();
3915 mcx.on(node, move |ev| {
3916 if let Event::ListReorder { from, to } = *ev {
3917 let pair = {
3918 let keys = keys.borrow();
3919 keys.get(from).cloned().zip(keys.get(to).cloned())
3920 };
3921 if let Some((moved, target)) = pair
3922 && (reorder.eligible)(&moved)
3923 && (reorder.eligible)(&target)
3924 {
3925 (reorder.moved)(moved, target);
3926 }
3927 }
3928 });
3929 }
3930 mcx.on(node, move |ev| {
3931 if let Event::SelectionChanged(i) = ev
3932 && let Some(k) = ks.borrow().get(*i as usize)
3933 {
3934 // Announce the navigation from its source (§14.6) with the row's own title:
3935 // the sidebar changes the route only after a remount, so a route observer would
3936 // otherwise miss the move and have no label for it. Index the live titles.
3937 let label = ts.borrow().get(*i as usize).cloned();
3938 day_core::note_navigation(&k.key(), label.as_deref());
3939 s.write(k.clone());
3940 // Activation is not just selection. UIKit can leave the supplementary
3941 // column offstage after its initial collapse, or after native back,
3942 // even though this route is already selected. Re-present the list on
3943 // EVERY tap, including a tap on the highlighted row. Do not rebuild it.
3944 if merged_list
3945 && pres_click.get() == NavPresentation::Stack
3946 && detail_visible_click.is_some_and(|visible| !visible.peek())
3947 && list_pred_click.as_ref().is_none_or(|p| p(k))
3948 {
3949 with_tree(|t| {
3950 t.patch(host, Box::new(NavPatch::ListInStack(true)), false)
3951 });
3952 }
3953 }
3954 });
3955 node
3956 })
3957 // A reorderable sidebar answers to the stand-in list's name, so a script's
3958 // `reorder` steps address the sidebar whichever one the toolkit shows.
3959 .id(if reorders_natively {
3960 day_core::id!(nav_reorder_list)
3961 } else {
3962 day_core::id!(nav_menu)
3963 })
3964 .any()
3965 };
3966 let content: AnyPiece = match sel.header {
3967 Some(h) => column((h(), menu_piece))
3968 .spacing(4.0)
3969 .align(HAlign::Leading)
3970 .any(),
3971 None => column((menu_piece,))
3972 .spacing(4.0)
3973 .align(HAlign::Leading)
3974 .any(),
3975 };
3976 let content = match sel.footer {
3977 Some(footer) => column((content.grow(Dimension::Both), footer()))
3978 .grow(Dimension::Both)
3979 .any(),
3980 None => content,
3981 };
3982 with_nav_host(Some(host_cx.clone()), || {
3983 let mut pcx = BuildCx::new(root_page);
3984 let _ = content.build(&mut pcx);
3985 });
3986 }
3987
3988 // The content-list page (docs/navigation.md): built once, resident for the host's life.
3989 // Its content follows the app's signals, so a selection change re-scopes it without a
3990 // rebuild. `with_nav_host(None)`: the pane is not a merge target, so a stack inside the
3991 // list keeps its own container rather than pushing onto this host.
3992 let list_build = sel.content_list.clone();
3993 let list_pred = sel.content_list_pred.clone();
3994 let detail_visible = sel.detail_visible;
3995 // Whether the content-list pane belongs to this destination (`content_list_for`), applied
3996 // wherever the shown destination can change. It lives here, shared, because three paths
3997 // reach it: a fresh `show`, a `show` that finds its page already resident (a chrome
3998 // presentation has built them all), and a presentation change that rebuilds the shape
3999 // around an unchanged selection. Missing any one of them strands the pane: collapsed
4000 // because some other destination was the last to speak, with nothing left to reopen it.
4001 // Set when the content-list page is built below; `apply_list_visible` writes through it so
4002 // the pane's chrome follows its visibility (docs/toolbars.md).
4003 let list_visible_sig: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
4004 let apply_list_visible: Rc<dyn Fn(&K)> = {
4005 let (shown, pred) = (list_shown.clone(), list_pred.clone());
4006 let mirror = list_visible_sig.clone();
4007 Rc::new(move |key: &K| {
4008 if !native_list {
4009 return;
4010 }
4011 let want = pred.as_ref().is_none_or(|p| p(key));
4012 if want != shown.get() {
4013 shown.set(want);
4014 // The chrome mirror, so the pane's own commands leave the bar with the pane.
4015 if let Some(sig) = mirror.get() {
4016 sig.set(want);
4017 }
4018 with_tree(|t| t.patch(host, Box::new(NavPatch::ListVisible(want)), false));
4019 }
4020 })
4021 };
4022 if native_list && let Some(build_list) = list_build.clone() {
4023 let page = nav_page(
4024 host,
4025 &NavPageProps {
4026 title: title_s.clone(),
4027 pane: Pane::List,
4028 },
4029 &sizes,
4030 );
4031 list_cell.set(Some(page));
4032 // The pane collapses for a destination that spans the whole detail area
4033 // (`content_list_for`), and a collapsed pane's commands must leave the bar with it
4034 // (docs/toolbars.md); otherwise a full-page section shows the list's Add and Filter.
4035 // Reactive, so a collapse re-composes the bar: the Cell above is what `NavLayout` reads
4036 // during layout, and this mirrors it for the chrome.
4037 let visible = Signal::new(initial_list_visible);
4038 list_visible_sig.set(Some(visible));
4039 // Two ways this pane stops being what the user is looking at: the destination collapses
4040 // it (`content_list_for`), or, on a shape that shows one pane at a time, a detail is
4041 // pushed over it. Its Add and Filter act on a list that is then behind the editor, so
4042 // they leave the bar with it (docs/toolbars.md). Side by side, both panes are up and
4043 // both keep their commands.
4044 let (dv, pres_sig) = (detail_visible, presentation_sig);
4045 // `try_get`: a gate is asked at merge time, which can be a window's teardown; a
4046 // disposed signal answers "not showing" rather than panicking (docs/toolbars.md).
4047 let gate: Rc<dyn Fn() -> bool> = Rc::new(move || {
4048 visible.try_get().unwrap_or(false)
4049 && (pres_sig.try_get().is_some_and(|p| p.is_split())
4050 || dv.is_none_or(|d| !d.try_get().unwrap_or(false)))
4051 });
4052 with_nav_host(None, || {
4053 day_core::with_page_gated(page, Some(gate), day_spec::ToolbarColumn::List, || {
4054 let mut pcx = BuildCx::new(page);
4055 let _ = build_list().build(&mut pcx);
4056 });
4057 });
4058 }
4059 // The composed content list (`Cap::NavContentList` Unsupported): every list-backed
4060 // destination page carries the pane itself, beside the content while split and as the
4061 // root of a two-layer push flow while compact (the gated detail above). The
4062 // presentation is read through the signal, so a live morph re-arranges the page without
4063 // the host's involvement.
4064 let compose: Option<DestFn<K>> = if let (Some(list), true) = (list_build.clone(), !native_list)
4065 {
4066 let pred = list_pred.clone();
4067 let width = sel.content_list_width;
4068 let dv = detail_visible;
4069 let items_c = items.clone();
4070 // The live rows, for a data-driven key's title: only a static item carries a
4071 // `TextSource` of its own, and without these a row from `.items` titled its pushed page
4072 // with its raw key ("feed:5756…") instead of the name the row shows.
4073 let (typed_c, titles_c) = (typed.clone(), titles.clone());
4074 let pres = presentation_sig;
4075 let win = window;
4076 let host_cx_g = host_cx.clone();
4077 let detail_title_g = detail_title.clone();
4078 Some(Rc::new(move |key: &K| {
4079 if pred.as_ref().is_some_and(|p| !p(key)) {
4080 return items_c.build_page(key);
4081 }
4082 let (l1, l2) = (list.clone(), list.clone());
4083 let (i1, i2) = (items_c.clone(), items_c.clone());
4084 let (k1, k2) = (key.clone(), key.clone());
4085 let (hc, dt) = (host_cx_g.clone(), detail_title_g.clone());
4086 let (tk, tt) = (typed_c.clone(), titles_c.clone());
4087 let ba = gated_toolbar.clone();
4088 // Each arm rebuilds in this destination's page: a morph re-runs the `when` long after
4089 // the page was built, and an arm built outside it registers the list's commands
4090 // without the page's gate (a narrowed tablet then showed Items' Add on Settings).
4091 // Captured when the page builds: the destination is constructed before its page frame
4092 // is entered.
4093 let page: Rc<RefCell<Option<PageContext>>> = Rc::default();
4094 let at_build = page.clone();
4095 let arms = when(
4096 move || {
4097 let p = pres.get();
4098 // Side by side only where there is room for two columns.
4099 // `rows_are_chrome()` alone is not that question: under the adaptive
4100 // ladder a tab bar is the compact rung, and pairing a 320pt list with an
4101 // editor across a phone leaves neither usable, which is what a scaffold
4102 // that wanted tabs on a phone got. A pinned tab bar on a wide window
4103 // still earns the pair, so the width is asked rather than the style.
4104 p.is_split()
4105 || (p.rows_are_chrome()
4106 && day_core::window_size_class(win).is_some_and(|c| c.prefers_split()))
4107 },
4108 {
4109 let page = page.clone();
4110 move || {
4111 let (l, i, k) = (l1.clone(), i1.clone(), k1.clone());
4112 PageContext::enter(
4113 &page,
4114 row((
4115 l().width(width).grow(Dimension::Height),
4116 i.build_page(&k).grow(Dimension::Both),
4117 ))
4118 .grow(Dimension::Both),
4119 )
4120 }
4121 },
4122 )
4123 .otherwise(move || {
4124 let (l, i, k) = (l2.clone(), i2.clone(), k2.clone());
4125 PageContext::enter(
4126 &page,
4127 match dv {
4128 // The gated two-layer flow (docs/navigation.md): a nested navigation
4129 // host in a chrome presentation, a push onto the enclosing host in a
4130 // stacked one; either way a navigation bar, a title, and a native
4131 // back, where an in-place swap had none.
4132 Some(d) => {
4133 let retitle = i.static_title(&k.key());
4134 let title = retitle
4135 .as_ref()
4136 .map(TextSource::initial)
4137 .or_else(|| {
4138 let at = tk.borrow().iter().position(|x| x.key() == k.key())?;
4139 tt.borrow().get(at).cloned()
4140 })
4141 .unwrap_or_else(|| k.title());
4142 gated_detail_piece(
4143 GatedDetail {
4144 open: d,
4145 list: l,
4146 items: i,
4147 key: k,
4148 title,
4149 retitle,
4150 detail_title: dt.clone(),
4151 host_cx: hc.clone(),
4152 toolbar: ba.clone(),
4153 },
4154 pres,
4155 win,
4156 )
4157 }
4158 None => i.build_page(&k),
4159 },
4160 )
4161 });
4162 AnyPiece::new(piece_fn(move |cx| {
4163 at_build.replace(Some(PageContext::current()));
4164 arms.build(cx)
4165 }))
4166 }))
4167 } else {
4168 None
4169 };
4170
4171 let sync_menu = {
4172 let mh = menu_holder.clone();
4173 move |idx: Option<usize>| {
4174 if let Some(m) = mh.get() {
4175 with_tree(|t| t.patch(m, Box::new(NavMenuPatch::Selected(idx)), false));
4176 }
4177 // And onto the host, which is the node `.id()` names: a script asserting on a
4178 // nav addresses the nav, not the row list nested inside it. Every path that
4179 // changes the selection lands here, so this is the one place that has to record it.
4180 with_tree(|t| t.set_probe_selected(host, idx));
4181 }
4182 };
4183
4184 // Detail pages, and how long they live.
4185 //
4186 // A presentation whose rows are the chrome (a tab bar, a rail) keeps every visited page
4187 // resident: switching tabs is `NavPatch::Select`, nothing is torn down, and each tab keeps
4188 // its scroll offset, its focused field, and its animations, which is what every native tab
4189 // container does. A split or stacked presentation keeps only the shown page and switches by
4190 // pop-then-push, which is what it did before adaptive navigation existed.
4191 //
4192 // Residency follows the presentation rather than the host. Making every nav page resident
4193 // would keep effects running for pages nobody is looking at and change the disposal
4194 // contract the docs make ("leaving the piece's branch disposes"); making none resident
4195 // would rebuild a tab's content on every tap. Splitting it this way means a morph only
4196 // ever disposes pages that are not on screen, or lazily builds ones that were not built
4197 // yet; the visible page is never rebuilt, which is the invariant a morph has to keep.
4198 let resident: Rc<RefCell<Vec<ResidentPage>>> = Rc::default();
4199 let current: Rc<RefCell<Option<String>>> = Rc::default();
4200 let nav_scope = Scope::current();
4201 // Shared: Both the selection bind and the row-derive effect drive the detail (see the
4202 // derive effect for why the selection bind alone is not enough).
4203 let show = std::rc::Rc::new({
4204 let (items, resident, current, sizes, typed_s, titles_s) = (
4205 items.clone(),
4206 resident.clone(),
4207 current.clone(),
4208 sizes.clone(),
4209 typed.clone(),
4210 titles.clone(),
4211 );
4212 let (sync_menu, owners, host_cx, selection, pres) = (
4213 sync_menu.clone(),
4214 owners.clone(),
4215 host_cx.clone(),
4216 selection.clone(),
4217 presentation_cell.clone(),
4218 );
4219 let (list_pred_s, list_in_stack_s) = (list_pred.clone(), list_in_stack.clone());
4220 let apply_list_visible_s = apply_list_visible.clone();
4221 let compose_s = compose.clone();
4222 let detail_title_s = detail_title.clone();
4223 move |key: &str| {
4224 if current.borrow().as_deref() == Some(key) {
4225 return;
4226 }
4227 let chrome = pres.get().rows_are_chrome();
4228 // The list interposes between the sidebar root and the detail exactly while a
4229 // merged-pane backend is stacked and the app gates the detail
4230 // (docs/navigation.md). Split-family presentations show the detail beside the
4231 // list, empty state and all.
4232 let gated =
4233 merged_list && pres.get() == NavPresentation::Stack && detail_visible.is_some();
4234 if !chrome {
4235 // Stacked or split: the outgoing page goes away. Dispose its scope first: a
4236 // merged inner stack's cleanup pops its pages (which sit on top natively) before
4237 // we pop the detail itself, so the native pop order stays top-down (iOS pops the
4238 // topmost VC; Android's inclusive pop unwinds everything above an entry).
4239 if let Some(p) = resident.borrow_mut().pop() {
4240 p.scope.dispose();
4241 with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4242 owners.borrow_mut().pop();
4243 sizes.borrow_mut().remove(&p.node);
4244 with_tree(|t| {
4245 t.remove_subtree(p.node);
4246 t.mark_layout_dirty();
4247 t.layout_if_needed();
4248 });
4249 }
4250 }
4251 *current.borrow_mut() = None;
4252 if key.is_empty() {
4253 // Deselected: the list layer (if interposed) leaves the stack with the detail.
4254 if list_in_stack_s.get() {
4255 list_in_stack_s.set(false);
4256 with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
4257 owners.borrow_mut().pop();
4258 }
4259 sync_menu(None);
4260 return;
4261 }
4262 let idx = typed_s.borrow().iter().position(|k| k.key() == key);
4263 let Some(idx) = idx else {
4264 sync_menu(None);
4265 return;
4266 };
4267 let typed_key_now = typed_s.borrow()[idx].clone();
4268 // The pane's visibility is settled for every destination change, including the
4269 // resident case below: a chrome presentation builds every destination, so the
4270 // last one built would otherwise be the one that had the final word.
4271 apply_list_visible_s(&typed_key_now);
4272 // Already built and still alive: the resident case. Nothing to build, nothing to
4273 // push: tell the host which of its pages to show and we are done.
4274 if let Some(i) = resident.borrow().iter().position(|p| p.key == key) {
4275 with_tree(|t| {
4276 t.patch(host, Box::new(NavPatch::Select(i)), false);
4277 t.mark_layout_dirty();
4278 t.layout_if_needed();
4279 });
4280 *current.borrow_mut() = Some(key.to_string());
4281 sync_menu(Some(idx));
4282 return;
4283 }
4284 let typed_key = typed_key_now;
4285 let title_now = titles_s.borrow()[idx].clone();
4286 // Per-destination pane visibility (`content_list_for`): a full-width destination
4287 // collapses the pane, a list-backed one brings it back. `interposed` = this
4288 // destination puts the list between the sidebar root and its detail (a stacked
4289 // merged-pane backend, docs/navigation.md).
4290 let want = native_list && list_pred_s.as_ref().is_none_or(|p| p(&typed_key));
4291 let interposed = gated && want;
4292 if native_list {
4293 if interposed && !list_in_stack_s.get() {
4294 // Interpose the list above the sidebar root, with its own back owner
4295 // (back from the list = deselect).
4296 list_in_stack_s.set(true);
4297 with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
4298 let s = selection.clone();
4299 owners.borrow_mut().push(Rc::new(move |_already_popped| {
4300 if let Some(root) = K::from_key("") {
4301 s.write(root);
4302 }
4303 }) as PopOwner);
4304 } else if gated && !want && list_in_stack_s.get() {
4305 // A full-width destination while stacked: the list leaves the stack so its
4306 // page sits directly on the sidebar root and back deselects.
4307 list_in_stack_s.set(false);
4308 with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
4309 owners.borrow_mut().pop();
4310 }
4311 // The detail waits for `detail_visible`: the list is the top of the stack
4312 // until the app opens a row. The selection is recorded as current; the
4313 // `detail_visible` bind re-enters here to perform the deferred push.
4314 if interposed && !detail_visible.expect("gated implies Some").peek() {
4315 // A selected list can still be offstage after UIKit's initial collapse.
4316 // Route changes must present it too, without adding another back owner.
4317 with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
4318 *current.borrow_mut() = Some(key.to_string());
4319 sync_menu(Some(idx));
4320 return;
4321 }
4322 }
4323 // A static item retitles on locale change (its TextSource); a data-driven key uses
4324 // the resolved snapshot (its title tracks the items signal, not the locale). A
4325 // list-backed destination on a host that places the pane natively is the detail
4326 // layer, so the app's `detail_title` names it where one is set: the layer shows
4327 // an item, not the section (docs/navigation.md).
4328 let (page_title, retitle) = match &detail_title_s {
4329 Some(dt) if want => (dt.initial(), Some(dt.clone())),
4330 _ => (title_now.clone(), items.static_title(key)),
4331 };
4332 let page = nav_page(
4333 host,
4334 &NavPageProps {
4335 title: page_title.clone(),
4336 pane: Pane::Detail,
4337 },
4338 &sizes,
4339 );
4340 if !chrome {
4341 // The detail page's back action: with the list interposed, back from the
4342 // detail returns to the list (`detail_visible` := false); classically it
4343 // deselects (returns to the sidebar rows). Pushed before the content builds,
4344 // so a merged inner stack's page owners stack on top of it. A chrome
4345 // presentation has no back stack to own; a tab bar never pops.
4346 let owner: PopOwner = if interposed && let Some(dv) = detail_visible {
4347 Rc::new(move |_already_popped| {
4348 dv.set(false);
4349 })
4350 } else {
4351 let s = selection.clone();
4352 Rc::new(move |_already_popped| {
4353 if let Some(root) = K::from_key("") {
4354 s.write(root);
4355 }
4356 })
4357 };
4358 owners.borrow_mut().push(owner);
4359 // Present the page before its content builds. Anything the content pushes
4360 // onto this same host while building (a composed gated detail whose signal
4361 // is already true, a merged stack's restored path) must land above this
4362 // page, and a backend that presents pages in patch order (Android presents
4363 // the most recently added) would otherwise show them inverted. `immersive_of`
4364 // runs out here for the usual reason: it can run app code, which must not
4365 // happen inside `with_tree`.
4366 let immersive = items.immersive_of(&typed_key.key());
4367 with_tree(|t| {
4368 t.patch(
4369 host,
4370 Box::new(NavPatch::Pushed {
4371 title: page_title.clone(),
4372 immersive,
4373 }),
4374 false,
4375 );
4376 });
4377 }
4378 let scope = nav_scope.enter(Scope::child);
4379 scope.enter(|| {
4380 // Inside the page's scope; see the pushed-detail site above.
4381 let content = match &compose_s {
4382 Some(c) => c(&typed_key),
4383 None => items.build_page(&typed_key),
4384 };
4385 // A resident page is a merge barrier: a `nav_stack` inside a tab keeps its own
4386 // native container rather than pushing onto the enclosing host, because the
4387 // enclosing host is not a stack (docs/navigation.md).
4388 let inner = if chrome { None } else { Some(host_cx.clone()) };
4389 // The page's own commands ride the window's bar only while it is the page
4390 // showing (docs/toolbars.md): a resident tab that is not in front, and a
4391 // destination the selection has moved off, both leave the bar.
4392 let sel_gate = Some(destination_gate(selection.clone(), key.to_string()));
4393 let build = || {
4394 with_nav_host(inner, || {
4395 day_core::with_page_in(
4396 page,
4397 sel_gate.clone(),
4398 day_spec::ToolbarColumn::Detail,
4399 window,
4400 || {
4401 let mut c = BuildCx::new(page);
4402 let _ = content.build(&mut c);
4403 },
4404 );
4405 });
4406 };
4407 if chrome {
4408 // Resident, so anything this page builds outlives the switch away from it and
4409 // has to say whether it is selected. Read the selection itself: a route link
4410 // can switch tabs and enter a nested route in one batched event, before the
4411 // presentation effect updates `current`.
4412 with_page_active(destination_gate(selection.clone(), key.to_string()), build);
4413 } else {
4414 build();
4415 }
4416 });
4417 resident.borrow_mut().push(ResidentPage {
4418 key: key.to_string(),
4419 scope,
4420 node: page,
4421 });
4422 let at = resident.borrow().len() - 1;
4423 // A stacked page was presented above, before its content; the resident case
4424 // selects after the build, because the page must exist to be shown.
4425 if chrome {
4426 with_tree(|t| t.patch(host, Box::new(NavPatch::Select(at)), false));
4427 }
4428 with_tree(|t| {
4429 t.mark_layout_dirty();
4430 t.layout_if_needed();
4431 });
4432 // Live retitle for a static item: its title source re-resolves on locale change and
4433 // the host's native bar follows via `NavPatch::Title`. Scope-owned, dies with the page.
4434 if let Some(rt) = retitle {
4435 scope.enter(|| {
4436 rt.bind_to(host, |t| Box::new(NavPatch::Title(t)), false);
4437 });
4438 }
4439 *current.borrow_mut() = Some(key.to_string());
4440 sync_menu(Some(idx));
4441 }
4442 });
4443
4444 // Neither a split nor a tab bar can draw "nothing selected": a split has no way to fill the
4445 // detail pane, and a tab bar always has one tab active. Both default to the first item. Only
4446 // a stack has an empty state, and there it is wanted: the collapsed list the user has not
4447 // chosen from yet. A host with a native content list joins the default-selection rule at
4448 // every presentation: the pane needs a selection to scope itself to, and a collapsed
4449 // merged-pane host opens on the list rather than on bare rows.
4450 if (split || presentation.rows_are_chrome() || native_list)
4451 && selection.peek().key().is_empty()
4452 && let Some(k) = typed.borrow().first().cloned()
4453 {
4454 selection.write(k);
4455 }
4456 // Build every destination, then re-select the current one.
4457 //
4458 // A tab bar needs an item per destination up front: `UITabBarController` and Material's
4459 // navigation bar both build their chrome from the full set, so a page nobody has visited yet
4460 // is a tab that is not there. Lazy building is right for a split or a stack, where only
4461 // the shown page is drawn; where the rows are the chrome, the rows have to be complete.
4462 //
4463 // This runs before the selection bind below, and that order is the contract with the
4464 // chrome backends: `NavPatch::Select` names a page by attach order, while the chrome draws
4465 // the rows, so a suite can only pair the two when page i is row i. Letting the bind build the
4466 // selected destination first breaks that: restoring a saved section (`.restore`, which
4467 // android-material installs for every app as its instance-state contract) rebuilds with a
4468 // non-first selection, whose page then attaches at 0 and highlights row 0.
4469 let build_all = {
4470 let (show, typed_a, sel_a) = (show.clone(), typed.clone(), selection.clone());
4471 Rc::new(move || {
4472 let keys: Vec<String> = typed_a.borrow().iter().map(|k| k.key()).collect();
4473 for k in keys {
4474 show(&k);
4475 }
4476 show(&sel_a.peek().key());
4477 })
4478 };
4479 if presentation.rows_are_chrome() {
4480 build_all();
4481 }
4482 {
4483 let (s, show) = (selection.clone(), show.clone());
4484 bind(move || s.read().key(), move |key: &String| show(key));
4485 }
4486
4487 // `detail_visible`, both directions (docs/navigation.md). Only the stacked merged-pane
4488 // shape reacts here: `true` performs the deferred detail push for the current selection,
4489 // `false` pops back to the interposed list. Split-family presentations ignore the signal:
4490 // their detail pane is always on screen (native back never runs a detail owner there).
4491 if let Some(dv) = detail_visible {
4492 let (show_dv, current_dv, resident_dv, sizes_dv, owners_dv) = (
4493 show.clone(),
4494 current.clone(),
4495 resident.clone(),
4496 sizes.clone(),
4497 owners.clone(),
4498 );
4499 let (pres_dv, list_in_stack_dv) = (presentation_cell.clone(), list_in_stack.clone());
4500 bind(
4501 move || dv.get(),
4502 move |v: &bool| {
4503 let gated_now = merged_list
4504 && pres_dv.get() == NavPresentation::Stack
4505 && list_in_stack_dv.get();
4506 if !gated_now {
4507 return;
4508 }
4509 if *v {
4510 let key = current_dv.borrow().clone();
4511 if resident_dv.borrow().is_empty()
4512 && let Some(k) = key
4513 {
4514 // Deferred push: `show` re-runs for the recorded selection, sees the
4515 // signal true, and performs the build it withheld.
4516 *current_dv.borrow_mut() = None;
4517 show_dv(&k);
4518 }
4519 } else if let Some(p) = resident_dv.borrow_mut().pop() {
4520 p.scope.dispose();
4521 with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4522 owners_dv.borrow_mut().pop();
4523 sizes_dv.borrow_mut().remove(&p.node);
4524 with_tree(|t| {
4525 t.remove_subtree(p.node);
4526 t.mark_layout_dirty();
4527 t.layout_if_needed();
4528 });
4529 }
4530 },
4531 );
4532 }
4533
4534 // A detail open beside its list closes before the section is left (docs/navigation.md). Where
4535 // the list is composed into the destination's page, the platform's back would pop that whole
4536 // page, list and detail together, so while a detail is open side by side this host routes the
4537 // native back through Day (`NavHostCx::vote_guard`) and the back handler below closes the
4538 // detail instead. A native pane is a column of its own, which no native back pops.
4539 let beside: Rc<Cell<bool>> = Rc::default();
4540 if let Some(dv) = detail_visible
4541 && list_build.is_some()
4542 && !native_list
4543 {
4544 let (hc, s, pred, beside) = (
4545 host_cx.clone(),
4546 selection.clone(),
4547 list_pred.clone(),
4548 beside.clone(),
4549 );
4550 bind(
4551 move || {
4552 let k = s.read();
4553 dv.get()
4554 && presentation_sig.get().is_split()
4555 && !k.key().is_empty()
4556 && pred.as_ref().is_none_or(|p| p(&k))
4557 },
4558 move |want: &bool| {
4559 if *want != beside.get() {
4560 beside.set(*want);
4561 hc.vote_guard(*want);
4562 }
4563 },
4564 );
4565 }
4566
4567 // What a presentation change means for the model, whoever caused it. Widening with nothing
4568 // selected would leave the detail pane empty, the one state a split presentation has no way
4569 // to draw, so adopt the same first-item rule the build uses. Narrowing keeps the selection
4570 // instead: the detail becomes the top of the stack, which is where the user already was.
4571 let reconcile = {
4572 let (pc, sel_r, typed_r, split_r) = (
4573 presentation_cell.clone(),
4574 selection.clone(),
4575 typed.clone(),
4576 split_cell.clone(),
4577 );
4578 let build_all_r = build_all.clone();
4579 let (resident_r, current_r, sizes_r, owners_r) = (
4580 resident.clone(),
4581 current.clone(),
4582 sizes.clone(),
4583 owners.clone(),
4584 );
4585 let (list_pred_r, list_in_stack_r, show_r) =
4586 (list_pred.clone(), list_in_stack.clone(), show.clone());
4587 let apply_list_visible_r = apply_list_visible.clone();
4588 Rc::new(move |next: NavPresentation| {
4589 let was_chrome = pc.get().rows_are_chrome();
4590 pc.set(next);
4591 split_r.set(next.is_split());
4592 presentation_sig.set(next);
4593 // Leaving a chrome presentation: the resident pages nobody can see any more go away,
4594 // because a split or stacked host draws exactly one detail page. The shown page is
4595 // kept (rebuilding what the user is looking at is the one thing a morph must never
4596 // do) and is left as the sole entry, so it reads as the top of the new stack.
4597 //
4598 // Entering a chrome presentation needs no counterpart: the shown page is already
4599 // resident, and the others build lazily when they are first selected.
4600 if was_chrome && !next.rows_are_chrome() {
4601 let shown = current_r.borrow().clone();
4602 let gone: Vec<ResidentPage> = {
4603 let mut r = resident_r.borrow_mut();
4604 let (keep, drop): (Vec<_>, Vec<_>) =
4605 r.drain(..).partition(|p| Some(&p.key) == shown.as_ref());
4606 *r = keep;
4607 drop
4608 };
4609 for p in gone {
4610 p.scope.dispose();
4611 sizes_r.borrow_mut().remove(&p.node);
4612 with_tree(|t| t.remove_subtree(p.node));
4613 }
4614 // The kept page now owns the one back affordance the stack presentation offers.
4615 owners_r.borrow_mut().clear();
4616 if let Some(k) = shown {
4617 let s = sel_r.clone();
4618 let owner: PopOwner = Rc::new(move |_already_popped| {
4619 if let Some(root) = K::from_key("") {
4620 s.write(root);
4621 }
4622 });
4623 owners_r.borrow_mut().push(owner);
4624 let _ = k;
4625 }
4626 with_tree(|t| {
4627 t.mark_layout_dirty();
4628 t.layout_if_needed();
4629 });
4630 }
4631 if !was_chrome && next.rows_are_chrome() {
4632 // Entering a chrome presentation: the rows become the chrome, so every
4633 // destination needs its page for the bar to be complete.
4634 build_all_r();
4635 }
4636 if (next.is_split() || next.rows_are_chrome() || native_list)
4637 && sel_r.peek().key().is_empty()
4638 && let Some(k) = typed_r.borrow().first().cloned()
4639 {
4640 sel_r.write(k);
4641 }
4642 // Content-list settlement (docs/navigation.md). The pane's own visibility comes
4643 // first and applies to every backend that places the pane itself: entering a chrome
4644 // presentation builds every destination, and a destination without a list collapses
4645 // the pane on its way past, so the shape that comes next has to state the selected
4646 // destination's answer again.
4647 if native_list
4648 && let Some(k) = typed_r
4649 .borrow()
4650 .iter()
4651 .find(|x| Some(&x.key()) == current_r.borrow().as_ref())
4652 .cloned()
4653 {
4654 apply_list_visible_r(&k);
4655 }
4656 // Narrowing into the gated stack interposes the list for the current selection and
4657 // retracts a detail the app is not showing; widening back restores the always-on
4658 // detail beside the pane. The owner stack is rebuilt for the new shape, because the
4659 // old owners named the old one.
4660 if merged_list && let Some(dv) = detail_visible {
4661 if next == NavPresentation::Stack {
4662 let key = current_r.borrow().clone();
4663 let want = key.as_ref().is_some_and(|k| {
4664 typed_r
4665 .borrow()
4666 .iter()
4667 .find(|x| &x.key() == k)
4668 .is_some_and(|tk| list_pred_r.as_ref().is_none_or(|p| p(tk)))
4669 });
4670 if want {
4671 if !list_in_stack_r.get() {
4672 list_in_stack_r.set(true);
4673 with_tree(|t| {
4674 t.patch(host, Box::new(NavPatch::ListInStack(true)), false)
4675 });
4676 }
4677 owners_r.borrow_mut().clear();
4678 let s = sel_r.clone();
4679 owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4680 if let Some(root) = K::from_key("") {
4681 s.write(root);
4682 }
4683 }) as PopOwner);
4684 if dv.peek() {
4685 // The detail stays on top of the interposed list; its back now
4686 // returns to the list, not to the rows.
4687 owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4688 dv.set(false);
4689 }) as PopOwner);
4690 } else if let Some(p) = resident_r.borrow_mut().pop() {
4691 // The app is not showing a detail: the list is the top.
4692 p.scope.dispose();
4693 with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4694 sizes_r.borrow_mut().remove(&p.node);
4695 with_tree(|t| {
4696 t.remove_subtree(p.node);
4697 t.mark_layout_dirty();
4698 t.layout_if_needed();
4699 });
4700 }
4701 }
4702 } else if next.is_split() {
4703 // The backend's expand lifted the list back into its own pane.
4704 list_in_stack_r.set(false);
4705 let key = current_r.borrow().clone();
4706 if resident_r.borrow().is_empty()
4707 && let Some(k) = key
4708 {
4709 // The detail was withheld while gated; a split shows it always.
4710 *current_r.borrow_mut() = None;
4711 show_r(&k);
4712 } else if !resident_r.borrow().is_empty() {
4713 owners_r.borrow_mut().clear();
4714 let s = sel_r.clone();
4715 owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4716 if let Some(root) = K::from_key("") {
4717 s.write(root);
4718 }
4719 }) as PopOwner);
4720 }
4721 }
4722 }
4723 })
4724 };
4725
4726 if requested.is_none() && can_split && we_drive {
4727 // We drive (docs/size-classes.md). Seeded with what we just built, so the first run is a
4728 // no-op; after that a class change patches the live host and the backend re-homes the
4729 // pages it already has. Nothing here rebuilds a page, which is what keeps scroll offsets,
4730 // field focus, and the search query across the morph.
4731 let rec = reconcile.clone();
4732 bind_seeded(
4733 presentation,
4734 move || resolve(day_core::window_size_class(window)),
4735 move |next: &NavPresentation| {
4736 with_tree(|t| {
4737 t.patch(host, Box::new(NavPatch::Presentation(*next)), false);
4738 t.mark_layout_dirty();
4739 t.layout_if_needed();
4740 });
4741 rec(*next);
4742 },
4743 );
4744 } else if toolkit_drives {
4745 // The toolkit drives: its own adaptive container already morphed and is telling us after
4746 // the fact, so there is nothing to patch, only the model to reconcile. Pushing a
4747 // presentation at it instead would be a second owner of the presentation racing the
4748 // platform's collapse animation.
4749 let rec = reconcile.clone();
4750 cx.on(host, move |ev| {
4751 if let Event::NavPresentationChanged(next) = ev {
4752 rec(*next);
4753 with_tree(|t| {
4754 t.mark_layout_dirty();
4755 t.layout_if_needed();
4756 });
4757 }
4758 });
4759 }
4760
4761 let icon_progress_enabled = icon_progress.is_some();
4762 let documents = sel.documents.is_some();
4763 let retain_selection = sel.retain_selection;
4764 // Re-derive the row set when a dynamic block's signal changes (re-patch the native menu,
4765 // reset the selection if its item vanished) and when the locale changes (tracked title
4766 // resolution: same keys, new titles). Installed unconditionally: a fully static
4767 // nav's derive subscribes to nothing and this effect never re-fires.
4768 {
4769 let (items_e, typed_e, titles_e, mh_e, sel_e) = (
4770 items.clone(),
4771 typed.clone(),
4772 titles.clone(),
4773 menu_holder.clone(),
4774 selection.clone(),
4775 );
4776 // The live presentation, not the build-time one: this effect outlives a morph, and what
4777 // "must never show an empty detail" means changes with it.
4778 let (show_e, pres_e) = (show.clone(), presentation_cell.clone());
4779 // Seeded with the rows the menu was realized with.
4780 let last_rows: RefCell<Option<ShownRows>> = RefCell::new(Some(shown0));
4781 let (resident_e, current_e, sizes_e) = (resident.clone(), current.clone(), sizes.clone());
4782 let movable_e = movable_of.clone();
4783 bind(
4784 move || {
4785 // Tracked derive: subscribes to every dynamic block's signal.
4786 let NavRows {
4787 keys: k,
4788 titles: t,
4789 icons: i,
4790 badges: b,
4791 badge_icons: bi,
4792 badge_tints: bt,
4793 section_ids: _,
4794 sections: sc,
4795 tints: tn,
4796 menus: mn,
4797 } = items_e.derive();
4798 (
4799 k.iter().map(|x| x.key()).collect::<Vec<_>>(),
4800 k,
4801 t,
4802 i,
4803 b,
4804 sc,
4805 tn,
4806 mn,
4807 bi,
4808 bt,
4809 )
4810 },
4811 move |(key_strs, keys, ts, ics, bs, scs, tns, mns, bis, bts): &DerivedRows<K>| {
4812 // Same rows as the last patch, with only their words or decorations moved?
4813 let rows_changed = {
4814 let mut last = last_rows.borrow_mut();
4815 let changed = last.as_ref().and_then(|l: &ShownRows| {
4816 (l.keys == *key_strs && l.sections == *scs && l.menus == *mns).then(|| {
4817 (0..key_strs.len())
4818 .filter(|&i| {
4819 l.titles[i] != ts[i]
4820 || l.icons[i] != ics[i]
4821 || l.tints[i] != tns[i]
4822 || l.badges[i] != bs[i]
4823 || l.badge_icons[i] != bis[i]
4824 || l.badge_tints[i] != bts[i]
4825 })
4826 .collect::<Box<[usize]>>()
4827 })
4828 });
4829 *last = Some(ShownRows {
4830 keys: key_strs.clone(),
4831 titles: ts.clone(),
4832 icons: ics.clone(),
4833 badges: bs.clone(),
4834 badge_icons: bis.clone(),
4835 badge_tints: bts.clone(),
4836 sections: scs.clone(),
4837 tints: tns.clone(),
4838 menus: mns.clone(),
4839 });
4840 changed
4841 };
4842 *typed_e.borrow_mut() = keys.clone();
4843 *titles_e.borrow_mut() = ts.clone();
4844 let selected_key = sel_e.peek();
4845 let cur = selected_key.key();
4846 let retain = !cur.is_empty()
4847 && !key_strs.contains(&cur)
4848 && retain_selection
4849 .as_ref()
4850 .is_some_and(|keep| keep(&selected_key));
4851 // A resident page whose row is gone has nothing left to select it, so it would
4852 // sit alive and invisible for the life of the surface, and shift every
4853 // `NavPatch::Select` index past it. Drop it here, where the new row set is known.
4854 // Only reachable in a chrome presentation; elsewhere at most one page is resident
4855 // and the selection reset below takes care of it.
4856 {
4857 let stale: Vec<ResidentPage> = {
4858 let mut r = resident_e.borrow_mut();
4859 let (keep, drop): (Vec<_>, Vec<_>) = r
4860 .drain(..)
4861 .partition(|p| key_strs.contains(&p.key) || (retain && p.key == cur));
4862 *r = keep;
4863 drop
4864 };
4865 if !stale.is_empty() {
4866 if current_e
4867 .borrow()
4868 .as_ref()
4869 .is_some_and(|c| stale.iter().any(|p| &p.key == c))
4870 {
4871 *current_e.borrow_mut() = None;
4872 }
4873 for p in stale {
4874 p.scope.dispose();
4875 sizes_e.borrow_mut().remove(&p.node);
4876 with_tree(|t| t.remove_subtree(p.node));
4877 }
4878 with_tree(|t| {
4879 t.mark_layout_dirty();
4880 t.layout_if_needed();
4881 });
4882 }
4883 }
4884 // If the selected key is gone, reset (Option key → None); else keep it selected.
4885 let still = retain || cur.is_empty() || key_strs.iter().any(|k| k == &cur);
4886 if !still && let Some(root) = K::from_key("") {
4887 sel_e.write(root);
4888 }
4889 // A split view must never show an empty detail. The build-time fallback ran
4890 // once, before any filtering, so re-apply it here: when the selected row is
4891 // gone, move to the first row that survived rather than blanking the pane.
4892 let mut cur2 = sel_e.peek().key();
4893 let pres_now = pres_e.get();
4894 // A collapsed native content list may have returned to its sidebar root.
4895 // Background count changes and filtering are not navigation requests: keep
4896 // that empty selection until a row tap or an explicit route activates it.
4897 if (pres_now.is_split()
4898 || pres_now.rows_are_chrome()
4899 || (native_list && pres_now != NavPresentation::Stack))
4900 && cur2.is_empty()
4901 && let Some(k) = keys.first().cloned()
4902 {
4903 sel_e.write(k.clone());
4904 cur2 = k.key();
4905 }
4906 let selected = key_strs.iter().position(|k| k == &cur2);
4907 if let Some(m) = mh_e.get() {
4908 with_tree(|t| {
4909 t.patch(
4910 m,
4911 Box::new(day_spec::props::NavMenuPatch::Items {
4912 rows_changed: rows_changed.clone(),
4913 document_keys: if documents {
4914 key_strs.clone()
4915 } else {
4916 Vec::new()
4917 }
4918 .into_boxed_slice(),
4919 items: ts.clone(),
4920 icons: ics.clone(),
4921 badges: bs.clone(),
4922 badge_icons: bis.clone(),
4923 badge_tints: bts.clone(),
4924 sections: scs.clone(),
4925 tints: tns.clone(),
4926 menus: mns.clone(),
4927 movable: movable_e
4928 .as_ref()
4929 .map(|r| {
4930 keys.iter().map(|k| r.drag(k) != NavDrag::Fixed).collect()
4931 })
4932 .unwrap_or_default(),
4933 sorted: match &movable_e {
4934 Some(r @ SidebarDrag::Regroup(_)) => {
4935 keys.iter().map(|k| r.drag(k) == NavDrag::Regroup).collect()
4936 }
4937 _ => Vec::new(),
4938 },
4939 selected,
4940 }),
4941 false,
4942 );
4943 });
4944 }
4945 // Re-map active route keys after insertions/filtering, after the row patch.
4946 if icon_progress_enabled {
4947 progress_revision.update(|n| *n = n.wrapping_add(1));
4948 }
4949 // Document collections can add in the background and reorder existing keys.
4950 // Realize missing pages first, then move the same native objects into key order.
4951 if pres_now.rows_are_chrome() {
4952 for key in key_strs {
4953 let missing = !resident_e.borrow().iter().any(|p| &p.key == key);
4954 if missing {
4955 show_e(key);
4956 }
4957 }
4958 let order: Vec<usize> = key_strs
4959 .iter()
4960 .filter_map(|key| resident_e.borrow().iter().position(|p| &p.key == key))
4961 .collect();
4962 if order.len() == resident_e.borrow().len()
4963 && order.iter().enumerate().any(|(i, old)| i != *old)
4964 {
4965 let mut old: Vec<Option<ResidentPage>> =
4966 resident_e.borrow_mut().drain(..).map(Some).collect();
4967 // Unique route keys produce a permutation of all resident pages;
4968 // each in-bounds slot is taken exactly once.
4969 *resident_e.borrow_mut() =
4970 order.iter().map(|i| old[*i].take().unwrap()).collect();
4971 with_tree(|t| t.patch(host, Box::new(NavPatch::Reorder(order)), false));
4972 *current_e.borrow_mut() = None;
4973 }
4974 }
4975 // Drive the detail from here as well as from the selection bind. That bind is
4976 // created first, so when a query signal and the selection are written in one
4977 // batch it runs while `typed` still holds the pre-filter rows, finds no index
4978 // for the key, and gives up, leaving a highlighted row over an empty pane with
4979 // nothing left to re-trigger it. The fallback just above has the same problem in
4980 // reverse: it changes the selection after that bind has already run. `show` is
4981 // idempotent (it returns at once when the detail already shows this key), so
4982 // calling it on every derive costs nothing and closes both holes.
4983 show_e(&cur2);
4984 },
4985 );
4986 }
4987 if let Some(progress) = icon_progress {
4988 let mh = menu_holder.clone();
4989 let keys = typed.clone();
4990 bind(
4991 move || {
4992 let revision = progress_revision.get();
4993 let active = progress();
4994 let keys = keys.borrow();
4995 let values = active
4996 .into_iter()
4997 .filter_map(|(key, fraction)| {
4998 keys.iter().position(|k| k.key() == key.key()).map(|row| {
4999 (
5000 row,
5001 fraction
5002 .filter(|f| f.is_finite())
5003 .map(|f| f.clamp(0.0, 1.0)),
5004 )
5005 })
5006 })
5007 .collect::<Vec<_>>();
5008 (revision, values)
5009 },
5010 move |(_, values)| {
5011 if let Some(menu) = mh.get() {
5012 with_tree(|t| {
5013 t.patch(
5014 menu,
5015 Box::new(NavMenuPatch::IconProgress(values.clone())),
5016 false,
5017 )
5018 });
5019 }
5020 },
5021 );
5022 }
5023
5024 // Native back (mobile up-arrow / system back) → the topmost page's owner. With only this
5025 // sidebar on the host, that's always the detail's deselect owner (returns to the list); when
5026 // a nested stack has merged its pages on top, its owners run first (docs/navigation.md). A
5027 // typed key deselects via its "" decoding (`Option<Section>` → `None`); a bare enum has no
5028 // list-only state so its owner's deselect is a no-op, so back is effectively ignored.
5029 //
5030 // A detail open beside its composed list comes first: `beside` holds this host's guard vote,
5031 // so the platform has not popped, and the back closes the detail rather than the section,
5032 // unless a stack merged above the section page owns it.
5033 {
5034 let owners = owners.clone();
5035 let (beside, dv_back) = (beside.clone(), detail_visible);
5036 cx.on(host, move |ev| match ev {
5037 Event::NavBack { already_popped } => {
5038 if !*already_popped
5039 && beside.get()
5040 && owners.borrow().len() <= 1
5041 && let Some(dv) = dv_back
5042 {
5043 dv.set(false);
5044 } else {
5045 let top = owners.borrow().last().cloned();
5046 if let Some(f) = top {
5047 f(*already_popped);
5048 }
5049 }
5050 }
5051 Event::RouteRequested(route) => {
5052 let _ = day_core::navigate(route);
5053 }
5054 _ => {}
5055 });
5056 }
5057
5058 // Registered after the pages are built: `register_nav` drains any pending route as it
5059 // registers, and a route arriving before this host has children attaches a page to a
5060 // parent that is not in the tree yet (an intermittent startup panic on AppKit). Ordering
5061 // here does not decide routing; `NavController::depth` does.
5062 let (tp_push, s_push) = (typed.clone(), selection.clone());
5063 let s_pop = selection.clone();
5064 let (dv_pop, lis_pop, pres_pop) = (
5065 detail_visible,
5066 list_in_stack.clone(),
5067 presentation_cell.clone(),
5068 );
5069 let (has_list_pop, pred_pop) = (list_build.is_some(), list_pred.clone());
5070 let s_cur = selection.clone();
5071 let (tp_enter, s_enter) = (typed.clone(), selection.clone());
5072 let s_seg = selection.clone();
5073 let pick =
5074 |tp: &Rc<RefCell<Vec<K>>>, k: &str| tp.borrow().iter().find(|x| x.key() == k).cloned();
5075 let pick_push = pick;
5076 let pick_enter = pick;
5077 if routed {
5078 note_routed_one_of_n("sidebar");
5079 register_route_surface(
5080 move |k| {
5081 if k.is_empty() {
5082 if let Some(root) = K::from_key("") {
5083 s_push.write(root);
5084 true
5085 } else {
5086 false // no empty state (bare-enum key); let the parent handle ""
5087 }
5088 } else if let Some(key) = pick_push(&tp_push, k) {
5089 s_push.write(key);
5090 true
5091 } else {
5092 false
5093 }
5094 },
5095 move |_| {
5096 let current = s_pop.peek();
5097 let pres = pres_pop.get();
5098 if current.key().is_empty() {
5099 false
5100 } else if let Some(dv) = dv_pop
5101 && dv.peek()
5102 && has_list_pop
5103 && pred_pop.as_ref().is_none_or(|p| p(¤t))
5104 && (pres.is_split()
5105 || (merged_list && pres == NavPresentation::Stack && lis_pop.get()))
5106 {
5107 // The detail is the innermost layer wherever it shows with its list
5108 // (docs/navigation.md): over it while the list is interposed in a collapsed
5109 // stack, where the native back closes it through the page's owner, and
5110 // beside it in a split, where the back closes it before the section is left.
5111 // An imperative `nav_back` lands in the same place rather than leaving the
5112 // section, which is what it did on a phone, popping the list and the section
5113 // under a script's back.
5114 dv.set(false);
5115 true
5116 } else if let Some(root) = K::from_key("") {
5117 s_pop.write(root);
5118 true
5119 } else {
5120 false
5121 }
5122 },
5123 move || s_cur.peek().key(),
5124 // Absolute-path segment: a declared item key selects it (no "", since segments are
5125 // non-empty).
5126 move |k| {
5127 if let Some(key) = pick_enter(&tp_enter, k) {
5128 s_enter.write(key);
5129 true
5130 } else {
5131 false
5132 }
5133 },
5134 move || {
5135 let k = s_seg.peek().key();
5136 if k.is_empty() { Vec::new() } else { vec![k] }
5137 },
5138 );
5139 }
5140
5141 persist_selection(restore, &selection);
5142 host
5143}
5144
5145// ===========================================================================
5146// NavStack: a push/pop navigation stack bound to a Signal<Vec<String>>.
5147// The native UINavigationController / AdwNavigationView / back-stack is reconciled
5148// to the path; the back button writes the pop back into the path.
5149// ===========================================================================
5150
5151struct StackEntry<K> {
5152 key: K,
5153 scope: Scope,
5154 page: RNode,
5155}
5156
5157/// What a [`NavStack::on_back`] guard returns for one back-like event (a native back gesture/button,
5158/// or [`nav_back`]). Programmatic path writes are not guarded; the guard is a policy on the
5159/// user's back affordance, matching Jetpack Compose's `BackHandler` (docs/navigation.md).
5160#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5161pub enum BackResponse {
5162 /// Let the pop happen now.
5163 Proceed,
5164 /// Consume the back; the pop does not happen. Stash the [`BackRequest`] and call
5165 /// [`BackRequest::proceed`] later (e.g. after a confirmation dialog) to perform the pop.
5166 Handled,
5167}
5168
5169/// The deferred pop handed to a [`NavStack::on_back`] guard. Hold it, then call [`proceed`] to
5170/// perform the back the guard consumed (the unsaved-changes → confirm → leave flow).
5171///
5172/// [`proceed`]: BackRequest::proceed
5173#[derive(Clone)]
5174pub struct BackRequest {
5175 pop: Rc<dyn Fn()>,
5176}
5177
5178impl BackRequest {
5179 /// Perform the pop this back requested. Runs the same path pop a `Proceed` would have; safe
5180 /// to call once (a second call after the page is gone is a no-op).
5181 pub fn proceed(&self) {
5182 (self.pop)();
5183 }
5184}
5185
5186/// A push/pop navigation stack whose contents are an app-owned `Signal<Vec<K>>` (the path
5187/// above the root). Day reconciles the native stack to the path; the native back button
5188/// writes the pop back into it (docs/navigation.md).
5189///
5190/// The key type is any [`Route`]: `String` for raw keys, or a typed enum whose variants can
5191/// carry data; the destination builder then receives the typed value, and an absolute
5192/// `navigate("…/item-42")` parses each segment via [`Route::from_key`] (rejecting segments
5193/// that don't parse; `String` accepts everything).
5194///
5195/// ```ignore
5196/// let path = Signal::new(Vec::<Drill>::new());
5197/// nav_stack(path.clone(), home_view).destination(|d: &Drill| detail_view(d))
5198/// // push: path.update(|p| p.push(Drill::Item { id: 42 }));
5199/// ```
5200pub struct NavStack<S: Binding<Vec<K>>, K: Route = String> {
5201 path: S,
5202 title: TextSource,
5203 root: AnyPiece,
5204 destination: Rc<dyn Fn(&K) -> AnyPiece>,
5205 on_back: Option<Rc<dyn Fn(BackRequest) -> BackResponse>>,
5206 /// The persistence key set by [`NavStack::restore`]: the path is saved here (its keys `/`-joined)
5207 /// on every change and restored at build. `None` = not persisted.
5208 restore: Option<String>,
5209 /// Items declared on the stack's root page chrome ([`NavStack::toolbar`]).
5210 toolbar: Vec<crate::ToolbarSource>,
5211}
5212
5213pub fn nav_stack<K: Route, S: Binding<Vec<K>>>(path: S, root: impl Piece) -> NavStack<S, K> {
5214 NavStack {
5215 path,
5216 title: TextSource::Static(String::new()),
5217 root: AnyPiece::new(root),
5218 destination: Rc::new(|_| {
5219 piece_fn(|cx| cx.layout_only(Rc::new(PassThrough), Flex::default(), Boundary::No)).any()
5220 }),
5221 on_back: None,
5222 restore: None,
5223 toolbar: Vec::new(),
5224 }
5225}
5226
5227#[day_macros::builder(NavStackBuilder<K>)]
5228impl<K: Route, S: Binding<Vec<K>>> NavStack<S, K> {
5229 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
5230 self.title = t.into_text();
5231 self
5232 }
5233 /// Declare toolbar items on this stack's root page chrome (docs/toolbars.md): the commands
5234 /// that act on what the root shows, and that have nothing to act on once a pushed page covers
5235 /// it. A pushed page declares its own with the same method on the piece it builds.
5236 ///
5237 /// Takes one item, a list of them, or a closure that derives the list.
5238 pub fn toolbar<M>(mut self, content: impl crate::ToolbarContent<M>) -> Self {
5239 self.toolbar.push(content.into_source());
5240 self
5241 }
5242
5243 /// Build the view for a pushed key (`&String` for raw keys, the typed value otherwise).
5244 pub fn destination<P: Piece>(mut self, build: impl Fn(&K) -> P + 'static) -> Self {
5245 self.destination = Rc::new(move |k| AnyPiece::new(build(k)));
5246 self
5247 }
5248 /// Intercept the back affordance (docs/navigation.md). The guard runs for every native back
5249 /// gesture/button and [`nav_back`] while the stack is above its root; it returns
5250 /// [`BackResponse::Proceed`] to pop now or [`BackResponse::Handled`] to consume the back
5251 /// (stash the [`BackRequest`] and call [`BackRequest::proceed`] later). Programmatic path
5252 /// writes are never guarded. While a guard is armed the toolkit stops auto-popping on a
5253 /// native gesture and routes the back through Day instead (`NavPatch::GuardTop`).
5254 pub fn on_back(mut self, guard: impl Fn(BackRequest) -> BackResponse + 'static) -> Self {
5255 self.on_back = Some(Rc::new(guard));
5256 self
5257 }
5258 /// Remember the pushed path across launches (docs/navigation.md). On every change the path's
5259 /// keys are `/`-joined and saved under `key`; at build the saved path is parsed back (each
5260 /// segment via [`Route::from_key`]) and restored, so the app reopens exactly where the user
5261 /// left off, including after an Android process death, unless a launch deep link is pending,
5262 /// which wins. `day::launch` installs the preferences as the store (docs/navigation.md); a
5263 /// saved path with a segment that no longer parses is ignored whole.
5264 pub fn restore(mut self, key: impl Into<String>) -> Self {
5265 self.restore = Some(key.into());
5266 self
5267 }
5268}
5269
5270impl<K: Route, S: Binding<Vec<K>>> Piece for NavStack<S, K> {
5271 fn build(self, cx: &mut BuildCx) -> RNode {
5272 use day_spec::props::{NavPageProps, NavPatch, NavPresentation, NavProps, Pane};
5273 let NavStack {
5274 path,
5275 title,
5276 root,
5277 destination: dest,
5278 on_back,
5279 restore,
5280 toolbar,
5281 } = self;
5282 let title_s = title.initial();
5283 // Only the top page shows (docs/toolbars.md): a desktop's one bar carries its items and
5284 // its search field, not those of the pages under it. The enclosing page's own gate still
5285 // applies, so a stack in a tab that is not selected shows nothing.
5286 let outer_gate = day_core::current_page_gate();
5287 let shown_depth = Signal::new(0usize);
5288 let gate = move |at: usize| -> Option<Rc<dyn Fn() -> bool>> {
5289 let outer = outer_gate.clone();
5290 Some(Rc::new(move || {
5291 outer.as_ref().is_none_or(|g| g()) && shown_depth.get() == at
5292 }))
5293 };
5294
5295 // Restore the saved path before the reconcile binding runs, so its pages build on first
5296 // pass. A launch deep link wins (skip). The path is decoded from the same percent-encoded
5297 // wire format the rest of nav uses (`parse_route`), so a key that itself contains `/` (or
5298 // `?`, `%`) round-trips instead of splitting into two. The whole path is parsed via
5299 // `Route::from_key`; any segment that no longer parses discards the restore rather than
5300 // building a partial stack (docs/navigation.md).
5301 if let Some(key) = restore.as_deref()
5302 && !day_core::has_launch_deeplink()
5303 && let Some(saved) = day_core::nav_store_load(key)
5304 {
5305 let (segments, _) = day_core::parse_route(&saved);
5306 let parsed: Option<Vec<K>> = segments.iter().map(|s| K::from_key(s)).collect();
5307 if let Some(v) = parsed {
5308 path.write(v);
5309 }
5310 }
5311
5312 // If we're built inside a page of an enclosing nav host that presents as a push stack
5313 // (mobile, `split == false`), merge: push our pages onto that host instead of minting a
5314 // second native container (one native nav chain, one back button; docs/navigation.md).
5315 // A split host (desktop) is not merged into; a stack keeps its own detail-pane stack.
5316 let merge = current_nav_host().filter(|c| !c.split.get());
5317
5318 let entries: Rc<RefCell<Vec<StackEntry<K>>>> = Rc::default();
5319 let native_popped: Rc<Cell<usize>> = Rc::new(Cell::new(0));
5320
5321 let host: RNode;
5322 let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>>;
5323 let owners: Rc<RefCell<Vec<PopOwner>>>;
5324 let host_cx: NavHostCx;
5325 let ret_node: RNode;
5326 let merged: bool;
5327 if let Some(ctx) = merge {
5328 // Merged: reuse the enclosing host; our root renders inline in the current page (which
5329 // is already a NAV_PAGE), and only our pushed destinations become new pages.
5330 host = ctx.host;
5331 sizes = ctx.sizes.clone();
5332 owners = ctx.owners.clone();
5333 host_cx = ctx;
5334 let hc = host_cx.clone();
5335 ret_node = with_nav_host(Some(hc), || root.build(cx));
5336 // A merged stack has no chrome of its own: its root renders inside the enclosing
5337 // host's page, and that page's bar is the one the user sees. Its items go there,
5338 // where they used to be dropped with a debug warning.
5339 for source in toolbar {
5340 crate::contribute(day_core::current_chrome(), source);
5341 }
5342 merged = true;
5343 } else {
5344 // Standalone: create the native host + root page (an app-root stack, or a nested stack
5345 // under a split/desktop host).
5346 sizes = Rc::default();
5347 host = cx.native(
5348 kinds::NAV,
5349 &NavProps {
5350 documents: None,
5351 // A stack is a stack at every size: it has no sidebar pane to re-home, so
5352 // there is nothing for a size-class change to re-present.
5353 title: title_s.clone(),
5354 presentation: NavPresentation::Stack,
5355 // Never adaptive: the `nav_stack()` piece is a push/pop surface at every size, so
5356 // an Emulated toolkit must build a plain navigation container for it rather
5357 // than its adaptive one (docs/size-classes.md).
5358 adaptive: false,
5359 // A stack has no sidebar pane, so nothing to toggle.
5360 sidebar_toggle: false,
5361 // Stacks are not searchable yet: `.searchable()` is on `Nav` only
5362 // (docs/search.md); a stack gains the same surface when the placement
5363 // resolver lands, since it is the same lowering.
5364 search: None,
5365 // A content list is a nav shape; a stack has no sidebar to sit beside.
5366 list_width: None,
5367 // A stack never has a content-list pane, so this says nothing.
5368 list_visible: true,
5369 },
5370 Rc::new(NavLayout::stack(sizes.clone())),
5371 Flex {
5372 grow_w: true,
5373 grow_h: true,
5374 ..Default::default()
5375 },
5376 Boundary::Yes,
5377 );
5378 owners = Rc::default();
5379 host_cx = NavHostCx {
5380 host,
5381 sizes: sizes.clone(),
5382 owners: owners.clone(),
5383 split: Rc::new(Cell::new(false)),
5384 guards: Rc::default(),
5385 };
5386 let root_page = nav_page(
5387 host,
5388 &NavPageProps {
5389 title: title_s,
5390 pane: Pane::Detail,
5391 },
5392 &sizes,
5393 );
5394 let hc = host_cx.clone();
5395 with_nav_host(Some(hc), || {
5396 day_core::with_page_gated(
5397 root_page,
5398 gate(0),
5399 day_spec::ToolbarColumn::Detail,
5400 || {
5401 let mut pcx = BuildCx::new(root_page);
5402 let _ = root.build(&mut pcx);
5403 },
5404 );
5405 });
5406 // A standalone stack's items ride its root page's chrome: the commands that act
5407 // on what the root shows, and that a pushed page covers along with it.
5408 for source in toolbar {
5409 crate::contribute(day_core::Chrome::Page(root_page), source);
5410 }
5411 ret_node = host;
5412 merged = false;
5413 }
5414
5415 let nav_scope = Scope::current();
5416
5417 // The raw pop: drop the top path segment (reconcile then pops the native page). The
5418 // guard's `BackRequest::proceed` runs exactly this.
5419 let raw_pop: Rc<dyn Fn()> = {
5420 let p = path.clone();
5421 Rc::new(move || {
5422 let mut v = p.peek();
5423 if v.pop().is_some() {
5424 p.write(v);
5425 }
5426 })
5427 };
5428 let depth = {
5429 let p = path.clone();
5430 move || p.peek().len()
5431 };
5432 // One back-like event (native gesture that Day owns, or `nav_back()`): consult the guard
5433 // if one is armed and we're above the root, else pop. `Proceed` pops now; `Handled`
5434 // consumes it (the app holds the `BackRequest`). Programmatic `path.set` never lands here.
5435 let run_back: Rc<dyn Fn()> = {
5436 let (raw_pop, depth, guard) = (raw_pop.clone(), depth.clone(), on_back.clone());
5437 Rc::new(move || {
5438 if depth() == 0 {
5439 return; // at root: nothing of ours to pop
5440 }
5441 match &guard {
5442 Some(g) => {
5443 let req = BackRequest {
5444 pop: raw_pop.clone(),
5445 };
5446 if g(req) == BackResponse::Proceed {
5447 raw_pop();
5448 }
5449 }
5450 None => raw_pop(),
5451 }
5452 })
5453 };
5454
5455 // This stack's back owner (one Rc shared by all its pages): a native pop the toolkit
5456 // Already performed (an unguarded iOS swipe) is absorbed + synced without the guard; a
5457 // back Day owns runs `run_back` so the guard decides.
5458 let stack_owner: PopOwner = {
5459 let (native_popped, raw_pop, run_back) =
5460 (native_popped.clone(), raw_pop.clone(), run_back.clone());
5461 Rc::new(move |already_popped: bool| {
5462 if already_popped {
5463 native_popped.set(native_popped.get() + 1);
5464 raw_pop();
5465 } else {
5466 run_back();
5467 }
5468 })
5469 };
5470
5471 // Reconcile the native stack to `want`: keep the common prefix, pop the rest, push
5472 // the new suffix. A pop the native already performed (iOS back) is not re-issued. Pages
5473 // and owners land on `host` (our own, or the enclosing one when merged).
5474 // `true` while this stack holds a guard vote on its host (`NavHostCx::vote_guard`), so the
5475 // vote moves only on a real transition (arming/disarming native gesture handling is not
5476 // free on every pop), and a merged stack shares the count with the host's other voters.
5477 let guard_armed_sent = Rc::new(Cell::new(false));
5478 let has_guard = on_back.is_some();
5479 let reconcile = {
5480 let (entries, sizes, dest, native_popped, owners, host_cx, stack_owner) = (
5481 entries.clone(),
5482 sizes.clone(),
5483 dest.clone(),
5484 native_popped.clone(),
5485 owners.clone(),
5486 host_cx.clone(),
5487 stack_owner.clone(),
5488 );
5489 let guard_armed_sent = guard_armed_sent.clone();
5490 move |want: &Vec<K>| {
5491 let common = {
5492 let ents = entries.borrow();
5493 let mut i = 0;
5494 while i < ents.len() && i < want.len() && ents[i].key == want[i] {
5495 i += 1;
5496 }
5497 i
5498 };
5499 while entries.borrow().len() > common {
5500 let e = entries.borrow_mut().pop().unwrap();
5501 if native_popped.get() > 0 {
5502 native_popped.set(native_popped.get() - 1);
5503 } else {
5504 with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
5505 }
5506 e.scope.dispose();
5507 sizes.borrow_mut().remove(&e.page);
5508 with_tree(|t| t.remove_subtree(e.page));
5509 owners.borrow_mut().pop();
5510 }
5511 for (at, key) in want.iter().enumerate().skip(common) {
5512 let title = key.title();
5513 let page = nav_page(
5514 host,
5515 &NavPageProps {
5516 title: title.clone(),
5517 pane: Pane::Detail,
5518 },
5519 &sizes,
5520 );
5521 let scope = nav_scope.enter(Scope::child);
5522 let hc = host_cx.clone();
5523 scope.enter(|| {
5524 // Inside the page's scope; see the pushed-detail site above.
5525 let content = (dest)(key);
5526 with_nav_host(Some(hc), || {
5527 day_core::with_page_gated(
5528 page,
5529 gate(at + 1),
5530 day_spec::ToolbarColumn::Detail,
5531 || {
5532 let mut c = BuildCx::new(page);
5533 let _ = content.build(&mut c);
5534 },
5535 );
5536 });
5537 });
5538 with_tree(|t| {
5539 // NavStack destinations are standard chrome in v1; the immersive flag is a
5540 // nav-item concept today (docs/navigation.md).
5541 t.patch(
5542 host,
5543 Box::new(NavPatch::Pushed {
5544 title,
5545 immersive: false,
5546 }),
5547 false,
5548 )
5549 });
5550 owners.borrow_mut().push(stack_owner.clone());
5551 entries.borrow_mut().push(StackEntry {
5552 key: key.clone(),
5553 scope,
5554 page,
5555 });
5556 }
5557 shown_depth.set(want.len());
5558 // Arm/disarm native gesture handling when the guarded-above-root state changes
5559 // (docs/navigation.md). The host is our own container, or the enclosing one when
5560 // merged; either way the native nav that owns the back gesture.
5561 if has_guard {
5562 let armed = !entries.borrow().is_empty();
5563 if armed != guard_armed_sent.get() {
5564 guard_armed_sent.set(armed);
5565 host_cx.vote_guard(armed);
5566 }
5567 }
5568 with_tree(|t| {
5569 t.mark_layout_dirty();
5570 t.layout_if_needed();
5571 });
5572 }
5573 };
5574 {
5575 let p = path.clone();
5576 bind(move || p.read(), move |want: &Vec<K>| reconcile(want));
5577 }
5578
5579 // Route identity may stay the same while asynchronously loaded metadata changes
5580 // its title. Track that title independently of path equality; do not rebuild the
5581 // page or let an enclosing merged stack rename a deeper stack's current page.
5582 {
5583 let p = path.clone();
5584 let owners = owners.clone();
5585 let stack_owner = stack_owner.clone();
5586 bind(
5587 move || p.read().last().map(Route::title),
5588 move |title: &Option<String>| {
5589 if let Some(title) = title
5590 && owners
5591 .borrow()
5592 .last()
5593 .is_some_and(|owner| Rc::ptr_eq(owner, &stack_owner))
5594 {
5595 with_tree(|t| {
5596 t.patch(host, Box::new(NavPatch::Title(title.clone())), false)
5597 });
5598 }
5599 },
5600 );
5601 }
5602
5603 // A live root title (a localized string re-resolving on locale change, docs/
5604 // localization.md): the host's bar follows while the stack shows its root, and again
5605 // when a pop returns there, since a pushed page's bar is its own (the binding above).
5606 // A merged stack's root sits inside the enclosing host's page, whose bar is that page's.
5607 if !merged && let TextSource::Dyn(_) = &title {
5608 let (p, src) = (path.clone(), title.clone());
5609 bind_seeded(
5610 (src.initial(), true),
5611 move || (src.resolve(), p.read().is_empty()),
5612 move |(t, at_root): &(String, bool)| {
5613 if *at_root {
5614 with_tree(|tr| tr.patch(host, Box::new(NavPatch::Title(t.clone())), false));
5615 }
5616 },
5617 );
5618 }
5619
5620 // Persist the path across launches when `.restore` is set: save the keys in the same
5621 // percent-encoded wire format `parse_route` reads back (`encode_route`), so a key
5622 // containing `/` survives the round-trip (docs/navigation.md). Scope-owned, so it stops
5623 // with the stack.
5624 if let Some(key) = restore {
5625 let p = path.clone();
5626 bind(
5627 move || {
5628 let keys: Vec<String> = p.read().iter().map(|k| k.key()).collect();
5629 day_core::encode_route(&keys, &[])
5630 },
5631 move |s: &String| day_core::nav_store_save(&key, s),
5632 );
5633 }
5634
5635 // Standalone: own the host's single NavBack dispatcher (→ topmost page's owner) and the
5636 // deeplink handler. Merged: the enclosing host's creator already owns both.
5637 if !merged {
5638 let owners_h = owners.clone();
5639 cx.on(host, move |ev| match ev {
5640 Event::NavBack { already_popped } => {
5641 let top = owners_h.borrow().last().cloned();
5642 if let Some(f) = top {
5643 f(*already_popped);
5644 }
5645 }
5646 Event::RouteRequested(route) => {
5647 let _ = day_core::navigate(route);
5648 }
5649 _ => {}
5650 });
5651 }
5652
5653 // Merged: our pages live on the enclosing host, so the enclosing detail's
5654 // `remove_subtree` won't reach them; pop every remaining page (top-down) off that host
5655 // when our scope disposes (e.g. the section switches). Guarded for app teardown.
5656 if merged {
5657 let (entries_c, sizes_c, owners_c, native_popped_c) = (
5658 entries.clone(),
5659 sizes.clone(),
5660 owners.clone(),
5661 native_popped.clone(),
5662 );
5663 let (guard_c, host_cx_c) = (guard_armed_sent.clone(), host_cx.clone());
5664 nav_scope.on_cleanup(move || {
5665 let alive = with_tree(|t| t.node_kind(host).is_some());
5666 // A vote this stack still holds would keep the enclosing host routing every back
5667 // through Day after the stack is gone.
5668 if alive && guard_c.replace(false) {
5669 host_cx_c.vote_guard(false);
5670 }
5671 loop {
5672 let e = entries_c.borrow_mut().pop();
5673 let Some(e) = e else { break };
5674 if alive {
5675 if native_popped_c.get() > 0 {
5676 native_popped_c.set(native_popped_c.get() - 1);
5677 } else {
5678 with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
5679 }
5680 sizes_c.borrow_mut().remove(&e.page);
5681 with_tree(|t| t.remove_subtree(e.page));
5682 owners_c.borrow_mut().pop();
5683 }
5684 }
5685 if alive {
5686 with_tree(|t| {
5687 t.mark_layout_dirty();
5688 t.layout_if_needed();
5689 });
5690 }
5691 });
5692 }
5693
5694 // string-route adapter. A stack is driven by its `path` (app state / buttons), not by
5695 // magic navigate-strings: a relative `navigate("<key>")` claims only "" (pop to root),
5696 // so sibling keys fall through to the enclosing surface, but an absolute path's
5697 // segments (`enter`) push any segment the key type parses: a `String` stack is
5698 // open-ended, a typed stack validates via `Route::from_key`, and an explicit `a/b/c`
5699 // path is the stack's state. `pop` falls through once empty.
5700 let p_push = path.clone();
5701 let p_cur = path.clone();
5702 let p_enter = path.clone();
5703 let p_seg = path.clone();
5704 register_route_surface(
5705 move |k| {
5706 if k.is_empty() {
5707 let mut v = p_push.peek();
5708 if v.is_empty() {
5709 return false; // already at root; let the parent handle ""
5710 }
5711 v.clear();
5712 p_push.write(v);
5713 true
5714 } else {
5715 false
5716 }
5717 },
5718 {
5719 // `nav_back()` is a back-like event, so it is guarded too (docs/navigation.md):
5720 // run_back consults the guard. We "own" the back (return true, no fall-through)
5721 // whenever we're above the root, whether the guard pops or consumes.
5722 let (run_back, depth) = (run_back.clone(), depth.clone());
5723 move |_| {
5724 if depth() == 0 {
5725 return false; // at root; let the parent handle back
5726 }
5727 run_back();
5728 true
5729 }
5730 },
5731 move || p_cur.peek().last().map(|k| k.key()).unwrap_or_default(),
5732 move |k| {
5733 let Some(parsed) = K::from_key(k) else {
5734 return false; // not one of this stack's routes; leave it queued
5735 };
5736 let mut v = p_enter.peek();
5737 v.push(parsed);
5738 p_enter.write(v);
5739 true
5740 },
5741 move || p_seg.peek().iter().map(|k| k.key()).collect(),
5742 );
5743 ret_node
5744 }
5745}
5746
5747// ===========================================================================
5748// Cover: a fullscreen modal surface bound to a Signal<Option<Route>> (docs/cover.md).
5749// ===========================================================================
5750
5751/// A fullscreen cover: the modal counterpart of [`nav_stack`], bound to a `Signal<Option<R>>`.
5752/// `Some(r)` presents the built content over the whole window (edge-to-edge, slide-up where
5753/// the platform animates modals); `None` dismisses it. The SwiftUI analogue is
5754/// `fullScreenCover(item:)`. Build one with [`cover`].
5755///
5756/// The open value is app state, exactly like a stack's path: set it and the cover presents;
5757/// a native dismissal (Android system back) writes `None` back, unless an
5758/// [`interactive_dismiss_disabled`](Decorate::interactive_dismiss_disabled) subtree is
5759/// mounted inside the content, in which case only programmatic writes close it.
5760/// A cover's per-route surface color (see [`Cover::background`]).
5761type CoverBackground<R> = Rc<dyn Fn(&R) -> day_spec::Color>;
5762
5763pub struct Cover<S, R: Route> {
5764 sheet: bool,
5765 half: bool,
5766 large: bool,
5767 open: S,
5768 build: Rc<dyn Fn(&R) -> AnyPiece>,
5769 background: Option<CoverBackground<R>>,
5770 routed: bool,
5771 _marker: std::marker::PhantomData<R>,
5772}
5773
5774/// A fullscreen cover over `open`: `Some(r)` presents `build(&r)`, `None` dismisses
5775/// (docs/cover.md). Registers a string-route adapter, so `navigate("<key>")` opens it and
5776/// `nav_back()` closes it, and `current_route()` reports the presented key.
5777pub fn cover<R: Route, S: Binding<Option<R>>, P: Piece>(
5778 open: S,
5779 build: impl Fn(&R) -> P + 'static,
5780) -> Cover<S, R> {
5781 Cover {
5782 sheet: false,
5783 half: false,
5784 large: false,
5785 open,
5786 // The stored builder is erased because a `Cover` holds one closure for every route it
5787 // presents; the parameter stays generic so callers never write `.any()` for us.
5788 build: Rc::new(move |r| AnyPiece::new(build(r))),
5789 background: None,
5790 routed: true,
5791 _marker: std::marker::PhantomData,
5792 }
5793}
5794
5795#[day_macros::builder(CoverBuilder<R>)]
5796impl<S: Binding<Option<R>>, R: Route> Cover<S, R> {
5797 /// Prefer a native modal sheet. Backends without sheets retain their modal cover.
5798 pub fn sheet(mut self) -> Self {
5799 self.sheet = true;
5800 self
5801 }
5802
5803 /// Present as a large modal sheet: most of the window, less a margin, for a document or a
5804 /// web page that needs the room a form does not (docs/cover.md "Large sheet"). macOS sizes
5805 /// its window sheet and the composed desktop tiers their card up to
5806 /// [`LARGE_SHEET_MAX`](day_spec::props::LARGE_SHEET_MAX); iPadOS presents a page sheet;
5807 /// compact windows keep the full-window cover, as for any sheet. Implies [`Cover::sheet`].
5808 pub fn large_sheet(mut self) -> Self {
5809 self.sheet = true;
5810 self.large = true;
5811 self
5812 }
5813
5814 /// Present as a half-height sheet rising from the bottom edge, the window content above
5815 /// it staying on show: an inspector over the canvas it describes, a transport over the
5816 /// media it controls (docs/cover.md "Half sheet"). iOS presents a medium-detent sheet that
5817 /// leaves the content interactive, Android a Material bottom sheet, the web, HarmonyOS and
5818 /// the emulated desktop tiers a bottom-anchored half panel, and macOS its window sheet at
5819 /// half the window's height. Implies [`Cover::sheet`].
5820 pub fn half_sheet(mut self) -> Self {
5821 self.sheet = true;
5822 self.half = true;
5823 self
5824 }
5825
5826 /// The surface color painted edge-to-edge behind the content (under the status bar and
5827 /// home indicator) while `r` is presented. Without it the platform's default surface
5828 /// color shows in the unsafe areas.
5829 pub fn background(mut self, f: impl Fn(&R) -> day_spec::Color + 'static) -> Self {
5830 self.background = Some(Rc::new(f));
5831 self
5832 }
5833
5834 /// Keep this cover out of the app's route space: `navigate("<key>")` never presents it, it
5835 /// contributes nothing to `current_route()`, and `nav_back()` walks past it.
5836 ///
5837 /// For a cover that is a **control's own panel** rather than an app destination (a color
5838 /// picker's chooser, a media scrubber's fullscreen mode), presented and dismissed by the
5839 /// control, never linked to. Two reasons that matters:
5840 ///
5841 /// - **A routed cover claims route segments**, and over the untyped `Route` (`String`,
5842 /// whose `from_key` accepts anything) it claims *every* segment: mount one and the next
5843 /// `navigate("settings")` presents the cover with the key `"settings"` instead of going to
5844 /// settings. A piece that mounts a cover would be silently rewriting its host app's
5845 /// navigation.
5846 /// - **It is not a place.** `current_route()` naming a transient chooser makes a restored
5847 /// session reopen it, and a "share this screen" link point at a modal.
5848 ///
5849 /// Interactive dismissal is unaffected: the cover still answers Android's system back through
5850 /// [`Event::NavBack`](day_spec::Event::NavBack) on its own node, which never went through the
5851 /// route adapter.
5852 pub fn unrouted(mut self) -> Self {
5853 self.routed = false;
5854 self
5855 }
5856}
5857
5858impl<S: Binding<Option<R>>, R: Route> Piece for Cover<S, R> {
5859 fn build(self, cx: &mut BuildCx) -> RNode {
5860 use day_spec::props::{CoverPatch, CoverProps};
5861 let Cover {
5862 sheet,
5863 half,
5864 large,
5865 open,
5866 build,
5867 background,
5868 routed,
5869 ..
5870 } = self;
5871 // A `.sheet()` on a toolkit with no native sheet is composed here: a card over the
5872 // dimmed page, on the transparent cover (docs/cover.md "Modal sheet"). The window is
5873 // the one being built, whose size class decides at each presentation.
5874 let composed_sheet = sheet
5875 && !half
5876 && day_core::capability(day_spec::Cap::CoverSheet) == day_spec::Support::Unsupported;
5877 let window = day_core::window_being_built();
5878
5879 let size: Rc<RefCell<Option<Size>>> = Rc::default();
5880 let node = cx.native(
5881 kinds::COVER,
5882 &CoverProps { sheet, half, large },
5883 Rc::new(day_core::CoverLayout { size: size.clone() }),
5884 Flex::default(),
5885 Boundary::Yes,
5886 );
5887
5888 // The presented content's scope, and whether a dismiss transition is in flight
5889 // (content stays mounted until the backend reports `CoverHidden`, so the surface
5890 // isn't blank while it slides out).
5891 struct Presented<R> {
5892 key: R,
5893 scope: Scope,
5894 }
5895 let current: Rc<RefCell<Option<Presented<R>>>> = Rc::default();
5896 let closing: Rc<Cell<bool>> = Rc::default();
5897 let owner_scope = Scope::current();
5898 let layer = NavLayer {
5899 order: Rc::new(Cell::new(0)),
5900 depth: owner_scope.use_context::<NavLayer>().map_or(0, |l| l.depth),
5901 };
5902
5903 let dispose_content = {
5904 let current = current.clone();
5905 move || {
5906 let presented = current.borrow_mut().take();
5907 // Detaching focused native inputs can enqueue their final value
5908 // or blur events. Remove their handlers before disposing signals
5909 // captured by those handlers, then release the content scope.
5910 while with_tree(|t| t.child_count(node)) > 0 {
5911 match with_tree(|t| t.first_child(node)) {
5912 Some(c) => with_tree(|t| t.remove_subtree(c)),
5913 None => break,
5914 }
5915 }
5916 if let Some(p) = presented {
5917 p.scope.dispose();
5918 }
5919 }
5920 };
5921
5922 // Reconcile the presented surface to the signal.
5923 let reconcile = {
5924 let (current, closing, dispose_content) =
5925 (current.clone(), closing.clone(), dispose_content.clone());
5926 let layer = layer.clone();
5927 move |want: &Option<R>| match want {
5928 Some(r) => {
5929 let already =
5930 !closing.get() && current.borrow().as_ref().is_some_and(|p| p.key == *r);
5931 if already {
5932 return;
5933 }
5934 dispose_content();
5935 closing.set(false);
5936 layer.order.set(NEXT_COVER_LAYER.with(|next| {
5937 let order = next.get();
5938 next.set(order + 1);
5939 order
5940 }));
5941 let scope = owner_scope.enter(Scope::child);
5942 scope.provide(NavLayer {
5943 order: layer.order.clone(),
5944 depth: layer.depth + 1,
5945 });
5946 // Run the app's builder inside the presentation scope: side effects it
5947 // performs eagerly (state restore, autosave/cleanup registration, signals)
5948 // must belong to the presented content's lifetime, not the cover's.
5949 // A compact window keeps the full-window cover: a card there would leave a
5950 // sliver of dimmed page around it.
5951 let card = composed_sheet
5952 && !day_core::window_size_class_untracked(window)
5953 .is_some_and(|c| c.width == day_spec::WidthClass::Compact);
5954 // The cover is its content's window for toolbar purposes: a navigation stack
5955 // inside it (a sheet's title, Done, bottom bar) belongs on the cover's bar,
5956 // not on the window it covers.
5957 scope.enter(|| {
5958 day_core::toolbar::with_window(node, || {
5959 let content = (build)(r);
5960 let mut c = BuildCx::new(node);
5961 if card {
5962 let _ = day_core::ComposedSheet { content, large }.build(&mut c);
5963 } else {
5964 let _ = content.build(&mut c);
5965 }
5966 })
5967 });
5968 *current.borrow_mut() = Some(Presented {
5969 key: r.clone(),
5970 scope,
5971 });
5972 // Content is mounted, so any `interactive_dismiss_disabled` inside it has
5973 // registered, so the present patch carries the resolved flag.
5974 // The composed sheet paints its own card and dimmed page; the cover under
5975 // them is clear, so the page shows through.
5976 let bg = if card {
5977 Some(day_spec::Color::CLEAR)
5978 } else {
5979 background.as_ref().map(|f| f(r))
5980 };
5981 with_tree(|t| {
5982 t.patch(
5983 node,
5984 Box::new(CoverPatch::Present {
5985 background: bg,
5986 dismiss_disabled: day_core::shield::dismiss_disabled(),
5987 }),
5988 false,
5989 );
5990 t.mark_needs_measure(node);
5991 t.mark_layout_dirty();
5992 t.layout_if_needed();
5993 });
5994 }
5995 None => {
5996 layer.order.set(0);
5997 if current.borrow().is_some() && !closing.get() {
5998 closing.set(true);
5999 with_tree(|t| t.patch(node, Box::new(CoverPatch::Dismiss), false));
6000 }
6001 }
6002 }
6003 };
6004 {
6005 let o = open.clone();
6006 bind(move || o.read(), move |want: &Option<R>| reconcile(want));
6007 }
6008
6009 // While presented, keep the backend's dismiss-disabled flag in sync with the
6010 // mounted `interactive_dismiss_disabled` modifiers (the shield's change counter
6011 // makes this binding re-run as they mount/unmount).
6012 {
6013 let current = current.clone();
6014 bind(
6015 day_core::shield::dismiss_disabled,
6016 move |disabled: &bool| {
6017 if current.borrow().is_some() {
6018 with_tree(|t| {
6019 t.patch(
6020 node,
6021 Box::new(CoverPatch::DismissDisabled(*disabled)),
6022 false,
6023 )
6024 });
6025 }
6026 },
6027 );
6028 }
6029
6030 {
6031 let (o, size, closing, dispose_content) = (
6032 open.clone(),
6033 size.clone(),
6034 closing.clone(),
6035 dispose_content.clone(),
6036 );
6037 cx.on(node, move |ev| match ev {
6038 // The backend sized the presented content container (safe-area bounds).
6039 Event::FrameChanged(sz) => {
6040 if *size.borrow() != Some(*sz) {
6041 *size.borrow_mut() = Some(*sz);
6042 with_tree(|t| {
6043 t.mark_needs_measure(node);
6044 t.mark_layout_dirty();
6045 t.layout_if_needed();
6046 });
6047 }
6048 }
6049 // Native dismissal request (Android system back). Honored unless an
6050 // `interactive_dismiss_disabled` subtree is mounted.
6051 Event::NavBack { .. } => {
6052 if !day_core::shield::dismiss_disabled() && o.peek().is_some() {
6053 o.write(None);
6054 }
6055 }
6056 // The hide transition finished; now the content can go.
6057 // Idempotent + orderable (docs/cover.md): duplicates and belated reports
6058 // from a previous dismissal are no-ops via the closing gate.
6059 Event::CoverHidden if closing.get() => {
6060 closing.set(false);
6061 dispose_content();
6062 }
6063 _ => {}
6064 });
6065 }
6066
6067 // String-route adapter (docs/navigation.md): `navigate("<key>")` presents, `nav_back()`
6068 // dismisses, and the presented key is this surface's `current_route()` contribution.
6069 // Skipped for an `unrouted()` cover, which is a control's own panel rather than a place
6070 // the app navigates to; see `Cover::unrouted` for why that distinction matters.
6071 if !routed {
6072 return node;
6073 }
6074 let o_push = open.clone();
6075 let o_pop = open.clone();
6076 let o_cur = open.clone();
6077 let o_enter = open.clone();
6078 let o_seg = open;
6079 let push = move |k: &str, sig: &S| match R::from_key(k) {
6080 Some(r) => {
6081 sig.write(Some(r));
6082 true
6083 }
6084 None => false,
6085 };
6086 let push2 = push;
6087 register_route_surface_in_layer(
6088 layer,
6089 move |k| push(k, &o_push),
6090 move |_| {
6091 if o_pop.peek().is_some() {
6092 o_pop.write(None);
6093 true
6094 } else {
6095 false
6096 }
6097 },
6098 move || o_cur.peek().map(|r| r.key()).unwrap_or_default(),
6099 move |k| push2(k, &o_enter),
6100 move || o_seg.peek().map(|r| vec![r.key()]).unwrap_or_default(),
6101 );
6102
6103 node
6104 }
6105}
6106
6107// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
6108
6109#[cfg(feature = "conformance")]
6110pub(crate) mod conformance {
6111 use day_core::Piece;
6112 use std::rc::Rc;
6113
6114 use day_core::conformance::{Case, Drive};
6115 use day_core::{Boundary, Flex, RNode, piece_fn};
6116 use day_reactive::Signal;
6117 use day_spec::props::NavPresentation;
6118 use day_spec::{Cap, Size, kinds};
6119
6120 use crate::*;
6121
6122 /// A stack whose root pushes `detail` and whose pages show their key.
6123 fn stack(path: Signal<Vec<String>>) -> impl Piece {
6124 nav_stack(
6125 path,
6126 column((
6127 label(move || format!("depth {}", path.get().len())).id(day_core::id!(depth)),
6128 button("Open")
6129 .action(move || path.update(|p| p.push("detail".into())))
6130 .id(day_core::id!(open)),
6131 )),
6132 )
6133 .title("Root")
6134 .destination(|key: &String| {
6135 label(format!("Page {key}")).id(day_core::id!(page, key.to_owned()))
6136 })
6137 }
6138
6139 /// Pushing a page shows it; going back pops it and writes the pop into the path.
6140 #[day_macros::test(day_core)]
6141 fn nav_stack_push_pop() -> Case {
6142 Case::new()
6143 .proves(kinds::NAV)
6144 .proves(kinds::NAV_PAGE)
6145 .page(|| stack(Signal::new(Vec::new())))
6146 .drive(|d: Drive| async move {
6147 d.assert_text("depth", "depth 0").await?;
6148 d.tap("open").await?;
6149 d.assert_text("page:detail", "Page detail").await?;
6150 d.wait_idle().await?;
6151 d.nav_back().await?;
6152 d.assert_missing("page:detail").await?;
6153 d.assert_text("depth", "depth 0").await
6154 })
6155 }
6156
6157 /// The stack follows its path: two keys push two pages, and back returns through them.
6158 #[day_macros::test(day_core)]
6159 fn nav_stack_follows_path() -> Case {
6160 Case::new()
6161 .proves(kinds::NAV)
6162 .page(|| stack(Signal::new(vec!["first".into(), "second".into()])))
6163 .drive(|d: Drive| async move {
6164 d.assert_text("page:second", "Page second").await?;
6165 d.wait_idle().await?;
6166 d.nav_back().await?;
6167 d.assert_missing("page:second").await?;
6168 d.assert_text("page:first", "Page first").await?;
6169 d.wait_idle().await?;
6170 d.nav_back().await?;
6171 d.assert_missing("page:first").await?;
6172 d.assert_text("depth", "depth 0").await
6173 })
6174 }
6175
6176 /// A sidebar's items each show their page when selected, as a route.
6177 #[day_macros::test(day_core)]
6178 fn nav_sidebar_selects() -> Case {
6179 Case::new()
6180 .proves(kinds::NAV)
6181 .proves(kinds::NAV_MENU)
6182 .page(|| {
6183 nav(Signal::new("alpha".to_string()))
6184 .item("alpha", "Alpha", || {
6185 label("Page Alpha").id(day_core::id!(page_alpha))
6186 })
6187 .item("beta", "Beta", || {
6188 label("Page Beta").id(day_core::id!(page_beta))
6189 })
6190 })
6191 .drive(|d: Drive| async move {
6192 d.navigate("beta").await?;
6193 d.assert_text("page_beta", "Page Beta").await?;
6194 d.assert_route("beta").await?;
6195 d.wait_idle().await?;
6196 d.navigate("alpha").await?;
6197 d.assert_text("page_alpha", "Page Alpha").await
6198 })
6199 }
6200
6201 /// Tabs show the selected tab's page and switch on a route.
6202 #[day_macros::test(day_core)]
6203 fn nav_tabs_switch() -> Case {
6204 Case::new()
6205 .proves(kinds::NAV)
6206 .page(|| {
6207 nav(Signal::new("alpha".to_string()))
6208 .presentation(NavPresentation::Tabs)
6209 .item("alpha", "Alpha", || {
6210 label("Tab Alpha").id(day_core::id!(tab_alpha))
6211 })
6212 .item("beta", "Beta", || {
6213 label("Tab Beta").id(day_core::id!(tab_beta))
6214 })
6215 })
6216 .drive(|d: Drive| async move {
6217 d.assert_text("tab_alpha", "Tab Alpha").await?;
6218 d.navigate("beta").await?;
6219 d.assert_text("tab_beta", "Tab Beta").await?;
6220 d.assert_route("beta").await
6221 })
6222 }
6223
6224 /// The page under a cover: a button that opens it and the open value as text.
6225 fn covered(open: Signal<Option<String>>, sheet: bool) -> impl Piece {
6226 let c = cover(open, move |key: &String| {
6227 column((
6228 label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6229 button("Close")
6230 .action(move || open.set(None))
6231 .id(day_core::id!(close)),
6232 ))
6233 });
6234 column((
6235 label(move || format!("open {}", open.get().unwrap_or_default()))
6236 .id(day_core::id!(state)),
6237 button("Show")
6238 .action(move || open.set(Some("panel".into())))
6239 .id(day_core::id!(show)),
6240 if sheet { c.sheet().any() } else { c.any() },
6241 ))
6242 }
6243
6244 /// Setting the open value presents the cover; clearing it dismisses it.
6245 #[day_macros::test(day_core)]
6246 fn cover_presents_and_dismisses() -> Case {
6247 Case::new()
6248 .proves_cap(Cap::Cover)
6249 .proves(kinds::COVER)
6250 .page(|| covered(Signal::new(None), false))
6251 .drive(|d: Drive| async move {
6252 d.assert_missing("cover_text").await?;
6253 d.tap("show").await?;
6254 d.assert_text("cover_text", "Cover panel").await?;
6255 d.wait_idle().await?;
6256 d.tap("close").await?;
6257 d.assert_missing("cover_text").await?;
6258 d.assert_text("state", "open ").await
6259 })
6260 }
6261
6262 /// A sheet presents the same way, and going back dismisses it and writes `None` back.
6263 #[day_macros::test(day_core)]
6264 fn cover_sheet_back_dismisses() -> Case {
6265 Case::new()
6266 .proves(kinds::COVER)
6267 .page(|| covered(Signal::new(None), true))
6268 .drive(|d: Drive| async move {
6269 d.tap("show").await?;
6270 d.assert_text("cover_text", "Cover panel").await?;
6271 d.assert_text("state", "open panel").await?;
6272 d.wait_idle().await?;
6273 d.nav_back().await?;
6274 d.assert_missing("cover_text").await?;
6275 d.assert_text("state", "open ").await
6276 })
6277 }
6278
6279 /// A layout that answers the proposal and remembers the height it was placed at: how a
6280 /// case measures a surface on every toolkit, the mock included, without a number that
6281 /// would only hold for one window size.
6282 pub(crate) struct HeightProbe(pub(crate) Rc<std::cell::Cell<f64>>);
6283
6284 impl day_core::Layout for HeightProbe {
6285 fn measure(
6286 &self,
6287 _cx: &mut dyn day_core::LayoutOps,
6288 _children: &[RNode],
6289 p: day_geometry::Proposal,
6290 ) -> Size {
6291 Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
6292 }
6293 fn place(
6294 &self,
6295 _cx: &mut dyn day_core::LayoutOps,
6296 _children: &[RNode],
6297 bounds: day_geometry::Rect,
6298 ) {
6299 self.0.set(bounds.size.height);
6300 }
6301 }
6302
6303 /// A growable piece that records the height it is laid out at into `into`.
6304 pub(crate) fn height_probe(into: Rc<std::cell::Cell<f64>>) -> impl Piece {
6305 piece_fn(move |cx| {
6306 cx.layout_only(
6307 Rc::new(HeightProbe(into)),
6308 Flex {
6309 grow_w: true,
6310 grow_h: true,
6311 ..Default::default()
6312 },
6313 Boundary::No,
6314 )
6315 })
6316 }
6317
6318 // The heights the half-sheet cases compare: the page's, and the cover content's.
6319 thread_local! {
6320 static HALF_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
6321 (Rc::default(), Rc::default());
6322 }
6323
6324 /// The page under a half sheet: a probe filling the page, the open value as text, a
6325 /// button that opens the sheet, and the sheet with a probe filling its content.
6326 fn half_covered(open: Signal<Option<String>>) -> impl Piece {
6327 let (page_h, cover_h) = HALF_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
6328 page_h.set(0.0);
6329 cover_h.set(0.0);
6330 let sheet = cover(open, move |key: &String| {
6331 column((
6332 label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6333 height_probe(cover_h.clone()),
6334 button("Close")
6335 .action(move || open.set(None))
6336 .id(day_core::id!(close)),
6337 ))
6338 })
6339 .half_sheet();
6340 zstack((
6341 height_probe(page_h),
6342 column((
6343 label(move || format!("open {}", open.get().unwrap_or_default()))
6344 .id(day_core::id!(state)),
6345 button("Show")
6346 .action(move || open.set(Some("panel".into())))
6347 .id(day_core::id!(show)),
6348 sheet,
6349 )),
6350 ))
6351 }
6352
6353 /// Whether `probe_h` is a half sheet's content height against the page's `page_h`: at
6354 /// most a little over half (a grabber or handle rides inside the half), and well clear of
6355 /// zero.
6356 pub(crate) fn is_half(page_h: f64, probe_h: f64) -> bool {
6357 page_h > 0.0 && probe_h > page_h * 0.15 && probe_h <= page_h * 0.6
6358 }
6359
6360 /// Wait for a presented sheet's content to be laid out, then judge it with [`is_half`].
6361 /// The frame a native sheet reports lands a turn after the presentation (and on the mock
6362 /// a flush later), so the probe is polled rather than read once.
6363 pub(crate) async fn check_half(
6364 d: &Drive,
6365 what: &str,
6366 heights: &(Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>),
6367 ) -> day_core::conformance::TestResult {
6368 let mut got = (0.0, 0.0);
6369 for _ in 0..40 {
6370 got = (heights.0.get(), heights.1.get());
6371 if is_half(got.0, got.1) {
6372 break;
6373 }
6374 d.pause(0.05).await?;
6375 d.wait_idle().await?;
6376 }
6377 d.check(
6378 is_half(got.0, got.1),
6379 &format!("{what} {} of page {}: between 15% and 60%", got.1, got.0),
6380 )
6381 }
6382
6383 /// A half sheet presents over the page at (about) half its height, and the content
6384 /// underneath stays mounted; clearing the value dismisses it.
6385 #[day_macros::test(day_core)]
6386 fn cover_half_sheet_presents_over_content() -> Case {
6387 Case::new()
6388 .proves(kinds::COVER)
6389 .page(|| half_covered(Signal::new(None)))
6390 .drive(|d: Drive| async move {
6391 d.assert_missing("cover_text").await?;
6392 d.tap("show").await?;
6393 d.assert_text("cover_text", "Cover panel").await?;
6394 d.wait_idle().await?;
6395 let heights = HALF_HEIGHTS.with(|h| h.clone());
6396 check_half(&d, "half sheet content", &heights).await?;
6397 d.assert_text("state", "open panel").await?;
6398 d.tap("close").await?;
6399 d.assert_missing("cover_text").await?;
6400 d.assert_text("state", "open ").await
6401 })
6402 }
6403
6404 /// Going back dismisses a half sheet and writes `None` back, as it does a sheet.
6405 #[day_macros::test(day_core)]
6406 fn cover_half_sheet_back_dismisses() -> Case {
6407 Case::new()
6408 .proves(kinds::COVER)
6409 .page(|| half_covered(Signal::new(None)))
6410 .drive(|d: Drive| async move {
6411 d.tap("show").await?;
6412 d.assert_text("cover_text", "Cover panel").await?;
6413 d.wait_idle().await?;
6414 d.nav_back().await?;
6415 d.assert_missing("cover_text").await?;
6416 d.assert_text("state", "open ").await
6417 })
6418 }
6419
6420 // The heights the composed-sheet case compares: the page's, and the sheet content's.
6421 thread_local! {
6422 static SHEET_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
6423 (Rc::default(), Rc::default());
6424 }
6425
6426 /// On a toolkit with no native sheet, a `.sheet()` over a wide window is a card centered
6427 /// on the dimmed page: its content lays out shorter than the page, the page stays mounted,
6428 /// and the card's own controls dismiss it.
6429 #[day_macros::test(day_core)]
6430 fn cover_sheet_composes_a_card_on_wide() -> Case {
6431 Case::new()
6432 .proves(kinds::COVER)
6433 .requires_support("composed sheet", || {
6434 if day_core::capability(Cap::CoverSheet) == day_spec::Support::Unsupported {
6435 day_spec::Support::Native
6436 } else {
6437 day_spec::Support::Unsupported
6438 }
6439 })
6440 .page(|| {
6441 let (page_h, sheet_h) = SHEET_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
6442 page_h.set(0.0);
6443 sheet_h.set(0.0);
6444 let open = Signal::new(None::<String>);
6445 let sheet = cover(open, move |key: &String| {
6446 column((
6447 label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6448 height_probe(sheet_h.clone()),
6449 button("Close")
6450 .action(move || open.set(None))
6451 .id(day_core::id!(close)),
6452 ))
6453 })
6454 .sheet()
6455 .unrouted();
6456 zstack((
6457 height_probe(page_h),
6458 column((
6459 label(move || format!("open {}", open.get().unwrap_or_default()))
6460 .id(day_core::id!(state)),
6461 button("Show")
6462 .action(move || open.set(Some("panel".into())))
6463 .id(day_core::id!(show)),
6464 sheet,
6465 )),
6466 ))
6467 })
6468 .drive(|d: Drive| async move {
6469 let _restore = crate::inspector::conformance::RestoreSizeClass;
6470 day_core::override_size_class(day_spec::SizeClass {
6471 width: day_spec::WidthClass::Expanded,
6472 height: day_spec::HeightClass::Expanded,
6473 });
6474 d.wait_idle().await?;
6475 d.tap("show").await?;
6476 d.assert_text("cover_text", "Cover panel").await?;
6477 let heights = SHEET_HEIGHTS.with(|h| h.clone());
6478 let mut got = (0.0, 0.0);
6479 for _ in 0..40 {
6480 got = (heights.0.get(), heights.1.get());
6481 if got.0 > 0.0 && got.1 > 0.0 {
6482 break;
6483 }
6484 d.pause(0.05).await?;
6485 d.wait_idle().await?;
6486 }
6487 d.check(
6488 got.0 > 0.0 && got.1 > 0.0 && got.1 < got.0,
6489 &format!("sheet content {} under a page {} tall", got.1, got.0),
6490 )?;
6491 d.assert_text("state", "open panel").await?;
6492 d.tap("close").await?;
6493 d.assert_missing("cover_text").await?;
6494 d.assert_text("state", "open ").await
6495 })
6496 }
6497}