Skip to main content

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