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::Ink>>,
688    Vec<Vec<day_spec::MenuItem>>,
689    Vec<Option<String>>,
690    Vec<Option<day_spec::Ink>>,
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::Ink>>,
702    sections: Vec<Option<String>>,
703    tints: Vec<Option<day_spec::Ink>>,
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::Ink>,
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::Ink>,
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::Ink>,
770    menu: Vec<day_spec::MenuItem>,
771    badge: Option<TextSource>,
772    badge_icon: Option<String>,
773    badge_tint: Option<day_spec::Ink>,
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: impl Into<day_spec::Ink>) -> Self {
821        self.icon_tint = Some(color.into());
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: impl Into<day_spec::Ink>) -> Self {
859        self.badge_tint = Some(color.into());
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 (UIKit and edge-to-edge Android) 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::Ink>,
1040    menu: Vec<day_spec::MenuItem>,
1041    badge: Option<TextSource>,
1042    badge_icon: Option<String>,
1043    badge_tint: Option<day_spec::Ink>,
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::Ink>,
1241    badge: Option<String>,
1242    badge_icon: Option<String>,
1243    badge_tint: Option<day_spec::Ink>,
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::Ink::system(day_spec::SystemColor::Accent));
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: day_spec::Angle::deg(-90.0),
1374                                sweep: day_spec::Angle::FULL * 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::Ink>>,
1714    sections: Vec<Option<String>>,
1715    section_ids: Vec<Option<String>>,
1716    tints: Vec<Option<day_spec::Ink>>,
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                immersive: false,
3115            },
3116            &sizes,
3117        );
3118        // The list is this host's root page, so a `nav_stack()` inside it merges here: a drill-down
3119        // from the list (a category, then its items) pushes onto the tab's own navigation
3120        // controller, and the gated detail lands on top of whatever it pushed
3121        // (docs/navigation.md). Only the native resident pane is a barrier.
3122        // This shape shows one layer at a time, so the list's commands leave once the detail is
3123        // pushed over it, the same rule the native pane follows. The enclosing page's own gate
3124        // still applies: a tab that is not selected takes the list's commands with it.
3125        let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
3126        with_nav_host(Some(target.clone()), || {
3127            day_core::with_page_gated(
3128                root_page,
3129                Some(covered),
3130                day_spec::ToolbarColumn::List,
3131                || {
3132                    let mut pcx = BuildCx::new(root_page);
3133                    let _ = (cfg.list)().grow(Dimension::Both).build(&mut pcx);
3134                },
3135            );
3136        });
3137        // The nav's items, re-homed: a chrome presentation draws no bar of its own, so this
3138        // nested host's root page is where the list's commands belong (docs/toolbars.md).
3139        for source in cfg.toolbar.clone() {
3140            crate::contribute(day_core::Chrome::Page(root_page), source);
3141        }
3142        // This host's one back dispatcher: the topmost owner, the detail layer's or a
3143        // stack's that merged inside the detail.
3144        {
3145            let owners = owners.clone();
3146            cx.on(host, move |ev| match ev {
3147                Event::NavBack { already_popped } => {
3148                    let top = owners.borrow().last().cloned();
3149                    if let Some(f) = top {
3150                        f(*already_popped);
3151                    }
3152                }
3153                Event::RouteRequested(route) => {
3154                    let _ = day_core::navigate(route);
3155                }
3156                _ => {}
3157            });
3158        }
3159        wire_gated_detail(&cfg, &target);
3160        host
3161    })
3162}
3163
3164/// A stacked presentation's gated destination: the list renders inline in the destination's
3165/// own page and the detail pushes onto the enclosing host, the same merge a nested `nav_stack()`
3166/// performs, so the whole chain stays one native stack with one back button
3167/// (docs/navigation.md).
3168fn gated_detail_merged<K: Route>(cfg: GatedDetail<K>) -> impl Piece {
3169    piece_fn(move |cx| {
3170        let target = cfg.host_cx.clone();
3171        // The list is inline in a page of the enclosing stack, so a `nav_stack()` inside it merges
3172        // there, as one inside any pushed page does (docs/navigation.md).
3173        // Same rule as the nested shape: the detail pushes over this list, so the list's own
3174        // commands leave the bar while it is covered (docs/toolbars.md), and while the page it is
3175        // inline in is not showing.
3176        let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
3177        // The page this list is inline in, whichever it is: the gate is what matters, and the
3178        // frame keeps the chrome it was already going to land on.
3179        let page = match day_core::current_chrome() {
3180            day_core::Chrome::Page(p) => p,
3181            day_core::Chrome::Window(w) => w,
3182        };
3183        let node = with_nav_host(Some(target.clone()), || {
3184            day_core::with_page_gated(page, Some(covered), day_spec::ToolbarColumn::List, || {
3185                (cfg.list)().grow(Dimension::Both).build(cx)
3186            })
3187        });
3188        wire_gated_detail(&cfg, &target);
3189        node
3190    })
3191}
3192
3193/// Drive the detail layer from `detail_visible`, whichever host carries it: `true` pushes the
3194/// destination's page onto `target`, `false` (and the native back, which writes it) pops.
3195/// Registered in the current scope, so a section switch or a presentation morph tears the
3196/// layer down with the shape that built it.
3197fn wire_gated_detail<K: Route>(cfg: &GatedDetail<K>, target: &NavHostCx) {
3198    use day_spec::props::{NavPageProps, NavPatch, Pane};
3199    /// The pushed layer: its page, and the scope its content lives in.
3200    struct Layer {
3201        scope: Scope,
3202        page: RNode,
3203    }
3204    let layer: Rc<RefCell<Option<Layer>>> = Rc::default();
3205    // Pops the toolkit already performed (an iOS swipe, the Android system back): the
3206    // answering `Popped` is absorbed rather than re-issued, same as a stack's.
3207    let native_popped: Rc<Cell<usize>> = Rc::default();
3208    let open = cfg.open;
3209    let owner_scope = Scope::current();
3210
3211    // The native back, while the detail is up: report it into the signal; the pop itself is
3212    // performed by the binding below, so a back and a programmatic `false` are one path.
3213    let owner: PopOwner = {
3214        let native_popped = native_popped.clone();
3215        Rc::new(move |already_popped: bool| {
3216            if already_popped {
3217                native_popped.set(native_popped.get() + 1);
3218            }
3219            open.set(false);
3220        })
3221    };
3222
3223    let detail_src = cfg.detail_title.clone();
3224    let root_title = cfg.title.clone();
3225    let push = {
3226        let (layer, target, owner) = (layer.clone(), target.clone(), owner.clone());
3227        let (items, key) = (cfg.items.clone(), cfg.key.clone());
3228        let (detail_src, root_title) = (detail_src.clone(), root_title.clone());
3229        move || {
3230            if layer.borrow().is_some() {
3231                return;
3232            }
3233            let title = detail_src
3234                .as_ref()
3235                .map_or_else(|| root_title.clone(), TextSource::initial);
3236            let immersive = items.immersive_of(&key.key());
3237            let page = nav_page(
3238                target.host,
3239                &NavPageProps {
3240                    title: title.clone(),
3241                    pane: Pane::Detail,
3242                    immersive,
3243                },
3244                &target.sizes,
3245            );
3246            // Before the content builds, so a stack that merges inside the detail lands its
3247            // owners on top of this one.
3248            target.owners.borrow_mut().push(owner.clone());
3249            let scope = owner_scope.enter(Scope::child);
3250            let tc = target.clone();
3251            scope.enter(|| {
3252                // The app's builder runs inside this page's scope, like the presentation site
3253                // further down: a page body runs app code (an ambient state read, a `Signal`,
3254                // a registration), and all of it belongs to the page's lifetime rather than to
3255                // whichever scope happened to be current when the push landed.
3256                let content = items.build_page(&key);
3257                with_nav_host(Some(tc), || {
3258                    day_core::with_page(page, || {
3259                        let mut c = BuildCx::new(page);
3260                        let _ = content.grow(Dimension::Both).build(&mut c);
3261                    });
3262                });
3263            });
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            immersive: false,
3665        },
3666        &sizes,
3667    );
3668    sidebar_cell.set(Some(root_page));
3669
3670    // Search, both directions (docs/search.md). The app's writes patch the live field; the user's
3671    // edits arrive as events against this host and write the app's own signals. Nothing here
3672    // touches the widget directly, which is what lets a later placement change relocate the field
3673    // without disturbing the query.
3674    if let Some((spec, seed)) = search_spec.as_ref().zip(search_seed.as_ref()) {
3675        spec.install(host, day_core::Chrome::Page(root_page), seed);
3676        let query = spec.query;
3677        let scope_sig = spec.scope;
3678        let submit = spec.submit.clone();
3679        cx.on(host, move |ev| match ev {
3680            Event::SearchChanged(text) => query.set(text.clone()),
3681            Event::SearchSubmitted(text) => {
3682                if let Some(f) = &submit {
3683                    f(text);
3684                }
3685            }
3686            Event::SearchScopeChanged(i) => {
3687                if let Some(s) = scope_sig {
3688                    s.set(*i);
3689                }
3690            }
3691            _ => {}
3692        });
3693    }
3694
3695    // This host's items (docs/toolbars.md): the sidebar column's chrome while split, the
3696    // root list's while collapsed. Registered under the build's scope, so they are withdrawn if
3697    // the whole surface goes.
3698    // The sidebar affordance the host supplies for itself, ahead of the app's own items. Every
3699    // desktop expects one and the toolkit owns the behavior, so an app that used to declare the
3700    // button by hand now declares nothing (docs/toolbars.md).
3701    // The host's chrome is the sidebar column (docs/toolbars.md): a three-pane desktop draws
3702    // these over the sidebar, against the divider they act on.
3703    day_core::with_page_in(
3704        root_page,
3705        None,
3706        day_spec::ToolbarColumn::Sidebar,
3707        window,
3708        || {
3709            if sidebar_toggle
3710                && with_tree(|t| t.capability(day_spec::Cap::Toolbar))
3711                    != day_spec::Support::Unsupported
3712            {
3713                crate::contribute(
3714                    day_core::Chrome::Page(root_page),
3715                    crate::ToolbarSource::Fixed(vec![crate::sidebar_toggle_item(host)]),
3716                );
3717            }
3718            for source in host_toolbar {
3719                crate::contribute(day_core::Chrome::Page(root_page), source);
3720            }
3721        },
3722    );
3723    let menu_holder: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
3724    // Reordering (docs/navigation.md): a toolkit whose own sidebar drags rows
3725    // (`Cap::NavReorder` Native) keeps it and marks the movable rows; one that cannot stands a
3726    // reorderable list in for it (`reorder_sidebar`). Collapsible sections win over both.
3727    let nav_reorder = day_core::capability(day_spec::Cap::NavReorder);
3728    let native_reorder = sel
3729        .reorder_items
3730        .clone()
3731        .filter(|_| nav_reorder == day_spec::Support::Native && sel.collapsed_sections.is_none());
3732    // Which rows drag, re-asked whenever the rows change.
3733    let movable_of = native_reorder.clone();
3734    {
3735        let (mh, ks, s, ts) = (
3736            menu_holder.clone(),
3737            typed.clone(),
3738            selection.clone(),
3739            titles.clone(),
3740        );
3741        let (titles_init, icons_init) = (titles.borrow().clone(), icons0.clone());
3742        // The selection the host is already on, not `None`. `sync_menu` pushes it a moment later
3743        // as `NavMenuPatch::Selected`, and every backend that draws a resting highlight used to
3744        // depend on that patch landing after its view existed, which held on UIKit and did not
3745        // on Android, where the sidebar came up marking nothing at all. Seeding the props means
3746        // the first realization is already right and the patch is only ever a change.
3747        let selected_init = {
3748            let key = selection.peek().key().clone();
3749            typed
3750                .borrow()
3751                .iter()
3752                .position(|k| k.key() == key)
3753                .filter(|_| !key.is_empty())
3754        };
3755        let (badges_init, sections_init) = (rows0.badges.clone(), rows0.sections.clone());
3756        let (badge_icons_init, badge_tints_init) =
3757            (rows0.badge_icons.clone(), rows0.badge_tints.clone());
3758        let tints_init = rows0.tints.clone();
3759        let menus_init = rows0.menus.clone();
3760        let reorders_natively = native_reorder.is_some();
3761        let rows_script = items.clone();
3762        let movable_init: Vec<bool> = movable_of.as_ref().map_or_default(|r| {
3763            typed
3764                .borrow()
3765                .iter()
3766                .map(|k| r.drag(k) != NavDrag::Fixed)
3767                .collect()
3768        });
3769        let regroup_init = matches!(movable_of, Some(SidebarDrag::Regroup(_)));
3770        let sorted_init: Vec<bool> = match &movable_of {
3771            Some(r @ SidebarDrag::Regroup(_)) => typed
3772                .borrow()
3773                .iter()
3774                .map(|k| r.drag(k) == NavDrag::Regroup)
3775                .collect(),
3776            _ => Vec::new(),
3777        };
3778        let document_keys = if sel.documents.is_some() {
3779            typed.borrow().iter().map(Route::key).collect()
3780        } else {
3781            Vec::new()
3782        };
3783        let document_event = sel.document_event.clone();
3784        let refresh = sel.refresh;
3785        let list_pred_click = sel.content_list_pred.clone();
3786        let pres_click = presentation_cell.clone();
3787        let detail_visible_click = sel.detail_visible;
3788        let menu_piece = if let Some(collapsed) = sel.collapsed_sections {
3789            section_sidebar(
3790                items.clone(),
3791                selection.clone(),
3792                collapsed,
3793                sel.on_section_expansion,
3794                icon_progress.clone(),
3795            )
3796        } else if let Some(reorder) = sel
3797            .reorder_items
3798            .filter(|_| nav_reorder == day_spec::Support::Emulated)
3799        {
3800            reorder_sidebar(
3801                items.clone(),
3802                selection.clone(),
3803                reorder,
3804                icon_progress.clone(),
3805            )
3806        } else {
3807            piece_fn(move |mcx| {
3808                let node = mcx.native(
3809                    kinds::NAV_MENU,
3810                    &NavMenuProps {
3811                        document_keys,
3812                        items: titles_init,
3813                        icons: icons_init,
3814                        badges: badges_init,
3815                        badge_icons: badge_icons_init,
3816                        badge_tints: badge_tints_init,
3817                        sections: sections_init,
3818                        tints: tints_init,
3819                        menus: menus_init,
3820                        movable: movable_init,
3821                        regroup: regroup_init,
3822                        sorted: sorted_init,
3823                        selected: selected_init,
3824                    },
3825                    Rc::new(LeafLayout),
3826                    Flex {
3827                        grow_w: true,
3828                        grow_h: true,
3829                        ..Default::default()
3830                    },
3831                    Boundary::No,
3832                );
3833                mh.set(Some(node));
3834                // The dayscript `reorder` step drives this sidebar in the rows the stand-in list
3835                // has, section headers counted, so one script reorders both.
3836                match native_reorder.clone() {
3837                    Some(SidebarDrag::Reorder(reorder)) => {
3838                        let rows = rows_script.clone();
3839                        day_core::set_scripted_reorder(node, move |from, to| {
3840                            let NavRows { keys, sections, .. } =
3841                                day_reactive::untrack(|| rows.derive());
3842                            script_nav_reorder(&keys, &sections, &reorder, from, to)
3843                        });
3844                    }
3845                    Some(SidebarDrag::Regroup(regroup)) => {
3846                        let rows = rows_script.clone();
3847                        day_core::set_scripted_reorder(node, move |from, to| {
3848                            let rows =
3849                                RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
3850                            if let Some(drop) = rows.display_drop(&regroup, from, to)? {
3851                                (regroup.dropped)(drop);
3852                            }
3853                            Ok(to)
3854                        });
3855                    }
3856                    None => {}
3857                }
3858                if let Some((refreshing, action)) = refresh {
3859                    let refreshing = Rc::new(refreshing);
3860                    let state = refreshing.clone();
3861                    bind(
3862                        move || state.get(),
3863                        move |busy| {
3864                            with_tree(|t| {
3865                                t.patch(
3866                                    node,
3867                                    Box::new(day_spec::props::RefreshPatch { refreshing: *busy }),
3868                                    false,
3869                                );
3870                            });
3871                        },
3872                    );
3873                    mcx.on(node, move |event| {
3874                        if matches!(event, Event::RefreshRequested) {
3875                            if !day_reactive::untrack(|| refreshing.get()) {
3876                                action();
3877                            }
3878                            // Re-apply even when the state did not change: the user may have
3879                            // pulled an empty/offline library and the app declined the work.
3880                            let busy = day_reactive::untrack(|| refreshing.get());
3881                            with_tree(|t| {
3882                                t.patch(
3883                                    node,
3884                                    Box::new(day_spec::props::RefreshPatch { refreshing: busy }),
3885                                    false,
3886                                );
3887                            });
3888                        }
3889                    });
3890                }
3891                if let Some(event) = document_event {
3892                    mcx.on(node, move |ev| event(ev));
3893                }
3894                // A row the sidebar itself dragged: `from` moved to where `to` stood, both
3895                // item indices into the keys as they were before the move.
3896                // A drop a regrouping sidebar committed, checked against the app's rules here,
3897                // whatever the toolkit offered.
3898                if let Some(SidebarDrag::Regroup(regroup)) = native_reorder.clone() {
3899                    let rows = rows_script.clone();
3900                    mcx.on(node, move |ev| {
3901                        if let Event::NavRegroup {
3902                            from,
3903                            section,
3904                            before,
3905                        } = *ev
3906                        {
3907                            let rows =
3908                                RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
3909                            if let Ok(Some(drop)) = rows.drop_at(&regroup, from, section, before) {
3910                                (regroup.dropped)(drop);
3911                            }
3912                        }
3913                    });
3914                }
3915                if let Some(SidebarDrag::Reorder(reorder)) = native_reorder {
3916                    let keys = ks.clone();
3917                    mcx.on(node, move |ev| {
3918                        if let Event::ListReorder { from, to } = *ev {
3919                            let pair = {
3920                                let keys = keys.borrow();
3921                                keys.get(from).cloned().zip(keys.get(to).cloned())
3922                            };
3923                            if let Some((moved, target)) = pair
3924                                && (reorder.eligible)(&moved)
3925                                && (reorder.eligible)(&target)
3926                            {
3927                                (reorder.moved)(moved, target);
3928                            }
3929                        }
3930                    });
3931                }
3932                mcx.on(node, move |ev| {
3933                    if let Event::SelectionChanged(i) = ev
3934                        && let Some(k) = ks.borrow().get(*i as usize)
3935                    {
3936                        // Announce the navigation from its source (§14.6) with the row's own title:
3937                        // the sidebar changes the route only after a remount, so a route observer would
3938                        // otherwise miss the move and have no label for it. Index the live titles.
3939                        let label = ts.borrow().get(*i as usize).cloned();
3940                        day_core::note_navigation(&k.key(), label.as_deref());
3941                        s.write(k.clone());
3942                        // Activation is not just selection. UIKit can leave the supplementary
3943                        // column offstage after its initial collapse, or after native back,
3944                        // even though this route is already selected. Re-present the list on
3945                        // EVERY tap, including a tap on the highlighted row. Do not rebuild it.
3946                        if merged_list
3947                            && pres_click.get() == NavPresentation::Stack
3948                            && detail_visible_click.is_some_and(|visible| !visible.peek())
3949                            && list_pred_click.as_ref().is_none_or(|p| p(k))
3950                        {
3951                            with_tree(|t| {
3952                                t.patch(host, Box::new(NavPatch::ListInStack(true)), false);
3953                            });
3954                        }
3955                    }
3956                });
3957                node
3958            })
3959            // A reorderable sidebar answers to the stand-in list's name, so a script's
3960            // `reorder` steps address the sidebar whichever one the toolkit shows.
3961            .id(if reorders_natively {
3962                day_core::id!(nav_reorder_list)
3963            } else {
3964                day_core::id!(nav_menu)
3965            })
3966            .any()
3967        };
3968        let content: AnyPiece = match sel.header {
3969            Some(h) => column((h(), menu_piece))
3970                .spacing(4.0)
3971                .align(HAlign::Leading)
3972                .any(),
3973            None => column((menu_piece,))
3974                .spacing(4.0)
3975                .align(HAlign::Leading)
3976                .any(),
3977        };
3978        let content = match sel.footer {
3979            Some(footer) => column((content.grow(Dimension::Both), footer()))
3980                .grow(Dimension::Both)
3981                .any(),
3982            None => content,
3983        };
3984        with_nav_host(Some(host_cx.clone()), || {
3985            let mut pcx = BuildCx::new(root_page);
3986            let _ = content.build(&mut pcx);
3987        });
3988    }
3989
3990    // The content-list page (docs/navigation.md): built once, resident for the host's life.
3991    // Its content follows the app's signals, so a selection change re-scopes it without a
3992    // rebuild. `with_nav_host(None)`: the pane is not a merge target, so a stack inside the
3993    // list keeps its own container rather than pushing onto this host.
3994    let list_build = sel.content_list.clone();
3995    let list_pred = sel.content_list_pred.clone();
3996    let detail_visible = sel.detail_visible;
3997    // Whether the content-list pane belongs to this destination (`content_list_for`), applied
3998    // wherever the shown destination can change. It lives here, shared, because three paths
3999    // reach it: a fresh `show`, a `show` that finds its page already resident (a chrome
4000    // presentation has built them all), and a presentation change that rebuilds the shape
4001    // around an unchanged selection. Missing any one of them strands the pane: collapsed
4002    // because some other destination was the last to speak, with nothing left to reopen it.
4003    // Set when the content-list page is built below; `apply_list_visible` writes through it so
4004    // the pane's chrome follows its visibility (docs/toolbars.md).
4005    let list_visible_sig: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
4006    let apply_list_visible: Rc<dyn Fn(&K)> = {
4007        let (shown, pred) = (list_shown.clone(), list_pred.clone());
4008        let mirror = list_visible_sig.clone();
4009        Rc::new(move |key: &K| {
4010            if !native_list {
4011                return;
4012            }
4013            let want = pred.as_ref().is_none_or(|p| p(key));
4014            if want != shown.get() {
4015                shown.set(want);
4016                // The chrome mirror, so the pane's own commands leave the bar with the pane.
4017                if let Some(sig) = mirror.get() {
4018                    sig.set(want);
4019                }
4020                with_tree(|t| t.patch(host, Box::new(NavPatch::ListVisible(want)), false));
4021            }
4022        })
4023    };
4024    if native_list && let Some(build_list) = list_build.clone() {
4025        let page = nav_page(
4026            host,
4027            &NavPageProps {
4028                title: title_s.clone(),
4029                pane: Pane::List,
4030                immersive: false,
4031            },
4032            &sizes,
4033        );
4034        list_cell.set(Some(page));
4035        // The pane collapses for a destination that spans the whole detail area
4036        // (`content_list_for`), and a collapsed pane's commands must leave the bar with it
4037        // (docs/toolbars.md); otherwise a full-page section shows the list's Add and Filter.
4038        // Reactive, so a collapse re-composes the bar: the Cell above is what `NavLayout` reads
4039        // during layout, and this mirrors it for the chrome.
4040        let visible = Signal::new(initial_list_visible);
4041        list_visible_sig.set(Some(visible));
4042        // Two ways this pane stops being what the user is looking at: the destination collapses
4043        // it (`content_list_for`), or, on a shape that shows one pane at a time, a detail is
4044        // pushed over it. Its Add and Filter act on a list that is then behind the editor, so
4045        // they leave the bar with it (docs/toolbars.md). Side by side, both panes are up and
4046        // both keep their commands.
4047        let (dv, pres_sig) = (detail_visible, presentation_sig);
4048        // `try_get`: a gate is asked at merge time, which can be a window's teardown; a
4049        // disposed signal answers "not showing" rather than panicking (docs/toolbars.md).
4050        let gate: Rc<dyn Fn() -> bool> = Rc::new(move || {
4051            visible.try_get().unwrap_or(false)
4052                && (pres_sig
4053                    .try_get()
4054                    .is_some_and(day_spec::props::NavPresentation::is_split)
4055                    || dv.is_none_or(|d| !d.try_get().unwrap_or(false)))
4056        });
4057        with_nav_host(None, || {
4058            day_core::with_page_gated(page, Some(gate), day_spec::ToolbarColumn::List, || {
4059                let mut pcx = BuildCx::new(page);
4060                let _ = build_list().build(&mut pcx);
4061            });
4062        });
4063    }
4064    // The composed content list (`Cap::NavContentList` Unsupported): every list-backed
4065    // destination page carries the pane itself, beside the content while split and as the
4066    // root of a two-layer push flow while compact (the gated detail above). The
4067    // presentation is read through the signal, so a live morph re-arranges the page without
4068    // the host's involvement.
4069    let compose: Option<DestFn<K>> = if let (Some(list), true) = (list_build.clone(), !native_list)
4070    {
4071        let pred = list_pred.clone();
4072        let width = sel.content_list_width;
4073        let dv = detail_visible;
4074        let items_c = items.clone();
4075        // The live rows, for a data-driven key's title: only a static item carries a
4076        // `TextSource` of its own, and without these a row from `.items` titled its pushed page
4077        // with its raw key ("feed:5756…") instead of the name the row shows.
4078        let (typed_c, titles_c) = (typed.clone(), titles.clone());
4079        let pres = presentation_sig;
4080        let win = window;
4081        let host_cx_g = host_cx.clone();
4082        let detail_title_g = detail_title.clone();
4083        Some(Rc::new(move |key: &K| {
4084            if pred.as_ref().is_some_and(|p| !p(key)) {
4085                return items_c.build_page(key);
4086            }
4087            let (l1, l2) = (list.clone(), list.clone());
4088            let (i1, i2) = (items_c.clone(), items_c.clone());
4089            let (k1, k2) = (key.clone(), key.clone());
4090            let (hc, dt) = (host_cx_g.clone(), detail_title_g.clone());
4091            let (tk, tt) = (typed_c.clone(), titles_c.clone());
4092            let ba = gated_toolbar.clone();
4093            // Each arm rebuilds in this destination's page: a morph re-runs the `when` long after
4094            // the page was built, and an arm built outside it registers the list's commands
4095            // without the page's gate (a narrowed tablet then showed Items' Add on Settings).
4096            // Captured when the page builds: the destination is constructed before its page frame
4097            // is entered.
4098            let page: Rc<RefCell<Option<PageContext>>> = Rc::default();
4099            let at_build = page.clone();
4100            let arms = when(
4101                move || {
4102                    let p = pres.get();
4103                    // Side by side only where there is room for two columns.
4104                    // `rows_are_chrome()` alone is not that question: under the adaptive
4105                    // ladder a tab bar is the compact rung, and pairing a 320pt list with an
4106                    // editor across a phone leaves neither usable, which is what a scaffold
4107                    // that wanted tabs on a phone got. A pinned tab bar on a wide window
4108                    // still earns the pair, so the width is asked rather than the style.
4109                    p.is_split()
4110                        || (p.rows_are_chrome()
4111                            && day_core::window_size_class(win)
4112                                .is_some_and(day_spec::SizeClass::prefers_split))
4113                },
4114                {
4115                    let page = page.clone();
4116                    move || {
4117                        let (l, i, k) = (l1.clone(), i1.clone(), k1.clone());
4118                        PageContext::enter(
4119                            &page,
4120                            row((
4121                                l().width(width).grow(Dimension::Height),
4122                                i.build_page(&k).grow(Dimension::Both),
4123                            ))
4124                            .grow(Dimension::Both),
4125                        )
4126                    }
4127                },
4128            )
4129            .otherwise(move || {
4130                let (l, i, k) = (l2.clone(), i2.clone(), k2.clone());
4131                PageContext::enter(
4132                    &page,
4133                    match dv {
4134                        // The gated two-layer flow (docs/navigation.md): a nested navigation
4135                        // host in a chrome presentation, a push onto the enclosing host in a
4136                        // stacked one; either way a navigation bar, a title, and a native
4137                        // back, where an in-place swap had none.
4138                        Some(d) => {
4139                            let retitle = i.static_title(&k.key());
4140                            let title = retitle
4141                                .as_ref()
4142                                .map(TextSource::initial)
4143                                .or_else(|| {
4144                                    let at = tk.borrow().iter().position(|x| x.key() == k.key())?;
4145                                    tt.borrow().get(at).cloned()
4146                                })
4147                                .unwrap_or_else(|| k.title());
4148                            gated_detail_piece(
4149                                GatedDetail {
4150                                    open: d,
4151                                    list: l,
4152                                    items: i,
4153                                    key: k,
4154                                    title,
4155                                    retitle,
4156                                    detail_title: dt.clone(),
4157                                    host_cx: hc.clone(),
4158                                    toolbar: ba.clone(),
4159                                },
4160                                pres,
4161                                win,
4162                            )
4163                        }
4164                        None => i.build_page(&k),
4165                    },
4166                )
4167            });
4168            AnyPiece::new(piece_fn(move |cx| {
4169                at_build.replace(Some(PageContext::current()));
4170                arms.build(cx)
4171            }))
4172        }))
4173    } else {
4174        None
4175    };
4176
4177    let sync_menu = {
4178        let mh = menu_holder.clone();
4179        move |idx: Option<usize>| {
4180            if let Some(m) = mh.get() {
4181                with_tree(|t| t.patch(m, Box::new(NavMenuPatch::Selected(idx)), false));
4182            }
4183            // And onto the host, which is the node `.id()` names: a script asserting on a
4184            // nav addresses the nav, not the row list nested inside it. Every path that
4185            // changes the selection lands here, so this is the one place that has to record it.
4186            with_tree(|t| t.set_probe_selected(host, idx));
4187        }
4188    };
4189
4190    // Detail pages, and how long they live.
4191    //
4192    // A presentation whose rows are the chrome (a tab bar, a rail) keeps every visited page
4193    // resident: switching tabs is `NavPatch::Select`, nothing is torn down, and each tab keeps
4194    // its scroll offset, its focused field, and its animations, which is what every native tab
4195    // container does. A split or stacked presentation keeps only the shown page and switches by
4196    // pop-then-push, which is what it did before adaptive navigation existed.
4197    //
4198    // Residency follows the presentation rather than the host. Making every nav page resident
4199    // would keep effects running for pages nobody is looking at and change the disposal
4200    // contract the docs make ("leaving the piece's branch disposes"); making none resident
4201    // would rebuild a tab's content on every tap. Splitting it this way means a morph only
4202    // ever disposes pages that are not on screen, or lazily builds ones that were not built
4203    // yet; the visible page is never rebuilt, which is the invariant a morph has to keep.
4204    let resident: Rc<RefCell<Vec<ResidentPage>>> = Rc::default();
4205    let current: Rc<RefCell<Option<String>>> = Rc::default();
4206    let nav_scope = Scope::current();
4207    // Shared: Both the selection bind and the row-derive effect drive the detail (see the
4208    // derive effect for why the selection bind alone is not enough).
4209    let show = std::rc::Rc::new({
4210        let (items, resident, current, sizes, typed_s, titles_s) = (
4211            items.clone(),
4212            resident.clone(),
4213            current.clone(),
4214            sizes.clone(),
4215            typed.clone(),
4216            titles.clone(),
4217        );
4218        let (sync_menu, owners, host_cx, selection, pres) = (
4219            sync_menu.clone(),
4220            owners.clone(),
4221            host_cx.clone(),
4222            selection.clone(),
4223            presentation_cell.clone(),
4224        );
4225        let (list_pred_s, list_in_stack_s) = (list_pred.clone(), list_in_stack.clone());
4226        let apply_list_visible_s = apply_list_visible.clone();
4227        let compose_s = compose.clone();
4228        let detail_title_s = detail_title.clone();
4229        move |key: &str| {
4230            if current.borrow().as_deref() == Some(key) {
4231                return;
4232            }
4233            let chrome = pres.get().rows_are_chrome();
4234            // The list interposes between the sidebar root and the detail exactly while a
4235            // merged-pane backend is stacked and the app gates the detail
4236            // (docs/navigation.md). Split-family presentations show the detail beside the
4237            // list, empty state and all.
4238            let gated =
4239                merged_list && pres.get() == NavPresentation::Stack && detail_visible.is_some();
4240            if !chrome {
4241                // Stacked or split: the outgoing page goes away. Dispose its scope first: a
4242                // merged inner stack's cleanup pops its pages (which sit on top natively) before
4243                // we pop the detail itself, so the native pop order stays top-down (iOS pops the
4244                // topmost VC; Android's inclusive pop unwinds everything above an entry).
4245                if let Some(p) = resident.borrow_mut().pop() {
4246                    p.scope.dispose();
4247                    with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4248                    owners.borrow_mut().pop();
4249                    sizes.borrow_mut().remove(&p.node);
4250                    with_tree(|t| {
4251                        t.remove_subtree(p.node);
4252                        t.mark_layout_dirty();
4253                        t.layout_if_needed();
4254                    });
4255                }
4256            }
4257            *current.borrow_mut() = None;
4258            if key.is_empty() {
4259                // Deselected: the list layer (if interposed) leaves the stack with the detail.
4260                if list_in_stack_s.get() {
4261                    list_in_stack_s.set(false);
4262                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
4263                    owners.borrow_mut().pop();
4264                }
4265                sync_menu(None);
4266                return;
4267            }
4268            let idx = typed_s.borrow().iter().position(|k| k.key() == key);
4269            let Some(idx) = idx else {
4270                sync_menu(None);
4271                return;
4272            };
4273            let typed_key_now = typed_s.borrow()[idx].clone();
4274            // The pane's visibility is settled for every destination change, including the
4275            // resident case below: a chrome presentation builds every destination, so the
4276            // last one built would otherwise be the one that had the final word.
4277            apply_list_visible_s(&typed_key_now);
4278            // Already built and still alive: the resident case. Nothing to build, nothing to
4279            // push: tell the host which of its pages to show and we are done.
4280            if let Some(i) = resident.borrow().iter().position(|p| p.key == key) {
4281                with_tree(|t| {
4282                    t.patch(host, Box::new(NavPatch::Select(i)), false);
4283                    t.mark_layout_dirty();
4284                    t.layout_if_needed();
4285                });
4286                *current.borrow_mut() = Some(key.to_string());
4287                sync_menu(Some(idx));
4288                return;
4289            }
4290            let typed_key = typed_key_now;
4291            let title_now = titles_s.borrow()[idx].clone();
4292            // Per-destination pane visibility (`content_list_for`): a full-width destination
4293            // collapses the pane, a list-backed one brings it back. `interposed` = this
4294            // destination puts the list between the sidebar root and its detail (a stacked
4295            // merged-pane backend, docs/navigation.md).
4296            let want = native_list && list_pred_s.as_ref().is_none_or(|p| p(&typed_key));
4297            let interposed = gated && want;
4298            if native_list {
4299                if interposed && !list_in_stack_s.get() {
4300                    // Interpose the list above the sidebar root, with its own back owner
4301                    // (back from the list = deselect).
4302                    list_in_stack_s.set(true);
4303                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
4304                    let s = selection.clone();
4305                    owners.borrow_mut().push(Rc::new(move |_already_popped| {
4306                        if let Some(root) = K::from_key("") {
4307                            s.write(root);
4308                        }
4309                    }) as PopOwner);
4310                } else if gated && !want && list_in_stack_s.get() {
4311                    // A full-width destination while stacked: the list leaves the stack so its
4312                    // page sits directly on the sidebar root and back deselects.
4313                    list_in_stack_s.set(false);
4314                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
4315                    owners.borrow_mut().pop();
4316                }
4317                // The detail waits for `detail_visible`: the list is the top of the stack
4318                // until the app opens a row. The selection is recorded as current; the
4319                // `detail_visible` bind re-enters here to perform the deferred push.
4320                if interposed && !detail_visible.expect("gated implies Some").peek() {
4321                    // A selected list can still be offstage after UIKit's initial collapse.
4322                    // Route changes must present it too, without adding another back owner.
4323                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
4324                    *current.borrow_mut() = Some(key.to_string());
4325                    sync_menu(Some(idx));
4326                    return;
4327                }
4328            }
4329            // A static item retitles on locale change (its TextSource); a data-driven key uses
4330            // the resolved snapshot (its title tracks the items signal, not the locale). A
4331            // list-backed destination on a host that places the pane natively is the detail
4332            // layer, so the app's `detail_title` names it where one is set: the layer shows
4333            // an item, not the section (docs/navigation.md).
4334            let (page_title, retitle) = match &detail_title_s {
4335                Some(dt) if want => (dt.initial(), Some(dt.clone())),
4336                _ => (title_now.clone(), items.static_title(key)),
4337            };
4338            let page = nav_page(
4339                host,
4340                &NavPageProps {
4341                    title: page_title.clone(),
4342                    pane: Pane::Detail,
4343                    immersive: items.immersive_of(&typed_key.key()),
4344                },
4345                &sizes,
4346            );
4347            if !chrome {
4348                // The detail page's back action: with the list interposed, back from the
4349                // detail returns to the list (`detail_visible` := false); classically it
4350                // deselects (returns to the sidebar rows). Pushed before the content builds,
4351                // so a merged inner stack's page owners stack on top of it. A chrome
4352                // presentation has no back stack to own; a tab bar never pops.
4353                let owner: PopOwner = if interposed && let Some(dv) = detail_visible {
4354                    Rc::new(move |_already_popped| {
4355                        dv.set(false);
4356                    })
4357                } else {
4358                    let s = selection.clone();
4359                    Rc::new(move |_already_popped| {
4360                        if let Some(root) = K::from_key("") {
4361                            s.write(root);
4362                        }
4363                    })
4364                };
4365                owners.borrow_mut().push(owner);
4366                // Present the page before its content builds. Anything the content pushes
4367                // onto this same host while building (a composed gated detail whose signal
4368                // is already true, a merged stack's restored path) must land above this
4369                // page, and a backend that presents pages in patch order (Android presents
4370                // the most recently added) would otherwise show them inverted. `immersive_of`
4371                // runs out here for the usual reason: it can run app code, which must not
4372                // happen inside `with_tree`.
4373                let immersive = items.immersive_of(&typed_key.key());
4374                with_tree(|t| {
4375                    t.patch(
4376                        host,
4377                        Box::new(NavPatch::Pushed {
4378                            title: page_title.clone(),
4379                            immersive,
4380                        }),
4381                        false,
4382                    );
4383                });
4384            }
4385            let scope = nav_scope.enter(Scope::child);
4386            scope.enter(|| {
4387                // Inside the page's scope; see the pushed-detail site above.
4388                let content = match &compose_s {
4389                    Some(c) => c(&typed_key),
4390                    None => items.build_page(&typed_key),
4391                };
4392                // A resident page is a merge barrier: a `nav_stack` inside a tab keeps its own
4393                // native container rather than pushing onto the enclosing host, because the
4394                // enclosing host is not a stack (docs/navigation.md).
4395                let inner = if chrome { None } else { Some(host_cx.clone()) };
4396                // The page's own commands ride the window's bar only while it is the page
4397                // showing (docs/toolbars.md): a resident tab that is not in front, and a
4398                // destination the selection has moved off, both leave the bar.
4399                let sel_gate = Some(destination_gate(selection.clone(), key.to_string()));
4400                let build = || {
4401                    with_nav_host(inner, || {
4402                        day_core::with_page_in(
4403                            page,
4404                            sel_gate.clone(),
4405                            day_spec::ToolbarColumn::Detail,
4406                            window,
4407                            || {
4408                                let mut c = BuildCx::new(page);
4409                                let _ = content.build(&mut c);
4410                            },
4411                        );
4412                    });
4413                };
4414                if chrome {
4415                    // Resident, so anything this page builds outlives the switch away from it and
4416                    // has to say whether it is selected. Read the selection itself: a route link
4417                    // can switch tabs and enter a nested route in one batched event, before the
4418                    // presentation effect updates `current`.
4419                    with_page_active(destination_gate(selection.clone(), key.to_string()), build);
4420                } else {
4421                    build();
4422                }
4423            });
4424            resident.borrow_mut().push(ResidentPage {
4425                key: key.to_string(),
4426                scope,
4427                node: page,
4428            });
4429            let at = resident.borrow().len() - 1;
4430            // A stacked page was presented above, before its content; the resident case
4431            // selects after the build, because the page must exist to be shown.
4432            if chrome {
4433                with_tree(|t| t.patch(host, Box::new(NavPatch::Select(at)), false));
4434            }
4435            with_tree(|t| {
4436                t.mark_layout_dirty();
4437                t.layout_if_needed();
4438            });
4439            // Live retitle for a static item: its title source re-resolves on locale change and
4440            // the host's native bar follows via `NavPatch::Title`. Scope-owned, dies with the page.
4441            if let Some(rt) = retitle {
4442                scope.enter(|| {
4443                    rt.bind_to(host, |t| Box::new(NavPatch::Title(t)), false);
4444                });
4445            }
4446            *current.borrow_mut() = Some(key.to_string());
4447            sync_menu(Some(idx));
4448        }
4449    });
4450
4451    // Neither a split nor a tab bar can draw "nothing selected": a split has no way to fill the
4452    // detail pane, and a tab bar always has one tab active. Both default to the first item. Only
4453    // a stack has an empty state, and there it is wanted: the collapsed list the user has not
4454    // chosen from yet. A host with a native content list joins the default-selection rule at
4455    // every presentation: the pane needs a selection to scope itself to, and a collapsed
4456    // merged-pane host opens on the list rather than on bare rows.
4457    if (split || presentation.rows_are_chrome() || native_list)
4458        && selection.peek().key().is_empty()
4459        && let Some(k) = typed.borrow().first().cloned()
4460    {
4461        selection.write(k);
4462    }
4463    // Build every destination, then re-select the current one.
4464    //
4465    // A tab bar needs an item per destination up front: `UITabBarController` and Material's
4466    // navigation bar both build their chrome from the full set, so a page nobody has visited yet
4467    // is a tab that is not there. Lazy building is right for a split or a stack, where only
4468    // the shown page is drawn; where the rows are the chrome, the rows have to be complete.
4469    //
4470    // This runs before the selection bind below, and that order is the contract with the
4471    // chrome backends: `NavPatch::Select` names a page by attach order, while the chrome draws
4472    // the rows, so a suite can only pair the two when page i is row i. Letting the bind build the
4473    // selected destination first breaks that: restoring a saved section (`.restore`, which
4474    // android-material installs for every app as its instance-state contract) rebuilds with a
4475    // non-first selection, whose page then attaches at 0 and highlights row 0.
4476    let build_all = {
4477        let (show, typed_a, sel_a) = (show.clone(), typed.clone(), selection.clone());
4478        Rc::new(move || {
4479            let keys: Vec<String> = typed_a.borrow().iter().map(Route::key).collect();
4480            for k in keys {
4481                show(&k);
4482            }
4483            show(&sel_a.peek().key());
4484        })
4485    };
4486    if presentation.rows_are_chrome() {
4487        build_all();
4488    }
4489    {
4490        let (s, show) = (selection.clone(), show.clone());
4491        bind(move || s.read().key(), move |key: &String| show(key));
4492    }
4493
4494    // `detail_visible`, both directions (docs/navigation.md). Only the stacked merged-pane
4495    // shape reacts here: `true` performs the deferred detail push for the current selection,
4496    // `false` pops back to the interposed list. Split-family presentations ignore the signal:
4497    // their detail pane is always on screen (native back never runs a detail owner there).
4498    if let Some(dv) = detail_visible {
4499        let (show_dv, current_dv, resident_dv, sizes_dv, owners_dv) = (
4500            show.clone(),
4501            current.clone(),
4502            resident.clone(),
4503            sizes.clone(),
4504            owners.clone(),
4505        );
4506        let (pres_dv, list_in_stack_dv) = (presentation_cell.clone(), list_in_stack.clone());
4507        bind(
4508            move || dv.get(),
4509            move |v: &bool| {
4510                let gated_now = merged_list
4511                    && pres_dv.get() == NavPresentation::Stack
4512                    && list_in_stack_dv.get();
4513                if !gated_now {
4514                    return;
4515                }
4516                if *v {
4517                    let key = current_dv.borrow().clone();
4518                    if resident_dv.borrow().is_empty()
4519                        && let Some(k) = key
4520                    {
4521                        // Deferred push: `show` re-runs for the recorded selection, sees the
4522                        // signal true, and performs the build it withheld.
4523                        *current_dv.borrow_mut() = None;
4524                        show_dv(&k);
4525                    }
4526                } else if let Some(p) = resident_dv.borrow_mut().pop() {
4527                    p.scope.dispose();
4528                    with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4529                    owners_dv.borrow_mut().pop();
4530                    sizes_dv.borrow_mut().remove(&p.node);
4531                    with_tree(|t| {
4532                        t.remove_subtree(p.node);
4533                        t.mark_layout_dirty();
4534                        t.layout_if_needed();
4535                    });
4536                }
4537            },
4538        );
4539    }
4540
4541    // A detail open beside its list closes before the section is left (docs/navigation.md). Where
4542    // the list is composed into the destination's page, the platform's back would pop that whole
4543    // page, list and detail together, so while a detail is open side by side this host routes the
4544    // native back through Day (`NavHostCx::vote_guard`) and the back handler below closes the
4545    // detail instead. A native pane is a column of its own, which no native back pops.
4546    let beside: Rc<Cell<bool>> = Rc::default();
4547    if let Some(dv) = detail_visible
4548        && list_build.is_some()
4549        && !native_list
4550    {
4551        let (hc, s, pred, beside) = (
4552            host_cx.clone(),
4553            selection.clone(),
4554            list_pred.clone(),
4555            beside.clone(),
4556        );
4557        bind(
4558            move || {
4559                let k = s.read();
4560                dv.get()
4561                    && presentation_sig.get().is_split()
4562                    && !k.key().is_empty()
4563                    && pred.as_ref().is_none_or(|p| p(&k))
4564            },
4565            move |want: &bool| {
4566                if *want != beside.get() {
4567                    beside.set(*want);
4568                    hc.vote_guard(*want);
4569                }
4570            },
4571        );
4572    }
4573
4574    // What a presentation change means for the model, whoever caused it. Widening with nothing
4575    // selected would leave the detail pane empty, the one state a split presentation has no way
4576    // to draw, so adopt the same first-item rule the build uses. Narrowing keeps the selection
4577    // instead: the detail becomes the top of the stack, which is where the user already was.
4578    let reconcile = {
4579        let (pc, sel_r, typed_r, split_r) = (
4580            presentation_cell.clone(),
4581            selection.clone(),
4582            typed.clone(),
4583            split_cell.clone(),
4584        );
4585        let build_all_r = build_all.clone();
4586        let (resident_r, current_r, sizes_r, owners_r) = (
4587            resident.clone(),
4588            current.clone(),
4589            sizes.clone(),
4590            owners.clone(),
4591        );
4592        let (list_pred_r, list_in_stack_r, show_r) =
4593            (list_pred.clone(), list_in_stack.clone(), show.clone());
4594        let apply_list_visible_r = apply_list_visible.clone();
4595        Rc::new(move |next: NavPresentation| {
4596            let was_chrome = pc.get().rows_are_chrome();
4597            pc.set(next);
4598            split_r.set(next.is_split());
4599            presentation_sig.set(next);
4600            // Leaving a chrome presentation: the resident pages nobody can see any more go away,
4601            // because a split or stacked host draws exactly one detail page. The shown page is
4602            // kept (rebuilding what the user is looking at is the one thing a morph must never
4603            // do) and is left as the sole entry, so it reads as the top of the new stack.
4604            //
4605            // Entering a chrome presentation needs no counterpart: the shown page is already
4606            // resident, and the others build lazily when they are first selected.
4607            if was_chrome && !next.rows_are_chrome() {
4608                let shown = current_r.borrow().clone();
4609                let gone: Vec<ResidentPage> = {
4610                    let mut r = resident_r.borrow_mut();
4611                    let (keep, drop): (Vec<_>, Vec<_>) =
4612                        r.drain(..).partition(|p| Some(&p.key) == shown.as_ref());
4613                    *r = keep;
4614                    drop
4615                };
4616                for p in gone {
4617                    p.scope.dispose();
4618                    sizes_r.borrow_mut().remove(&p.node);
4619                    with_tree(|t| t.remove_subtree(p.node));
4620                }
4621                // The kept page now owns the one back affordance the stack presentation offers.
4622                owners_r.borrow_mut().clear();
4623                if let Some(k) = shown {
4624                    let s = sel_r.clone();
4625                    let owner: PopOwner = Rc::new(move |_already_popped| {
4626                        if let Some(root) = K::from_key("") {
4627                            s.write(root);
4628                        }
4629                    });
4630                    owners_r.borrow_mut().push(owner);
4631                    let _ = k;
4632                }
4633                with_tree(|t| {
4634                    t.mark_layout_dirty();
4635                    t.layout_if_needed();
4636                });
4637            }
4638            if !was_chrome && next.rows_are_chrome() {
4639                // Entering a chrome presentation: the rows become the chrome, so every
4640                // destination needs its page for the bar to be complete.
4641                build_all_r();
4642            }
4643            if (next.is_split() || next.rows_are_chrome() || native_list)
4644                && sel_r.peek().key().is_empty()
4645                && let Some(k) = typed_r.borrow().first().cloned()
4646            {
4647                sel_r.write(k);
4648            }
4649            // Content-list settlement (docs/navigation.md). The pane's own visibility comes
4650            // first and applies to every backend that places the pane itself: entering a chrome
4651            // presentation builds every destination, and a destination without a list collapses
4652            // the pane on its way past, so the shape that comes next has to state the selected
4653            // destination's answer again.
4654            if native_list
4655                && let Some(k) = typed_r
4656                    .borrow()
4657                    .iter()
4658                    .find(|x| Some(&x.key()) == current_r.borrow().as_ref())
4659                    .cloned()
4660            {
4661                apply_list_visible_r(&k);
4662            }
4663            // Narrowing into the gated stack interposes the list for the current selection and
4664            // retracts a detail the app is not showing; widening back restores the always-on
4665            // detail beside the pane. The owner stack is rebuilt for the new shape, because the
4666            // old owners named the old one.
4667            if merged_list && let Some(dv) = detail_visible {
4668                if next == NavPresentation::Stack {
4669                    let key = current_r.borrow().clone();
4670                    let want = key.as_ref().is_some_and(|k| {
4671                        typed_r
4672                            .borrow()
4673                            .iter()
4674                            .find(|x| &x.key() == k)
4675                            .is_some_and(|tk| list_pred_r.as_ref().is_none_or(|p| p(tk)))
4676                    });
4677                    if want {
4678                        if !list_in_stack_r.get() {
4679                            list_in_stack_r.set(true);
4680                            with_tree(|t| {
4681                                t.patch(host, Box::new(NavPatch::ListInStack(true)), false);
4682                            });
4683                        }
4684                        owners_r.borrow_mut().clear();
4685                        let s = sel_r.clone();
4686                        owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4687                            if let Some(root) = K::from_key("") {
4688                                s.write(root);
4689                            }
4690                        }) as PopOwner);
4691                        if dv.peek() {
4692                            // The detail stays on top of the interposed list; its back now
4693                            // returns to the list, not to the rows.
4694                            owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4695                                dv.set(false);
4696                            }) as PopOwner);
4697                        } else if let Some(p) = resident_r.borrow_mut().pop() {
4698                            // The app is not showing a detail: the list is the top.
4699                            p.scope.dispose();
4700                            with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
4701                            sizes_r.borrow_mut().remove(&p.node);
4702                            with_tree(|t| {
4703                                t.remove_subtree(p.node);
4704                                t.mark_layout_dirty();
4705                                t.layout_if_needed();
4706                            });
4707                        }
4708                    }
4709                } else if next.is_split() {
4710                    // The backend's expand lifted the list back into its own pane.
4711                    list_in_stack_r.set(false);
4712                    let key = current_r.borrow().clone();
4713                    if resident_r.borrow().is_empty()
4714                        && let Some(k) = key
4715                    {
4716                        // The detail was withheld while gated; a split shows it always.
4717                        *current_r.borrow_mut() = None;
4718                        show_r(&k);
4719                    } else if !resident_r.borrow().is_empty() {
4720                        owners_r.borrow_mut().clear();
4721                        let s = sel_r.clone();
4722                        owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
4723                            if let Some(root) = K::from_key("") {
4724                                s.write(root);
4725                            }
4726                        }) as PopOwner);
4727                    }
4728                }
4729            }
4730        })
4731    };
4732
4733    if requested.is_none() && can_split && we_drive {
4734        // We drive (docs/size-classes.md). Seeded with what we just built, so the first run is a
4735        // no-op; after that a class change patches the live host and the backend re-homes the
4736        // pages it already has. Nothing here rebuilds a page, which is what keeps scroll offsets,
4737        // field focus, and the search query across the morph.
4738        let rec = reconcile.clone();
4739        bind_seeded(
4740            presentation,
4741            move || resolve(day_core::window_size_class(window)),
4742            move |next: &NavPresentation| {
4743                with_tree(|t| {
4744                    t.patch(host, Box::new(NavPatch::Presentation(*next)), false);
4745                    t.mark_layout_dirty();
4746                    t.layout_if_needed();
4747                });
4748                rec(*next);
4749            },
4750        );
4751    } else if toolkit_drives {
4752        // The toolkit drives: its own adaptive container already morphed and is telling us after
4753        // the fact, so there is nothing to patch, only the model to reconcile. Pushing a
4754        // presentation at it instead would be a second owner of the presentation racing the
4755        // platform's collapse animation.
4756        let rec = reconcile.clone();
4757        cx.on(host, move |ev| {
4758            if let Event::NavPresentationChanged(next) = ev {
4759                rec(*next);
4760                with_tree(|t| {
4761                    t.mark_layout_dirty();
4762                    t.layout_if_needed();
4763                });
4764            }
4765        });
4766    }
4767
4768    let icon_progress_enabled = icon_progress.is_some();
4769    let documents = sel.documents.is_some();
4770    let retain_selection = sel.retain_selection;
4771    // Re-derive the row set when a dynamic block's signal changes (re-patch the native menu,
4772    // reset the selection if its item vanished) and when the locale changes (tracked title
4773    // resolution: same keys, new titles). Installed unconditionally: a fully static
4774    // nav's derive subscribes to nothing and this effect never re-fires.
4775    {
4776        let (items_e, typed_e, titles_e, mh_e, sel_e) = (
4777            items.clone(),
4778            typed.clone(),
4779            titles.clone(),
4780            menu_holder.clone(),
4781            selection.clone(),
4782        );
4783        // The live presentation, not the build-time one: this effect outlives a morph, and what
4784        // "must never show an empty detail" means changes with it.
4785        let (show_e, pres_e) = (show.clone(), presentation_cell.clone());
4786        // Seeded with the rows the menu was realized with.
4787        let last_rows: RefCell<Option<ShownRows>> = RefCell::new(Some(shown0));
4788        let (resident_e, current_e, sizes_e) = (resident.clone(), current.clone(), sizes.clone());
4789        let movable_e = movable_of.clone();
4790        bind(
4791            move || {
4792                // Tracked derive: subscribes to every dynamic block's signal.
4793                let NavRows {
4794                    keys: k,
4795                    titles: t,
4796                    icons: i,
4797                    badges: b,
4798                    badge_icons: bi,
4799                    badge_tints: bt,
4800                    section_ids: _,
4801                    sections: sc,
4802                    tints: tn,
4803                    menus: mn,
4804                } = items_e.derive();
4805                (
4806                    k.iter().map(Route::key).collect::<Vec<_>>(),
4807                    k,
4808                    t,
4809                    i,
4810                    b,
4811                    sc,
4812                    tn,
4813                    mn,
4814                    bi,
4815                    bt,
4816                )
4817            },
4818            move |(key_strs, keys, ts, ics, bs, scs, tns, mns, bis, bts): &DerivedRows<K>| {
4819                // Same rows as the last patch, with only their words or decorations moved?
4820                let rows_changed = {
4821                    let mut last = last_rows.borrow_mut();
4822                    let changed = last.as_ref().and_then(|l: &ShownRows| {
4823                        (l.keys == *key_strs && l.sections == *scs && l.menus == *mns).then(|| {
4824                            (0..key_strs.len())
4825                                .filter(|&i| {
4826                                    l.titles[i] != ts[i]
4827                                        || l.icons[i] != ics[i]
4828                                        || l.tints[i] != tns[i]
4829                                        || l.badges[i] != bs[i]
4830                                        || l.badge_icons[i] != bis[i]
4831                                        || l.badge_tints[i] != bts[i]
4832                                })
4833                                .collect::<Box<[usize]>>()
4834                        })
4835                    });
4836                    *last = Some(ShownRows {
4837                        keys: key_strs.clone(),
4838                        titles: ts.clone(),
4839                        icons: ics.clone(),
4840                        badges: bs.clone(),
4841                        badge_icons: bis.clone(),
4842                        badge_tints: bts.clone(),
4843                        sections: scs.clone(),
4844                        tints: tns.clone(),
4845                        menus: mns.clone(),
4846                    });
4847                    changed
4848                };
4849                (*typed_e.borrow_mut()).clone_from(keys);
4850                (*titles_e.borrow_mut()).clone_from(ts);
4851                let selected_key = sel_e.peek();
4852                let cur = selected_key.key();
4853                let retain = !cur.is_empty()
4854                    && !key_strs.contains(&cur)
4855                    && retain_selection
4856                        .as_ref()
4857                        .is_some_and(|keep| keep(&selected_key));
4858                // A resident page whose row is gone has nothing left to select it, so it would
4859                // sit alive and invisible for the life of the surface, and shift every
4860                // `NavPatch::Select` index past it. Drop it here, where the new row set is known.
4861                // Only reachable in a chrome presentation; elsewhere at most one page is resident
4862                // and the selection reset below takes care of it.
4863                {
4864                    let stale: Vec<ResidentPage> = {
4865                        let mut r = resident_e.borrow_mut();
4866                        let (keep, drop): (Vec<_>, Vec<_>) = r
4867                            .drain(..)
4868                            .partition(|p| key_strs.contains(&p.key) || (retain && p.key == cur));
4869                        *r = keep;
4870                        drop
4871                    };
4872                    if !stale.is_empty() {
4873                        if current_e
4874                            .borrow()
4875                            .as_ref()
4876                            .is_some_and(|c| stale.iter().any(|p| &p.key == c))
4877                        {
4878                            *current_e.borrow_mut() = None;
4879                        }
4880                        for p in stale {
4881                            p.scope.dispose();
4882                            sizes_e.borrow_mut().remove(&p.node);
4883                            with_tree(|t| t.remove_subtree(p.node));
4884                        }
4885                        with_tree(|t| {
4886                            t.mark_layout_dirty();
4887                            t.layout_if_needed();
4888                        });
4889                    }
4890                }
4891                // If the selected key is gone, reset (Option key → None); else keep it selected.
4892                let still = retain || cur.is_empty() || key_strs.iter().any(|k| k == &cur);
4893                if !still && let Some(root) = K::from_key("") {
4894                    sel_e.write(root);
4895                }
4896                // A split view must never show an empty detail. The build-time fallback ran
4897                // once, before any filtering, so re-apply it here: when the selected row is
4898                // gone, move to the first row that survived rather than blanking the pane.
4899                let mut cur2 = sel_e.peek().key();
4900                let pres_now = pres_e.get();
4901                // A collapsed native content list may have returned to its sidebar root.
4902                // Background count changes and filtering are not navigation requests: keep
4903                // that empty selection until a row tap or an explicit route activates it.
4904                if (pres_now.is_split()
4905                    || pres_now.rows_are_chrome()
4906                    || (native_list && pres_now != NavPresentation::Stack))
4907                    && cur2.is_empty()
4908                    && let Some(k) = keys.first().cloned()
4909                {
4910                    sel_e.write(k.clone());
4911                    cur2 = k.key();
4912                }
4913                let selected = key_strs.iter().position(|k| k == &cur2);
4914                if let Some(m) = mh_e.get() {
4915                    with_tree(|t| {
4916                        t.patch(
4917                            m,
4918                            Box::new(day_spec::props::NavMenuPatch::Items {
4919                                rows_changed: rows_changed.clone(),
4920                                document_keys: if documents {
4921                                    key_strs.clone()
4922                                } else {
4923                                    Vec::new()
4924                                }
4925                                .into_boxed_slice(),
4926                                items: ts.clone(),
4927                                icons: ics.clone(),
4928                                badges: bs.clone(),
4929                                badge_icons: bis.clone(),
4930                                badge_tints: bts.clone(),
4931                                sections: scs.clone(),
4932                                tints: tns.clone(),
4933                                menus: mns.clone(),
4934                                movable: movable_e.as_ref().map_or_default(|r| {
4935                                    keys.iter().map(|k| r.drag(k) != NavDrag::Fixed).collect()
4936                                }),
4937                                sorted: match &movable_e {
4938                                    Some(r @ SidebarDrag::Regroup(_)) => {
4939                                        keys.iter().map(|k| r.drag(k) == NavDrag::Regroup).collect()
4940                                    }
4941                                    _ => Vec::new(),
4942                                },
4943                                selected,
4944                            }),
4945                            false,
4946                        );
4947                    });
4948                }
4949                // Re-map active route keys after insertions/filtering, after the row patch.
4950                if icon_progress_enabled {
4951                    progress_revision.update(|n| *n = n.wrapping_add(1));
4952                }
4953                // Document collections can add in the background and reorder existing keys.
4954                // Realize missing pages first, then move the same native objects into key order.
4955                if pres_now.rows_are_chrome() {
4956                    for key in key_strs {
4957                        let missing = !resident_e.borrow().iter().any(|p| &p.key == key);
4958                        if missing {
4959                            show_e(key);
4960                        }
4961                    }
4962                    let order: Vec<usize> = key_strs
4963                        .iter()
4964                        .filter_map(|key| resident_e.borrow().iter().position(|p| &p.key == key))
4965                        .collect();
4966                    if order.len() == resident_e.borrow().len()
4967                        && order.iter().enumerate().any(|(i, old)| i != *old)
4968                    {
4969                        let mut old: Vec<Option<ResidentPage>> =
4970                            resident_e.borrow_mut().drain(..).map(Some).collect();
4971                        // Unique route keys produce a permutation of all resident pages;
4972                        // each in-bounds slot is taken exactly once.
4973                        *resident_e.borrow_mut() =
4974                            order.iter().map(|i| old[*i].take().unwrap()).collect();
4975                        with_tree(|t| t.patch(host, Box::new(NavPatch::Reorder(order)), false));
4976                        *current_e.borrow_mut() = None;
4977                    }
4978                }
4979                // Drive the detail from here as well as from the selection bind. That bind is
4980                // created first, so when a query signal and the selection are written in one
4981                // batch it runs while `typed` still holds the pre-filter rows, finds no index
4982                // for the key, and gives up, leaving a highlighted row over an empty pane with
4983                // nothing left to re-trigger it. The fallback just above has the same problem in
4984                // reverse: it changes the selection after that bind has already run. `show` is
4985                // idempotent (it returns at once when the detail already shows this key), so
4986                // calling it on every derive costs nothing and closes both holes.
4987                show_e(&cur2);
4988            },
4989        );
4990    }
4991    if let Some(progress) = icon_progress {
4992        let mh = menu_holder.clone();
4993        let keys = typed.clone();
4994        bind(
4995            move || {
4996                let revision = progress_revision.get();
4997                let active = progress();
4998                let keys = keys.borrow();
4999                let values = active
5000                    .into_iter()
5001                    .filter_map(|(key, fraction)| {
5002                        keys.iter().position(|k| k.key() == key.key()).map(|row| {
5003                            (
5004                                row,
5005                                fraction
5006                                    .filter(|f| f.is_finite())
5007                                    .map(|f| f.clamp(0.0, 1.0)),
5008                            )
5009                        })
5010                    })
5011                    .collect::<Vec<_>>();
5012                (revision, values)
5013            },
5014            move |(_, values)| {
5015                if let Some(menu) = mh.get() {
5016                    with_tree(|t| {
5017                        t.patch(
5018                            menu,
5019                            Box::new(NavMenuPatch::IconProgress(values.clone())),
5020                            false,
5021                        );
5022                    });
5023                }
5024            },
5025        );
5026    }
5027
5028    // Native back (mobile up-arrow / system back) → the topmost page's owner. With only this
5029    // sidebar on the host, that's always the detail's deselect owner (returns to the list); when
5030    // a nested stack has merged its pages on top, its owners run first (docs/navigation.md). A
5031    // typed key deselects via its "" decoding (`Option<Section>` → `None`); a bare enum has no
5032    // list-only state so its owner's deselect is a no-op, so back is effectively ignored.
5033    //
5034    // A detail open beside its composed list comes first: `beside` holds this host's guard vote,
5035    // so the platform has not popped, and the back closes the detail rather than the section,
5036    // unless a stack merged above the section page owns it.
5037    {
5038        let owners = owners.clone();
5039        let (beside, dv_back) = (beside.clone(), detail_visible);
5040        cx.on(host, move |ev| match ev {
5041            Event::NavBack { already_popped } => {
5042                if !*already_popped
5043                    && beside.get()
5044                    && owners.borrow().len() <= 1
5045                    && let Some(dv) = dv_back
5046                {
5047                    dv.set(false);
5048                } else {
5049                    let top = owners.borrow().last().cloned();
5050                    if let Some(f) = top {
5051                        f(*already_popped);
5052                    }
5053                }
5054            }
5055            Event::RouteRequested(route) => {
5056                let _ = day_core::navigate(route);
5057            }
5058            _ => {}
5059        });
5060    }
5061
5062    // Registered after the pages are built: `register_nav` drains any pending route as it
5063    // registers, and a route arriving before this host has children attaches a page to a
5064    // parent that is not in the tree yet (an intermittent startup panic on AppKit). Ordering
5065    // here does not decide routing; `NavController::depth` does.
5066    let (tp_push, s_push) = (typed.clone(), selection.clone());
5067    let s_pop = selection.clone();
5068    let (dv_pop, lis_pop, pres_pop) = (
5069        detail_visible,
5070        list_in_stack.clone(),
5071        presentation_cell.clone(),
5072    );
5073    let (has_list_pop, pred_pop) = (list_build.is_some(), list_pred.clone());
5074    let s_cur = selection.clone();
5075    let (tp_enter, s_enter) = (typed.clone(), selection.clone());
5076    let s_seg = selection.clone();
5077    let pick =
5078        |tp: &Rc<RefCell<Vec<K>>>, k: &str| tp.borrow().iter().find(|x| x.key() == k).cloned();
5079    let pick_push = pick;
5080    let pick_enter = pick;
5081    if routed {
5082        note_routed_one_of_n("sidebar");
5083        register_route_surface(
5084            move |k| {
5085                if k.is_empty() {
5086                    if let Some(root) = K::from_key("") {
5087                        s_push.write(root);
5088                        true
5089                    } else {
5090                        false // no empty state (bare-enum key); let the parent handle ""
5091                    }
5092                } else if let Some(key) = pick_push(&tp_push, k) {
5093                    s_push.write(key);
5094                    true
5095                } else {
5096                    false
5097                }
5098            },
5099            move |_| {
5100                let current = s_pop.peek();
5101                let pres = pres_pop.get();
5102                if current.key().is_empty() {
5103                    false
5104                } else if let Some(dv) = dv_pop
5105                    && dv.peek()
5106                    && has_list_pop
5107                    && pred_pop.as_ref().is_none_or(|p| p(&current))
5108                    && (pres.is_split()
5109                        || (merged_list && pres == NavPresentation::Stack && lis_pop.get()))
5110                {
5111                    // The detail is the innermost layer wherever it shows with its list
5112                    // (docs/navigation.md): over it while the list is interposed in a collapsed
5113                    // stack, where the native back closes it through the page's owner, and
5114                    // beside it in a split, where the back closes it before the section is left.
5115                    // An imperative `nav_back` lands in the same place rather than leaving the
5116                    // section, which is what it did on a phone, popping the list and the section
5117                    // under a script's back.
5118                    dv.set(false);
5119                    true
5120                } else if let Some(root) = K::from_key("") {
5121                    s_pop.write(root);
5122                    true
5123                } else {
5124                    false
5125                }
5126            },
5127            move || s_cur.peek().key(),
5128            // Absolute-path segment: a declared item key selects it (no "", since segments are
5129            // non-empty).
5130            move |k| {
5131                if let Some(key) = pick_enter(&tp_enter, k) {
5132                    s_enter.write(key);
5133                    true
5134                } else {
5135                    false
5136                }
5137            },
5138            move || {
5139                let k = s_seg.peek().key();
5140                if k.is_empty() { Vec::new() } else { vec![k] }
5141            },
5142        );
5143    }
5144
5145    persist_selection(restore, &selection);
5146    host
5147}
5148
5149// ===========================================================================
5150// NavStack: a push/pop navigation stack bound to a Signal<Vec<String>>.
5151// The native UINavigationController / AdwNavigationView / back-stack is reconciled
5152// to the path; the back button writes the pop back into the path.
5153// ===========================================================================
5154
5155type StackImmersive<K> = dyn Fn(Option<&K>) -> bool;
5156
5157struct StackEntry<K> {
5158    key: K,
5159    scope: Scope,
5160    page: RNode,
5161}
5162
5163/// What a [`NavStack::on_back`] guard returns for one back-like event (a native back gesture/button,
5164/// or [`nav_back`]). Programmatic path writes are not guarded; the guard is a policy on the
5165/// user's back affordance, matching Jetpack Compose's `BackHandler` (docs/navigation.md).
5166#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5167pub enum BackResponse {
5168    /// Let the pop happen now.
5169    Proceed,
5170    /// Consume the back; the pop does not happen. Stash the [`BackRequest`] and call
5171    /// [`BackRequest::proceed`] later (e.g. after a confirmation dialog) to perform the pop.
5172    Handled,
5173}
5174
5175/// The deferred pop handed to a [`NavStack::on_back`] guard. Hold it, then call [`proceed`] to
5176/// perform the back the guard consumed (the unsaved-changes → confirm → leave flow).
5177///
5178/// [`proceed`]: BackRequest::proceed
5179#[derive(Clone)]
5180pub struct BackRequest {
5181    pop: Rc<dyn Fn()>,
5182}
5183
5184impl BackRequest {
5185    /// Perform the pop this back requested. Runs the same path pop a `Proceed` would have; safe
5186    /// to call once (a second call after the page is gone is a no-op).
5187    pub fn proceed(&self) {
5188        (self.pop)();
5189    }
5190}
5191
5192/// A push/pop navigation stack whose contents are an app-owned `Signal<Vec<K>>` (the path
5193/// above the root). Day reconciles the native stack to the path; the native back button
5194/// writes the pop back into it (docs/navigation.md).
5195///
5196/// The key type is any [`Route`]: `String` for raw keys, or a typed enum whose variants can
5197/// carry data; the destination builder then receives the typed value, and an absolute
5198/// `navigate("…/item-42")` parses each segment via [`Route::from_key`] (rejecting segments
5199/// that don't parse; `String` accepts everything).
5200///
5201/// ```ignore
5202/// let path = Signal::new(Vec::<Drill>::new());
5203/// nav_stack(path.clone(), home_view).destination(|d: &Drill| detail_view(d))
5204/// // push:  path.update(|p| p.push(Drill::Item { id: 42 }));
5205/// ```
5206#[must_use]
5207pub struct NavStack<S: Binding<Vec<K>>, K: Route = String> {
5208    path: S,
5209    title: TextSource,
5210    root: AnyPiece,
5211    destination: Rc<dyn Fn(&K) -> AnyPiece>,
5212    immersive: Rc<StackImmersive<K>>,
5213    on_back: Option<Rc<dyn Fn(BackRequest) -> BackResponse>>,
5214    /// The persistence key set by [`NavStack::restore`]: the path is saved here (its keys `/`-joined)
5215    /// on every change and restored at build. `None` = not persisted.
5216    restore: Option<String>,
5217    /// Items declared on the stack's root page chrome ([`NavStack::toolbar`]).
5218    toolbar: Vec<crate::ToolbarSource>,
5219}
5220
5221pub fn nav_stack<K: Route, S: Binding<Vec<K>>>(path: S, root: impl Piece) -> NavStack<S, K> {
5222    NavStack {
5223        path,
5224        title: TextSource::Static(String::new()),
5225        root: AnyPiece::new(root),
5226        destination: Rc::new(|_| {
5227            piece_fn(|cx| cx.layout_only(Rc::new(PassThrough), Flex::default(), Boundary::No)).any()
5228        }),
5229        immersive: Rc::new(|_| false),
5230        on_back: None,
5231        restore: None,
5232        toolbar: Vec::new(),
5233    }
5234}
5235
5236#[day_macros::builder(NavStackBuilder<K>)]
5237impl<K: Route, S: Binding<Vec<K>>> NavStack<S, K> {
5238    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
5239        self.title = t.into_text();
5240        self
5241    }
5242    /// Declare toolbar items on this stack's root page chrome (docs/toolbars.md): the commands
5243    /// that act on what the root shows, and that have nothing to act on once a pushed page covers
5244    /// it. A pushed page declares its own with the same method on the piece it builds.
5245    ///
5246    /// Takes one item, a list of them, or a closure that derives the list.
5247    pub fn toolbar<M>(mut self, content: impl crate::ToolbarContent<M>) -> Self {
5248        self.toolbar.push(content.into_source());
5249        self
5250    }
5251
5252    /// Build the view for a pushed key (`&String` for raw keys, the typed value otherwise).
5253    pub fn destination<P: Piece>(mut self, build: impl Fn(&K) -> P + 'static) -> Self {
5254        self.destination = Rc::new(move |k| AnyPiece::new(build(k)));
5255        self
5256    }
5257    /// Choose pages whose content extends behind the top system and navigation bars.
5258    /// The predicate receives `None` for the root and `Some(key)` for a destination, once
5259    /// when that page is created. UIKit keeps native navigation controls over the content;
5260    /// Android requires `[android] edge-to-edge = true` in `Day.toml`. Other toolkits ignore
5261    /// this presentation hint. Keep text and controls below the overlaid chrome.
5262    /// A merged stack's root inherits its enclosing page's presentation.
5263    pub fn immersive(mut self, page: impl Fn(Option<&K>) -> bool + 'static) -> Self {
5264        self.immersive = Rc::new(page);
5265        self
5266    }
5267
5268    /// Intercept the back affordance (docs/navigation.md). The guard runs for every native back
5269    /// gesture/button and [`nav_back`] while the stack is above its root; it returns
5270    /// [`BackResponse::Proceed`] to pop now or [`BackResponse::Handled`] to consume the back
5271    /// (stash the [`BackRequest`] and call [`BackRequest::proceed`] later). Programmatic path
5272    /// writes are never guarded. While a guard is armed the toolkit stops auto-popping on a
5273    /// native gesture and routes the back through Day instead (`NavPatch::GuardTop`).
5274    pub fn on_back(mut self, guard: impl Fn(BackRequest) -> BackResponse + 'static) -> Self {
5275        self.on_back = Some(Rc::new(guard));
5276        self
5277    }
5278    /// Remember the pushed path across launches (docs/navigation.md). On every change the path's
5279    /// keys are `/`-joined and saved under `key`; at build the saved path is parsed back (each
5280    /// segment via [`Route::from_key`]) and restored, so the app reopens exactly where the user
5281    /// left off, including after an Android process death, unless a launch deep link is pending,
5282    /// which wins. `day::launch` installs the preferences as the store (docs/navigation.md); a
5283    /// saved path with a segment that no longer parses is ignored whole.
5284    pub fn restore(mut self, key: impl Into<String>) -> Self {
5285        self.restore = Some(key.into());
5286        self
5287    }
5288}
5289
5290impl<K: Route, S: Binding<Vec<K>>> Piece for NavStack<S, K> {
5291    fn build(self, cx: &mut BuildCx) -> RNode {
5292        use day_spec::props::{NavPageProps, NavPatch, NavPresentation, NavProps, Pane};
5293        let NavStack {
5294            path,
5295            title,
5296            root,
5297            destination: dest,
5298            immersive,
5299            on_back,
5300            restore,
5301            toolbar,
5302        } = self;
5303        let title_s = title.initial();
5304        // Only the top page shows (docs/toolbars.md): a desktop's one bar carries its items and
5305        // its search field, not those of the pages under it. The enclosing page's own gate still
5306        // applies, so a stack in a tab that is not selected shows nothing.
5307        let outer_gate = day_core::current_page_gate();
5308        let shown_depth = Signal::new(0usize);
5309        let gate = move |at: usize| -> Option<Rc<dyn Fn() -> bool>> {
5310            let outer = outer_gate.clone();
5311            Some(Rc::new(move || {
5312                outer.as_ref().is_none_or(|g| g()) && shown_depth.get() == at
5313            }))
5314        };
5315
5316        // Restore the saved path before the reconcile binding runs, so its pages build on first
5317        // pass. A launch deep link wins (skip). The path is decoded from the same percent-encoded
5318        // wire format the rest of nav uses (`parse_route`), so a key that itself contains `/` (or
5319        // `?`, `%`) round-trips instead of splitting into two. The whole path is parsed via
5320        // `Route::from_key`; any segment that no longer parses discards the restore rather than
5321        // building a partial stack (docs/navigation.md).
5322        if let Some(key) = restore.as_deref()
5323            && !day_core::has_launch_deeplink()
5324            && let Some(saved) = day_core::nav_store_load(key)
5325        {
5326            let (segments, _) = day_core::parse_route(&saved);
5327            let parsed: Option<Vec<K>> = segments.iter().map(|s| K::from_key(s)).collect();
5328            if let Some(v) = parsed {
5329                path.write(v);
5330            }
5331        }
5332
5333        // If we're built inside a page of an enclosing nav host that presents as a push stack
5334        // (mobile, `split == false`), merge: push our pages onto that host instead of minting a
5335        // second native container (one native nav chain, one back button; docs/navigation.md).
5336        // A split host (desktop) is not merged into; a stack keeps its own detail-pane stack.
5337        let merge = current_nav_host().filter(|c| !c.split.get());
5338
5339        let entries: Rc<RefCell<Vec<StackEntry<K>>>> = Rc::default();
5340        let native_popped: Rc<Cell<usize>> = Rc::new(Cell::new(0));
5341
5342        let host: RNode;
5343        let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>>;
5344        let owners: Rc<RefCell<Vec<PopOwner>>>;
5345        let host_cx: NavHostCx;
5346        let ret_node: RNode;
5347        let merged: bool;
5348        if let Some(ctx) = merge {
5349            // Merged: reuse the enclosing host; our root renders inline in the current page (which
5350            // is already a NAV_PAGE), and only our pushed destinations become new pages.
5351            host = ctx.host;
5352            sizes = ctx.sizes.clone();
5353            owners = ctx.owners.clone();
5354            host_cx = ctx;
5355            let hc = host_cx.clone();
5356            ret_node = with_nav_host(Some(hc), || root.build(cx));
5357            // A merged stack has no chrome of its own: its root renders inside the enclosing
5358            // host's page, and that page's bar is the one the user sees. Its items go there,
5359            // where they used to be dropped with a debug warning.
5360            for source in toolbar {
5361                crate::contribute(day_core::current_chrome(), source);
5362            }
5363            merged = true;
5364        } else {
5365            // Standalone: create the native host + root page (an app-root stack, or a nested stack
5366            // under a split/desktop host).
5367            sizes = Rc::default();
5368            host = cx.native(
5369                kinds::NAV,
5370                &NavProps {
5371                    documents: None,
5372                    // A stack is a stack at every size: it has no sidebar pane to re-home, so
5373                    // there is nothing for a size-class change to re-present.
5374                    title: title_s.clone(),
5375                    presentation: NavPresentation::Stack,
5376                    // Never adaptive: the `nav_stack()` piece is a push/pop surface at every size, so
5377                    // an Emulated toolkit must build a plain navigation container for it rather
5378                    // than its adaptive one (docs/size-classes.md).
5379                    adaptive: false,
5380                    // A stack has no sidebar pane, so nothing to toggle.
5381                    sidebar_toggle: false,
5382                    // Stacks are not searchable yet: `.searchable()` is on `Nav` only
5383                    // (docs/search.md); a stack gains the same surface when the placement
5384                    // resolver lands, since it is the same lowering.
5385                    search: None,
5386                    // A content list is a nav shape; a stack has no sidebar to sit beside.
5387                    list_width: None,
5388                    // A stack never has a content-list pane, so this says nothing.
5389                    list_visible: true,
5390                },
5391                Rc::new(NavLayout::stack(sizes.clone())),
5392                Flex {
5393                    grow_w: true,
5394                    grow_h: true,
5395                    ..Default::default()
5396                },
5397                Boundary::Yes,
5398            );
5399            owners = Rc::default();
5400            host_cx = NavHostCx {
5401                host,
5402                sizes: sizes.clone(),
5403                owners: owners.clone(),
5404                split: Rc::new(Cell::new(false)),
5405                guards: Rc::default(),
5406            };
5407            let root_page = nav_page(
5408                host,
5409                &NavPageProps {
5410                    title: title_s,
5411                    pane: Pane::Detail,
5412                    immersive: immersive(None),
5413                },
5414                &sizes,
5415            );
5416            let hc = host_cx.clone();
5417            with_nav_host(Some(hc), || {
5418                day_core::with_page_gated(
5419                    root_page,
5420                    gate(0),
5421                    day_spec::ToolbarColumn::Detail,
5422                    || {
5423                        let mut pcx = BuildCx::new(root_page);
5424                        let _ = root.build(&mut pcx);
5425                    },
5426                );
5427            });
5428            // A standalone stack's items ride its root page's chrome: the commands that act
5429            // on what the root shows, and that a pushed page covers along with it.
5430            for source in toolbar {
5431                crate::contribute(day_core::Chrome::Page(root_page), source);
5432            }
5433            ret_node = host;
5434            merged = false;
5435        }
5436
5437        let nav_scope = Scope::current();
5438
5439        // The raw pop: drop the top path segment (reconcile then pops the native page). The
5440        // guard's `BackRequest::proceed` runs exactly this.
5441        let raw_pop: Rc<dyn Fn()> = {
5442            let p = path.clone();
5443            Rc::new(move || {
5444                let mut v = p.peek();
5445                if v.pop().is_some() {
5446                    p.write(v);
5447                }
5448            })
5449        };
5450        let depth = {
5451            let p = path.clone();
5452            move || p.peek().len()
5453        };
5454        // One back-like event (native gesture that Day owns, or `nav_back()`): consult the guard
5455        // if one is armed and we're above the root, else pop. `Proceed` pops now; `Handled`
5456        // consumes it (the app holds the `BackRequest`). Programmatic `path.set` never lands here.
5457        let run_back: Rc<dyn Fn()> = {
5458            let (raw_pop, depth, guard) = (raw_pop.clone(), depth.clone(), on_back.clone());
5459            Rc::new(move || {
5460                if depth() == 0 {
5461                    return; // at root: nothing of ours to pop
5462                }
5463                match &guard {
5464                    Some(g) => {
5465                        let req = BackRequest {
5466                            pop: raw_pop.clone(),
5467                        };
5468                        if g(req) == BackResponse::Proceed {
5469                            raw_pop();
5470                        }
5471                    }
5472                    None => raw_pop(),
5473                }
5474            })
5475        };
5476
5477        // This stack's back owner (one Rc shared by all its pages): a native pop the toolkit
5478        // Already performed (an unguarded iOS swipe) is absorbed + synced without the guard; a
5479        // back Day owns runs `run_back` so the guard decides.
5480        let stack_owner: PopOwner = {
5481            let (native_popped, raw_pop, run_back) =
5482                (native_popped.clone(), raw_pop.clone(), run_back.clone());
5483            Rc::new(move |already_popped: bool| {
5484                if already_popped {
5485                    native_popped.set(native_popped.get() + 1);
5486                    raw_pop();
5487                } else {
5488                    run_back();
5489                }
5490            })
5491        };
5492
5493        // Reconcile the native stack to `want`: keep the common prefix, pop the rest, push
5494        // the new suffix. A pop the native already performed (iOS back) is not re-issued. Pages
5495        // and owners land on `host` (our own, or the enclosing one when merged).
5496        // `true` while this stack holds a guard vote on its host (`NavHostCx::vote_guard`), so the
5497        // vote moves only on a real transition (arming/disarming native gesture handling is not
5498        // free on every pop), and a merged stack shares the count with the host's other voters.
5499        let guard_armed_sent = Rc::new(Cell::new(false));
5500        let has_guard = on_back.is_some();
5501        let reconcile = {
5502            let (entries, sizes, dest, native_popped, owners, host_cx, stack_owner) = (
5503                entries.clone(),
5504                sizes.clone(),
5505                dest.clone(),
5506                native_popped.clone(),
5507                owners.clone(),
5508                host_cx.clone(),
5509                stack_owner.clone(),
5510            );
5511            let guard_armed_sent = guard_armed_sent.clone();
5512            move |want: &Vec<K>| {
5513                let common = {
5514                    let ents = entries.borrow();
5515                    let mut i = 0;
5516                    while i < ents.len() && i < want.len() && ents[i].key == want[i] {
5517                        i += 1;
5518                    }
5519                    i
5520                };
5521                while entries.borrow().len() > common {
5522                    let e = entries.borrow_mut().pop().unwrap();
5523                    if native_popped.get() > 0 {
5524                        native_popped.set(native_popped.get() - 1);
5525                    } else {
5526                        with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
5527                    }
5528                    e.scope.dispose();
5529                    sizes.borrow_mut().remove(&e.page);
5530                    with_tree(|t| t.remove_subtree(e.page));
5531                    owners.borrow_mut().pop();
5532                }
5533                for (at, key) in want.iter().enumerate().skip(common) {
5534                    let title = key.title();
5535                    let immersive = immersive(Some(key));
5536                    let page = nav_page(
5537                        host,
5538                        &NavPageProps {
5539                            title: title.clone(),
5540                            pane: Pane::Detail,
5541                            immersive,
5542                        },
5543                        &sizes,
5544                    );
5545                    let scope = nav_scope.enter(Scope::child);
5546                    let hc = host_cx.clone();
5547                    scope.enter(|| {
5548                        // Inside the page's scope; see the pushed-detail site above.
5549                        let content = (dest)(key);
5550                        with_nav_host(Some(hc), || {
5551                            day_core::with_page_gated(
5552                                page,
5553                                gate(at + 1),
5554                                day_spec::ToolbarColumn::Detail,
5555                                || {
5556                                    let mut c = BuildCx::new(page);
5557                                    let _ = content.build(&mut c);
5558                                },
5559                            );
5560                        });
5561                    });
5562                    with_tree(|t| {
5563                        // The page props and push patch carry the same presentation choice.
5564                        t.patch(host, Box::new(NavPatch::Pushed { title, immersive }), false);
5565                    });
5566                    owners.borrow_mut().push(stack_owner.clone());
5567                    entries.borrow_mut().push(StackEntry {
5568                        key: key.clone(),
5569                        scope,
5570                        page,
5571                    });
5572                }
5573                shown_depth.set(want.len());
5574                // Arm/disarm native gesture handling when the guarded-above-root state changes
5575                // (docs/navigation.md). The host is our own container, or the enclosing one when
5576                // merged; either way the native nav that owns the back gesture.
5577                if has_guard {
5578                    let armed = !entries.borrow().is_empty();
5579                    if armed != guard_armed_sent.get() {
5580                        guard_armed_sent.set(armed);
5581                        host_cx.vote_guard(armed);
5582                    }
5583                }
5584                with_tree(|t| {
5585                    t.mark_layout_dirty();
5586                    t.layout_if_needed();
5587                });
5588            }
5589        };
5590        {
5591            let p = path.clone();
5592            bind(move || p.read(), move |want: &Vec<K>| reconcile(want));
5593        }
5594
5595        // Route identity may stay the same while asynchronously loaded metadata changes
5596        // its title. Track that title independently of path equality; do not rebuild the
5597        // page or let an enclosing merged stack rename a deeper stack's current page.
5598        {
5599            let p = path.clone();
5600            let owners = owners.clone();
5601            let stack_owner = stack_owner.clone();
5602            bind(
5603                move || p.read().last().map(Route::title),
5604                move |title: &Option<String>| {
5605                    if let Some(title) = title
5606                        && owners
5607                            .borrow()
5608                            .last()
5609                            .is_some_and(|owner| Rc::ptr_eq(owner, &stack_owner))
5610                    {
5611                        with_tree(|t| {
5612                            t.patch(host, Box::new(NavPatch::Title(title.clone())), false);
5613                        });
5614                    }
5615                },
5616            );
5617        }
5618
5619        // A live root title (a localized string re-resolving on locale change, docs/
5620        // localization.md): the host's bar follows while the stack shows its root, and again
5621        // when a pop returns there, since a pushed page's bar is its own (the binding above).
5622        // A merged stack's root sits inside the enclosing host's page, whose bar is that page's.
5623        if !merged && let TextSource::Dyn(_) = &title {
5624            let (p, src) = (path.clone(), title.clone());
5625            bind_seeded(
5626                (src.initial(), true),
5627                move || (src.resolve(), p.read().is_empty()),
5628                move |(t, at_root): &(String, bool)| {
5629                    if *at_root {
5630                        with_tree(|tr| tr.patch(host, Box::new(NavPatch::Title(t.clone())), false));
5631                    }
5632                },
5633            );
5634        }
5635
5636        // Persist the path across launches when `.restore` is set: save the keys in the same
5637        // percent-encoded wire format `parse_route` reads back (`encode_route`), so a key
5638        // containing `/` survives the round-trip (docs/navigation.md). Scope-owned, so it stops
5639        // with the stack.
5640        if let Some(key) = restore {
5641            let p = path.clone();
5642            bind(
5643                move || {
5644                    let keys: Vec<String> = p.read().iter().map(Route::key).collect();
5645                    day_core::encode_route(&keys, &[])
5646                },
5647                move |s: &String| day_core::nav_store_save(&key, s),
5648            );
5649        }
5650
5651        // Standalone: own the host's single NavBack dispatcher (→ topmost page's owner) and the
5652        // deeplink handler. Merged: the enclosing host's creator already owns both.
5653        if !merged {
5654            let owners_h = owners.clone();
5655            cx.on(host, move |ev| match ev {
5656                Event::NavBack { already_popped } => {
5657                    let top = owners_h.borrow().last().cloned();
5658                    if let Some(f) = top {
5659                        f(*already_popped);
5660                    }
5661                }
5662                Event::RouteRequested(route) => {
5663                    let _ = day_core::navigate(route);
5664                }
5665                _ => {}
5666            });
5667        }
5668
5669        // Merged: our pages live on the enclosing host, so the enclosing detail's
5670        // `remove_subtree` won't reach them; pop every remaining page (top-down) off that host
5671        // when our scope disposes (e.g. the section switches). Guarded for app teardown.
5672        if merged {
5673            let (entries_c, sizes_c, owners_c, native_popped_c) = (
5674                entries.clone(),
5675                sizes.clone(),
5676                owners.clone(),
5677                native_popped.clone(),
5678            );
5679            let (guard_c, host_cx_c) = (guard_armed_sent.clone(), host_cx.clone());
5680            nav_scope.on_cleanup(move || {
5681                let alive = with_tree(|t| t.node_kind(host).is_some());
5682                // A vote this stack still holds would keep the enclosing host routing every back
5683                // through Day after the stack is gone.
5684                if alive && guard_c.replace(false) {
5685                    host_cx_c.vote_guard(false);
5686                }
5687                loop {
5688                    let e = entries_c.borrow_mut().pop();
5689                    let Some(e) = e else { break };
5690                    if alive {
5691                        if native_popped_c.get() > 0 {
5692                            native_popped_c.set(native_popped_c.get() - 1);
5693                        } else {
5694                            with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
5695                        }
5696                        sizes_c.borrow_mut().remove(&e.page);
5697                        with_tree(|t| t.remove_subtree(e.page));
5698                        owners_c.borrow_mut().pop();
5699                    }
5700                }
5701                if alive {
5702                    with_tree(|t| {
5703                        t.mark_layout_dirty();
5704                        t.layout_if_needed();
5705                    });
5706                }
5707            });
5708        }
5709
5710        // string-route adapter. A stack is driven by its `path` (app state / buttons), not by
5711        // magic navigate-strings: a relative `navigate("<key>")` claims only "" (pop to root),
5712        // so sibling keys fall through to the enclosing surface, but an absolute path's
5713        // segments (`enter`) push any segment the key type parses: a `String` stack is
5714        // open-ended, a typed stack validates via `Route::from_key`, and an explicit `a/b/c`
5715        // path is the stack's state. `pop` falls through once empty.
5716        let p_push = path.clone();
5717        let p_cur = path.clone();
5718        let p_enter = path.clone();
5719        let p_seg = path.clone();
5720        register_route_surface(
5721            move |k| {
5722                if k.is_empty() {
5723                    let mut v = p_push.peek();
5724                    if v.is_empty() {
5725                        return false; // already at root; let the parent handle ""
5726                    }
5727                    v.clear();
5728                    p_push.write(v);
5729                    true
5730                } else {
5731                    false
5732                }
5733            },
5734            {
5735                // `nav_back()` is a back-like event, so it is guarded too (docs/navigation.md):
5736                // run_back consults the guard. We "own" the back (return true, no fall-through)
5737                // whenever we're above the root, whether the guard pops or consumes.
5738                let (run_back, depth) = (run_back.clone(), depth.clone());
5739                move |_| {
5740                    if depth() == 0 {
5741                        return false; // at root; let the parent handle back
5742                    }
5743                    run_back();
5744                    true
5745                }
5746            },
5747            move || p_cur.peek().last().map_or_default(Route::key),
5748            move |k| {
5749                let Some(parsed) = K::from_key(k) else {
5750                    return false; // not one of this stack's routes; leave it queued
5751                };
5752                let mut v = p_enter.peek();
5753                v.push(parsed);
5754                p_enter.write(v);
5755                true
5756            },
5757            move || p_seg.peek().iter().map(Route::key).collect(),
5758        );
5759        ret_node
5760    }
5761}
5762
5763// ===========================================================================
5764// Cover: a fullscreen modal surface bound to a Signal<Option<Route>> (docs/cover.md).
5765// ===========================================================================
5766
5767/// A fullscreen cover: the modal counterpart of [`nav_stack`], bound to a `Signal<Option<R>>`.
5768/// `Some(r)` presents the built content over the whole window (edge-to-edge, slide-up where
5769/// the platform animates modals); `None` dismisses it. The SwiftUI analogue is
5770/// `fullScreenCover(item:)`. Build one with [`cover`].
5771///
5772/// The open value is app state, exactly like a stack's path: set it and the cover presents;
5773/// a native dismissal (Android system back) writes `None` back, unless an
5774/// [`interactive_dismiss_disabled`](Decorate::interactive_dismiss_disabled) subtree is
5775/// mounted inside the content, in which case only programmatic writes close it.
5776/// A cover's per-route surface color (see [`Cover::background`]).
5777type CoverBackground<R> = Rc<dyn Fn(&R) -> day_spec::Ink>;
5778
5779#[must_use]
5780pub struct Cover<S, R: Route> {
5781    sheet: bool,
5782    half: bool,
5783    large: bool,
5784    open: S,
5785    build: Rc<dyn Fn(&R) -> AnyPiece>,
5786    background: Option<CoverBackground<R>>,
5787    routed: bool,
5788    _marker: std::marker::PhantomData<R>,
5789}
5790
5791/// The route of a cover bound to a `bool` (docs/cover.md "Open or closed"): the cover has one
5792/// thing to show, so its route carries nothing. The builder still receives it, so a bool cover
5793/// is written `cover(open, |_| content())`.
5794#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5795pub struct Shown;
5796
5797impl Route for Shown {
5798    fn key(&self) -> String {
5799        "shown".into()
5800    }
5801    fn from_key(key: &str) -> Option<Self> {
5802        (key == "shown").then_some(Shown)
5803    }
5804}
5805
5806/// A `Binding<bool>` seen as the `Binding<Option<Shown>>` a cover presents from: `true` is
5807/// `Some(Shown)`, and a native dismissal writes `false` back.
5808#[derive(Clone)]
5809pub struct ShownBinding<B>(B);
5810
5811impl<B: Binding<bool>> Binding<Option<Shown>> for ShownBinding<B> {
5812    fn read(&self) -> Option<Shown> {
5813        self.0.read().then_some(Shown)
5814    }
5815    fn peek(&self) -> Option<Shown> {
5816        self.0.peek().then_some(Shown)
5817    }
5818    fn write(&self, v: Option<Shown>) {
5819        self.0.write(v.is_some());
5820    }
5821}
5822
5823/// Marker for a cover opened by a `Binding<Option<R>>` ([`IntoCoverOpen`]).
5824pub struct RouteOpen;
5825/// Marker for a cover opened by a `Binding<bool>` ([`IntoCoverOpen`]).
5826pub struct BoolOpen;
5827
5828/// What a [`cover`] presents from: a `Binding<Option<R>>` (a typed route, `None` closed) or a
5829/// `Binding<bool>` (open or closed, route [`Shown`]).
5830pub trait IntoCoverOpen<R: Route, M> {
5831    /// The binding the cover reads and writes.
5832    type Open: Binding<Option<R>>;
5833    /// Whether the cover registers a string-route adapter (`navigate("<key>")`). A bool cover
5834    /// does not: every bool cover would answer the same key.
5835    const ROUTED: bool;
5836    /// The binding.
5837    fn into_open(self) -> Self::Open;
5838}
5839
5840impl<R: Route, S: Binding<Option<R>>> IntoCoverOpen<R, RouteOpen> for S {
5841    type Open = S;
5842    const ROUTED: bool = true;
5843    fn into_open(self) -> S {
5844        self
5845    }
5846}
5847
5848impl<B: Binding<bool>> IntoCoverOpen<Shown, BoolOpen> for B {
5849    type Open = ShownBinding<B>;
5850    const ROUTED: bool = false;
5851    fn into_open(self) -> ShownBinding<B> {
5852        ShownBinding(self)
5853    }
5854}
5855
5856/// A fullscreen cover over `open` (docs/cover.md). With a `Binding<Option<R>>`, `Some(r)`
5857/// presents `build(&r)` and `None` dismisses; the cover registers a string-route adapter, so
5858/// `navigate("<key>")` opens it, `nav_back()` closes it, and `current_route()` reports the
5859/// presented key. With a `Binding<bool>`, `true` presents and `false` dismisses:
5860///
5861/// ```ignore
5862/// let editing = Signal::new(false);
5863/// cover(editing, |_| editor()).sheet()
5864/// ```
5865pub fn cover<R: Route, M, O: IntoCoverOpen<R, M>, P: Piece>(
5866    open: O,
5867    build: impl Fn(&R) -> P + 'static,
5868) -> Cover<O::Open, R> {
5869    Cover {
5870        sheet: false,
5871        half: false,
5872        large: false,
5873        open: open.into_open(),
5874        // The stored builder is erased because a `Cover` holds one closure for every route it
5875        // presents; the parameter stays generic so callers never write `.any()` for us.
5876        build: Rc::new(move |r| AnyPiece::new(build(r))),
5877        background: None,
5878        routed: O::ROUTED,
5879        _marker: std::marker::PhantomData,
5880    }
5881}
5882
5883#[day_macros::builder(CoverBuilder<R>)]
5884impl<S: Binding<Option<R>>, R: Route> Cover<S, R> {
5885    /// Prefer a native modal sheet. Backends without sheets retain their modal cover.
5886    pub fn sheet(mut self) -> Self {
5887        self.sheet = true;
5888        self
5889    }
5890
5891    /// Present as a large modal sheet: most of the window, less a margin, for a document or a
5892    /// web page that needs the room a form does not (docs/cover.md "Large sheet"). macOS sizes
5893    /// its window sheet and the composed desktop tiers their card up to
5894    /// [`LARGE_SHEET_MAX`](day_spec::props::LARGE_SHEET_MAX); iPadOS presents a page sheet;
5895    /// compact windows keep the full-window cover, as for any sheet. Implies [`Cover::sheet`].
5896    pub fn large_sheet(mut self) -> Self {
5897        self.sheet = true;
5898        self.large = true;
5899        self
5900    }
5901
5902    /// Present as a half-height sheet rising from the bottom edge, the window content above
5903    /// it staying on show: an inspector over the canvas it describes, a transport over the
5904    /// media it controls (docs/cover.md "Half sheet"). iOS presents a medium-detent sheet that
5905    /// leaves the content interactive, Android a Material bottom sheet, the web, HarmonyOS and
5906    /// the emulated desktop tiers a bottom-anchored half panel, and macOS its window sheet at
5907    /// half the window's height. Implies [`Cover::sheet`].
5908    pub fn half_sheet(mut self) -> Self {
5909        self.sheet = true;
5910        self.half = true;
5911        self
5912    }
5913
5914    /// The surface color painted edge-to-edge behind the content (under the status bar and
5915    /// home indicator) while `r` is presented. Without it the platform's default surface
5916    /// color shows in the unsafe areas. Any ink: a role or a light/dark pair follows the
5917    /// appearance while the cover is up.
5918    pub fn background<C: Into<day_spec::Ink>>(mut self, f: impl Fn(&R) -> C + 'static) -> Self {
5919        self.background = Some(Rc::new(move |r| f(r).into()));
5920        self
5921    }
5922
5923    /// Keep this cover out of the app's route space: `navigate("<key>")` never presents it, it
5924    /// contributes nothing to `current_route()`, and `nav_back()` walks past it.
5925    ///
5926    /// For a cover that is a **control's own panel** rather than an app destination (a color
5927    /// picker's chooser, a media scrubber's fullscreen mode), presented and dismissed by the
5928    /// control, never linked to. Two reasons that matters:
5929    ///
5930    /// - **A routed cover claims route segments**, and over the untyped `Route` (`String`,
5931    ///   whose `from_key` accepts anything) it claims *every* segment: mount one and the next
5932    ///   `navigate("settings")` presents the cover with the key `"settings"` instead of going to
5933    ///   settings. A piece that mounts a cover would be silently rewriting its host app's
5934    ///   navigation.
5935    /// - **It is not a place.** `current_route()` naming a transient chooser makes a restored
5936    ///   session reopen it, and a "share this screen" link point at a modal.
5937    ///
5938    /// Interactive dismissal is unaffected: the cover still answers Android's system back through
5939    /// [`Event::NavBack`](day_spec::Event::NavBack) on its own node, which never went through the
5940    /// route adapter.
5941    pub fn unrouted(mut self) -> Self {
5942        self.routed = false;
5943        self
5944    }
5945}
5946
5947impl<S: Binding<Option<R>>, R: Route> Piece for Cover<S, R> {
5948    fn build(self, cx: &mut BuildCx) -> RNode {
5949        // The presented content's scope, and whether a dismiss transition is in flight
5950        // (content stays mounted until the backend reports `CoverHidden`, so the surface
5951        // isn't blank while it slides out).
5952        struct Presented<R> {
5953            key: R,
5954            scope: Scope,
5955        }
5956        use day_spec::props::{CoverPatch, CoverProps};
5957        let Cover {
5958            sheet,
5959            half,
5960            large,
5961            open,
5962            build,
5963            background,
5964            routed,
5965            ..
5966        } = self;
5967        // A `.sheet()` on a toolkit with no native sheet is composed here: a card over the
5968        // dimmed page, on the transparent cover (docs/cover.md "Modal sheet"). The window is
5969        // the one being built, whose size class decides at each presentation.
5970        let composed_sheet = sheet
5971            && !half
5972            && day_core::capability(day_spec::Cap::CoverSheet) == day_spec::Support::Unsupported;
5973        let window = day_core::window_being_built();
5974
5975        let size: Rc<RefCell<Option<Size>>> = Rc::default();
5976        let node = cx.native(
5977            kinds::COVER,
5978            &CoverProps { sheet, half, large },
5979            Rc::new(day_core::CoverLayout { size: size.clone() }),
5980            Flex::default(),
5981            Boundary::Yes,
5982        );
5983
5984        let current: Rc<RefCell<Option<Presented<R>>>> = Rc::default();
5985        let closing: Rc<Cell<bool>> = Rc::default();
5986        let owner_scope = Scope::current();
5987        let layer = NavLayer {
5988            order: Rc::new(Cell::new(0)),
5989            depth: owner_scope.use_context::<NavLayer>().map_or(0, |l| l.depth),
5990        };
5991
5992        let dispose_content = {
5993            let current = current.clone();
5994            move || {
5995                let presented = current.borrow_mut().take();
5996                // Detaching focused native inputs can enqueue their final value
5997                // or blur events. Remove their handlers before disposing signals
5998                // captured by those handlers, then release the content scope.
5999                while with_tree(|t| t.child_count(node)) > 0 {
6000                    match with_tree(|t| t.first_child(node)) {
6001                        Some(c) => with_tree(|t| t.remove_subtree(c)),
6002                        None => break,
6003                    }
6004                }
6005                if let Some(p) = presented {
6006                    p.scope.dispose();
6007                }
6008            }
6009        };
6010
6011        // Reconcile the presented surface to the signal.
6012        let reconcile = {
6013            let (current, closing, dispose_content) =
6014                (current.clone(), closing.clone(), dispose_content.clone());
6015            let layer = layer.clone();
6016            move |want: &Option<R>| {
6017                if let Some(r) = want {
6018                    let already =
6019                        !closing.get() && current.borrow().as_ref().is_some_and(|p| p.key == *r);
6020                    if already {
6021                        return;
6022                    }
6023                    dispose_content();
6024                    closing.set(false);
6025                    layer.order.set(NEXT_COVER_LAYER.with(|next| {
6026                        let order = next.get();
6027                        next.set(order + 1);
6028                        order
6029                    }));
6030                    let scope = owner_scope.enter(Scope::child);
6031                    scope.provide(NavLayer {
6032                        order: layer.order.clone(),
6033                        depth: layer.depth + 1,
6034                    });
6035                    // Run the app's builder inside the presentation scope: side effects it
6036                    // performs eagerly (state restore, autosave/cleanup registration, signals)
6037                    // must belong to the presented content's lifetime, not the cover's.
6038                    // A compact window keeps the full-window cover: a card there would leave a
6039                    // sliver of dimmed page around it.
6040                    let card = composed_sheet
6041                        && day_core::window_size_class_untracked(window)
6042                            .is_none_or(|c| c.width != day_spec::WidthClass::Compact);
6043                    // The cover is its content's window for toolbar purposes: a navigation stack
6044                    // inside it (a sheet's title, Done, bottom bar) belongs on the cover's bar,
6045                    // not on the window it covers.
6046                    scope.enter(|| {
6047                        day_core::toolbar::with_window(node, || {
6048                            let content = (build)(r);
6049                            let mut c = BuildCx::new(node);
6050                            if card {
6051                                let _ = day_core::ComposedSheet { content, large }.build(&mut c);
6052                            } else {
6053                                let _ = content.build(&mut c);
6054                            }
6055                        });
6056                    });
6057                    *current.borrow_mut() = Some(Presented {
6058                        key: r.clone(),
6059                        scope,
6060                    });
6061                    // Content is mounted, so any `interactive_dismiss_disabled` inside it has
6062                    // registered, so the present patch carries the resolved flag.
6063                    // The composed sheet paints its own card and dimmed page; the cover under
6064                    // them is clear, so the page shows through.
6065                    let bg = if card {
6066                        Some(day_spec::Ink::CLEAR)
6067                    } else {
6068                        background.as_ref().map(|f| f(r))
6069                    };
6070                    with_tree(|t| {
6071                        t.patch(
6072                            node,
6073                            Box::new(CoverPatch::Present {
6074                                background: bg,
6075                                dismiss_disabled: day_core::shield::dismiss_disabled(),
6076                            }),
6077                            false,
6078                        );
6079                        t.mark_needs_measure(node);
6080                        t.mark_layout_dirty();
6081                        t.layout_if_needed();
6082                    });
6083                } else {
6084                    layer.order.set(0);
6085                    if current.borrow().is_some() && !closing.get() {
6086                        closing.set(true);
6087                        with_tree(|t| t.patch(node, Box::new(CoverPatch::Dismiss), false));
6088                    }
6089                }
6090            }
6091        };
6092        {
6093            let o = open.clone();
6094            bind(move || o.read(), move |want: &Option<R>| reconcile(want));
6095        }
6096
6097        // While presented, keep the backend's dismiss-disabled flag in sync with the
6098        // mounted `interactive_dismiss_disabled` modifiers (the shield's change counter
6099        // makes this binding re-run as they mount/unmount).
6100        {
6101            let current = current.clone();
6102            bind(
6103                day_core::shield::dismiss_disabled,
6104                move |disabled: &bool| {
6105                    if current.borrow().is_some() {
6106                        with_tree(|t| {
6107                            t.patch(
6108                                node,
6109                                Box::new(CoverPatch::DismissDisabled(*disabled)),
6110                                false,
6111                            );
6112                        });
6113                    }
6114                },
6115            );
6116        }
6117
6118        {
6119            let (o, size, closing, dispose_content) = (
6120                open.clone(),
6121                size.clone(),
6122                closing.clone(),
6123                dispose_content.clone(),
6124            );
6125            cx.on(node, move |ev| match ev {
6126                // The backend sized the presented content container (safe-area bounds).
6127                Event::FrameChanged(sz) => {
6128                    if *size.borrow() != Some(*sz) {
6129                        *size.borrow_mut() = Some(*sz);
6130                        with_tree(|t| {
6131                            t.mark_needs_measure(node);
6132                            t.mark_layout_dirty();
6133                            t.layout_if_needed();
6134                        });
6135                    }
6136                }
6137                // Native dismissal request (Android system back). Honored unless an
6138                // `interactive_dismiss_disabled` subtree is mounted.
6139                Event::NavBack { .. } => {
6140                    if !day_core::shield::dismiss_disabled() && o.peek().is_some() {
6141                        o.write(None);
6142                    }
6143                }
6144                // The hide transition finished; now the content can go.
6145                // Idempotent + orderable (docs/cover.md): duplicates and belated reports
6146                // from a previous dismissal are no-ops via the closing gate.
6147                Event::CoverHidden if closing.get() => {
6148                    closing.set(false);
6149                    dispose_content();
6150                }
6151                _ => {}
6152            });
6153        }
6154
6155        // String-route adapter (docs/navigation.md): `navigate("<key>")` presents, `nav_back()`
6156        // dismisses, and the presented key is this surface's `current_route()` contribution.
6157        // Skipped for an `unrouted()` cover, which is a control's own panel rather than a place
6158        // the app navigates to; see `Cover::unrouted` for why that distinction matters.
6159        if !routed {
6160            return node;
6161        }
6162        let o_push = open.clone();
6163        let o_pop = open.clone();
6164        let o_cur = open.clone();
6165        let o_enter = open.clone();
6166        let o_seg = open;
6167        let push = move |k: &str, sig: &S| match R::from_key(k) {
6168            Some(r) => {
6169                sig.write(Some(r));
6170                true
6171            }
6172            None => false,
6173        };
6174        let push2 = push;
6175        register_route_surface_in_layer(
6176            layer,
6177            move |k| push(k, &o_push),
6178            move |_| {
6179                if o_pop.peek().is_some() {
6180                    o_pop.write(None);
6181                    true
6182                } else {
6183                    false
6184                }
6185            },
6186            move || o_cur.peek().map_or_default(|r| r.key()),
6187            move |k| push2(k, &o_enter),
6188            move || o_seg.peek().map_or_default(|r| vec![r.key()]),
6189        );
6190
6191        node
6192    }
6193}
6194
6195// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
6196
6197#[cfg(feature = "conformance")]
6198pub(crate) mod conformance {
6199    use day_core::Piece;
6200    use std::rc::Rc;
6201
6202    use day_core::conformance::{Case, Drive};
6203    use day_core::{Boundary, Flex, RNode, piece_fn};
6204    use day_reactive::Signal;
6205    use day_spec::props::NavPresentation;
6206    use day_spec::{Cap, Size, kinds};
6207
6208    use crate::*;
6209
6210    /// A stack whose root pushes `detail` and whose pages show their key.
6211    fn stack(path: Signal<Vec<String>>) -> impl Piece {
6212        nav_stack(
6213            path,
6214            column((
6215                label(move || format!("depth {}", path.get().len())).id(day_core::id!(depth)),
6216                button("Open")
6217                    .action(move || path.update(|p| p.push("detail".into())))
6218                    .id(day_core::id!(open)),
6219            )),
6220        )
6221        .title("Root")
6222        .destination(|key: &String| {
6223            label(format!("Page {key}")).id(day_core::id!(page, key.to_owned()))
6224        })
6225    }
6226
6227    /// Pushing a page shows it; going back pops it and writes the pop into the path.
6228    #[day_macros::test(day_core)]
6229    fn nav_stack_push_pop() -> Case {
6230        Case::new()
6231            .proves(kinds::NAV)
6232            .proves(kinds::NAV_PAGE)
6233            .page(|| stack(Signal::new(Vec::new())))
6234            .drive(|d: Drive| async move {
6235                d.assert_text("depth", "depth 0").await?;
6236                d.tap("open").await?;
6237                d.assert_text("page:detail", "Page detail").await?;
6238                d.wait_idle().await?;
6239                d.nav_back().await?;
6240                d.assert_missing("page:detail").await?;
6241                d.assert_text("depth", "depth 0").await
6242            })
6243    }
6244
6245    /// The stack follows its path: two keys push two pages, and back returns through them.
6246    #[day_macros::test(day_core)]
6247    fn nav_stack_follows_path() -> Case {
6248        Case::new()
6249            .proves(kinds::NAV)
6250            .page(|| stack(Signal::new(vec!["first".into(), "second".into()])))
6251            .drive(|d: Drive| async move {
6252                d.assert_text("page:second", "Page second").await?;
6253                d.wait_idle().await?;
6254                d.nav_back().await?;
6255                d.assert_missing("page:second").await?;
6256                d.assert_text("page:first", "Page first").await?;
6257                d.wait_idle().await?;
6258                d.nav_back().await?;
6259                d.assert_missing("page:first").await?;
6260                d.assert_text("depth", "depth 0").await
6261            })
6262    }
6263
6264    /// A sidebar's items each show their page when selected, as a route.
6265    #[day_macros::test(day_core)]
6266    fn nav_sidebar_selects() -> Case {
6267        Case::new()
6268            .proves(kinds::NAV)
6269            .proves(kinds::NAV_MENU)
6270            .page(|| {
6271                nav(Signal::new("alpha".to_string()))
6272                    .item("alpha", "Alpha", || {
6273                        label("Page Alpha").id(day_core::id!(page_alpha))
6274                    })
6275                    .item("beta", "Beta", || {
6276                        label("Page Beta").id(day_core::id!(page_beta))
6277                    })
6278            })
6279            .drive(|d: Drive| async move {
6280                d.navigate("beta").await?;
6281                d.assert_text("page_beta", "Page Beta").await?;
6282                d.assert_route("beta").await?;
6283                d.wait_idle().await?;
6284                d.navigate("alpha").await?;
6285                d.assert_text("page_alpha", "Page Alpha").await
6286            })
6287    }
6288
6289    /// Tabs show the selected tab's page and switch on a route.
6290    #[day_macros::test(day_core)]
6291    fn nav_tabs_switch() -> Case {
6292        Case::new()
6293            .proves(kinds::NAV)
6294            .page(|| {
6295                nav(Signal::new("alpha".to_string()))
6296                    .presentation(NavPresentation::Tabs)
6297                    .item("alpha", "Alpha", || {
6298                        label("Tab Alpha").id(day_core::id!(tab_alpha))
6299                    })
6300                    .item("beta", "Beta", || {
6301                        label("Tab Beta").id(day_core::id!(tab_beta))
6302                    })
6303            })
6304            .drive(|d: Drive| async move {
6305                d.assert_text("tab_alpha", "Tab Alpha").await?;
6306                d.navigate("beta").await?;
6307                d.assert_text("tab_beta", "Tab Beta").await?;
6308                d.assert_route("beta").await
6309            })
6310    }
6311
6312    /// The page under a cover: a button that opens it and the open value as text.
6313    fn covered(open: Signal<Option<String>>, sheet: bool) -> impl Piece {
6314        let c = cover(open, move |key: &String| {
6315            column((
6316                label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6317                button("Close")
6318                    .action(move || open.set(None))
6319                    .id(day_core::id!(close)),
6320            ))
6321        });
6322        column((
6323            label(move || format!("open {}", open.get().unwrap_or_default()))
6324                .id(day_core::id!(state)),
6325            button("Show")
6326                .action(move || open.set(Some("panel".into())))
6327                .id(day_core::id!(show)),
6328            if sheet { c.sheet().any() } else { c.any() },
6329        ))
6330    }
6331
6332    /// Setting the open value presents the cover; clearing it dismisses it.
6333    #[day_macros::test(day_core)]
6334    fn cover_presents_and_dismisses() -> Case {
6335        Case::new()
6336            .proves_cap(Cap::Cover)
6337            .proves(kinds::COVER)
6338            .page(|| covered(Signal::new(None), false))
6339            .drive(|d: Drive| async move {
6340                d.assert_missing("cover_text").await?;
6341                d.tap("show").await?;
6342                d.assert_text("cover_text", "Cover panel").await?;
6343                d.wait_idle().await?;
6344                d.tap("close").await?;
6345                d.assert_missing("cover_text").await?;
6346                d.assert_text("state", "open ").await
6347            })
6348    }
6349
6350    /// A sheet presents the same way, and going back dismisses it and writes `None` back.
6351    #[day_macros::test(day_core)]
6352    fn cover_sheet_back_dismisses() -> Case {
6353        Case::new()
6354            .proves(kinds::COVER)
6355            .page(|| covered(Signal::new(None), true))
6356            .drive(|d: Drive| async move {
6357                d.tap("show").await?;
6358                d.assert_text("cover_text", "Cover panel").await?;
6359                d.assert_text("state", "open panel").await?;
6360                d.wait_idle().await?;
6361                d.nav_back().await?;
6362                d.assert_missing("cover_text").await?;
6363                d.assert_text("state", "open ").await
6364            })
6365    }
6366
6367    /// A cover bound to a `bool` presents on `true` and dismisses on `false`, and it stays out
6368    /// of the app's route space: it is a panel, not a place (docs/cover.md "Open or closed").
6369    #[day_macros::test(day_core)]
6370    fn cover_bound_to_a_bool() -> Case {
6371        Case::new()
6372            .proves(kinds::COVER)
6373            .page(|| {
6374                let open = Signal::new(false);
6375                column((
6376                    label(move || format!("shown {}", open.get())).id(day_core::id!(state)),
6377                    button("Show")
6378                        .action(move || open.set(true))
6379                        .id(day_core::id!(show)),
6380                    cover(open, move |_| {
6381                        column((
6382                            label("Editor").id(day_core::id!(cover_text)),
6383                            button("Done")
6384                                .action(move || open.set(false))
6385                                .id(day_core::id!(close)),
6386                        ))
6387                    })
6388                    .sheet(),
6389                ))
6390            })
6391            .drive(|d: Drive| async move {
6392                d.assert_missing("cover_text").await?;
6393                d.tap("show").await?;
6394                d.assert_text("cover_text", "Editor").await?;
6395                d.assert_text("state", "shown true").await?;
6396                d.wait_idle().await?;
6397                d.tap("close").await?;
6398                d.assert_missing("cover_text").await?;
6399                d.assert_text("state", "shown false").await
6400            })
6401    }
6402
6403    /// A layout that answers the proposal and remembers the height it was placed at: how a
6404    /// case measures a surface on every toolkit, the mock included, without a number that
6405    /// would only hold for one window size.
6406    pub(crate) struct HeightProbe(pub(crate) Rc<std::cell::Cell<f64>>);
6407
6408    impl day_core::Layout for HeightProbe {
6409        fn measure(
6410            &self,
6411            _cx: &mut dyn day_core::LayoutOps,
6412            _children: &[RNode],
6413            p: day_geometry::Proposal,
6414        ) -> Size {
6415            Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
6416        }
6417        fn place(
6418            &self,
6419            _cx: &mut dyn day_core::LayoutOps,
6420            _children: &[RNode],
6421            bounds: day_geometry::Rect,
6422        ) {
6423            self.0.set(bounds.size.height);
6424        }
6425    }
6426
6427    /// A growable piece that records the height it is laid out at into `into`.
6428    pub(crate) fn height_probe(into: Rc<std::cell::Cell<f64>>) -> impl Piece {
6429        piece_fn(move |cx| {
6430            cx.layout_only(
6431                Rc::new(HeightProbe(into)),
6432                Flex {
6433                    grow_w: true,
6434                    grow_h: true,
6435                    ..Default::default()
6436                },
6437                Boundary::No,
6438            )
6439        })
6440    }
6441
6442    // The heights the half-sheet cases compare: the page's, and the cover content's.
6443    thread_local! {
6444        static HALF_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
6445            (Rc::default(), Rc::default());
6446    }
6447
6448    /// The page under a half sheet: a probe filling the page, the open value as text, a
6449    /// button that opens the sheet, and the sheet with a probe filling its content.
6450    fn half_covered(open: Signal<Option<String>>) -> impl Piece {
6451        let (page_h, cover_h) = HALF_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
6452        page_h.set(0.0);
6453        cover_h.set(0.0);
6454        let sheet = cover(open, move |key: &String| {
6455            column((
6456                label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6457                height_probe(cover_h.clone()),
6458                button("Close")
6459                    .action(move || open.set(None))
6460                    .id(day_core::id!(close)),
6461            ))
6462        })
6463        .half_sheet();
6464        zstack((
6465            height_probe(page_h),
6466            column((
6467                label(move || format!("open {}", open.get().unwrap_or_default()))
6468                    .id(day_core::id!(state)),
6469                button("Show")
6470                    .action(move || open.set(Some("panel".into())))
6471                    .id(day_core::id!(show)),
6472                sheet,
6473            )),
6474        ))
6475    }
6476
6477    /// Whether `probe_h` is a half sheet's content height against the page's `page_h`: at
6478    /// most a little over half (a grabber or handle rides inside the half), and well clear of
6479    /// zero.
6480    pub(crate) fn is_half(page_h: f64, probe_h: f64) -> bool {
6481        page_h > 0.0 && probe_h > page_h * 0.15 && probe_h <= page_h * 0.6
6482    }
6483
6484    /// Wait for a presented sheet's content to be laid out, then judge it with [`is_half`].
6485    /// The frame a native sheet reports lands a turn after the presentation (and on the mock
6486    /// a flush later), so the probe is polled rather than read once.
6487    pub(crate) async fn check_half(
6488        d: &Drive,
6489        what: &str,
6490        heights: &(Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>),
6491    ) -> day_core::conformance::TestResult {
6492        let mut got = (0.0, 0.0);
6493        for _ in 0..40 {
6494            got = (heights.0.get(), heights.1.get());
6495            if is_half(got.0, got.1) {
6496                break;
6497            }
6498            d.pause(0.05).await?;
6499            d.wait_idle().await?;
6500        }
6501        d.check(
6502            is_half(got.0, got.1),
6503            &format!("{what} {} of page {}: between 15% and 60%", got.1, got.0),
6504        )
6505    }
6506
6507    /// A half sheet presents over the page at (about) half its height, and the content
6508    /// underneath stays mounted; clearing the value dismisses it.
6509    #[day_macros::test(day_core)]
6510    fn cover_half_sheet_presents_over_content() -> Case {
6511        Case::new()
6512            .proves(kinds::COVER)
6513            .page(|| half_covered(Signal::new(None)))
6514            .drive(|d: Drive| async move {
6515                d.assert_missing("cover_text").await?;
6516                d.tap("show").await?;
6517                d.assert_text("cover_text", "Cover panel").await?;
6518                d.wait_idle().await?;
6519                let heights = HALF_HEIGHTS.with(std::clone::Clone::clone);
6520                check_half(&d, "half sheet content", &heights).await?;
6521                d.assert_text("state", "open panel").await?;
6522                d.tap("close").await?;
6523                d.assert_missing("cover_text").await?;
6524                d.assert_text("state", "open ").await
6525            })
6526    }
6527
6528    /// Going back dismisses a half sheet and writes `None` back, as it does a sheet.
6529    #[day_macros::test(day_core)]
6530    fn cover_half_sheet_back_dismisses() -> Case {
6531        Case::new()
6532            .proves(kinds::COVER)
6533            .page(|| half_covered(Signal::new(None)))
6534            .drive(|d: Drive| async move {
6535                d.tap("show").await?;
6536                d.assert_text("cover_text", "Cover panel").await?;
6537                d.wait_idle().await?;
6538                d.nav_back().await?;
6539                d.assert_missing("cover_text").await?;
6540                d.assert_text("state", "open ").await
6541            })
6542    }
6543
6544    // The heights the composed-sheet case compares: the page's, and the sheet content's.
6545    thread_local! {
6546        static SHEET_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
6547            (Rc::default(), Rc::default());
6548    }
6549
6550    /// On a toolkit with no native sheet, a `.sheet()` over a wide window is a card centered
6551    /// on the dimmed page: its content lays out shorter than the page, the page stays mounted,
6552    /// and the card's own controls dismiss it.
6553    #[day_macros::test(day_core)]
6554    fn cover_sheet_composes_a_card_on_wide() -> Case {
6555        Case::new()
6556            .proves(kinds::COVER)
6557            .requires_support("composed sheet", || {
6558                if day_core::capability(Cap::CoverSheet) == day_spec::Support::Unsupported {
6559                    day_spec::Support::Native
6560                } else {
6561                    day_spec::Support::Unsupported
6562                }
6563            })
6564            .page(|| {
6565                let (page_h, sheet_h) = SHEET_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
6566                page_h.set(0.0);
6567                sheet_h.set(0.0);
6568                let open = Signal::new(None::<String>);
6569                let sheet = cover(open, move |key: &String| {
6570                    column((
6571                        label(format!("Cover {key}")).id(day_core::id!(cover_text)),
6572                        height_probe(sheet_h.clone()),
6573                        button("Close")
6574                            .action(move || open.set(None))
6575                            .id(day_core::id!(close)),
6576                    ))
6577                })
6578                .sheet()
6579                .unrouted();
6580                zstack((
6581                    height_probe(page_h),
6582                    column((
6583                        label(move || format!("open {}", open.get().unwrap_or_default()))
6584                            .id(day_core::id!(state)),
6585                        button("Show")
6586                            .action(move || open.set(Some("panel".into())))
6587                            .id(day_core::id!(show)),
6588                        sheet,
6589                    )),
6590                ))
6591            })
6592            .drive(|d: Drive| async move {
6593                let _restore = crate::inspector::conformance::RestoreSizeClass;
6594                day_core::override_size_class(day_spec::SizeClass {
6595                    width: day_spec::WidthClass::Expanded,
6596                    height: day_spec::HeightClass::Expanded,
6597                });
6598                d.wait_idle().await?;
6599                d.tap("show").await?;
6600                d.assert_text("cover_text", "Cover panel").await?;
6601                let heights = SHEET_HEIGHTS.with(std::clone::Clone::clone);
6602                let mut got = (0.0, 0.0);
6603                for _ in 0..40 {
6604                    got = (heights.0.get(), heights.1.get());
6605                    if got.0 > 0.0 && got.1 > 0.0 {
6606                        break;
6607                    }
6608                    d.pause(0.05).await?;
6609                    d.wait_idle().await?;
6610                }
6611                d.check(
6612                    got.0 > 0.0 && got.1 > 0.0 && got.1 < got.0,
6613                    &format!("sheet content {} under a page {} tall", got.1, got.0),
6614                )?;
6615                d.assert_text("state", "open panel").await?;
6616                d.tap("close").await?;
6617                d.assert_missing("cover_text").await?;
6618                d.assert_text("state", "open ").await
6619            })
6620    }
6621}