Skip to main content

frust_widgets/nav/
controller.rs

1//! [`NavigatorController`]: the cloneable app-state handle that *records*
2//! navigation ops for a [`NavigatorWidget`]
3//! to drain at its next rebuild, plus the published depth / back-interest /
4//! transition / route-stack read seams the facade and app code observe it
5//! through.
6
7use std::cell::{Cell, RefCell};
8use std::rc::Rc;
9
10use frust_core::{AnyView, View};
11
12use super::ambient::host_reachable;
13use super::options::{
14    BackPolicy, NavOp, NavigatorId, PageBuilder, PopResult, PushOptions, ReplaceOptions,
15    ResultCallback,
16};
17use super::route_state::RouteStack;
18use super::transition::{TransitionSpec, TransitionState};
19
20// Named only by the doc comments moved here with this module's items, so their
21// intra-doc links keep resolving to the same targets they did in `navigator`.
22#[allow(unused_imports)]
23use super::navigator::NavigatorWidget;
24#[allow(unused_imports)]
25use super::transition::PageTransition;
26#[allow(unused_imports)]
27use super::view::navigator;
28#[allow(unused_imports)]
29use frust_core::Widget;
30
31/// The app-state handle to a [`navigator`]: a cloneable op queue an app keeps in
32/// its `Component::State` and drives with [`push`](Self::push)/[`pop`](Self::pop)/
33/// [`replace`](Self::replace). Every clone shares one queue (`Rc`), so the handle
34/// the view carries and the handle event handlers call are the same.
35///
36/// Ops are *recorded*, not applied — the [`NavigatorWidget`] drains and applies
37/// them at its next rebuild (see the [module docs](self)).
38pub struct NavigatorController<State: 'static> {
39    pub(super) ops: Rc<RefCell<Vec<NavOp<State>>>>,
40    /// The current page-stack **depth**, published by the attached
41    /// [`NavigatorWidget`] on every `build`/`rebuild`/`apply_ops`. The widget
42    /// owns the authoritative stack; this shared cell is
43    /// the read seam [`depth`](Self::depth)/[`can_pop`](Self::can_pop) expose so
44    /// the facade's back handler (and app code) can ask "would a pop do
45    /// anything?" without reaching into the widget. `0` until a widget attaches.
46    ///
47    /// `frust-widgets` stays reactive-free: this is a plain `Rc<Cell<_>>`,
48    /// not a signal — a shell/facade polls it at rebuild time (see the timing
49    /// note in `frust-reactive::back`).
50    pub(super) depth: Rc<Cell<usize>>,
51    /// Whether a back press should be *claimed* by the navigator ahead-of-time
52    /// (predictive-back parity) — published by the attached
53    /// [`NavigatorWidget`] alongside [`depth`](Self::depth). `true` iff the stack
54    /// is poppable (`depth > 1`) **or** the top page's [`BackPolicy`] is not
55    /// [`Pop`](BackPolicy::Pop) (a dismissable/veto overlay claims back even at
56    /// the root) — **and** the page hosting this navigator is itself
57    /// input-reachable (the R23 gate; see
58    /// [`NavigatorWidget::reachable`], always satisfied for a top-level
59    /// navigator). This is the signal the facade's back handler computes
60    /// `handles_back` from — it differs from [`can_pop`](Self::can_pop) exactly
61    /// in the depth-1-with-overlay case, where a raw pop would do nothing but the
62    /// overlay still owns the press. Same plain `Rc<Cell<_>>` (reactive-free)
63    /// polled-at-rebuild contract as `depth`.
64    pub(super) back_interest: Rc<Cell<bool>>,
65    /// The published snapshot of the navigator's single in-flight page
66    /// transition, written by the attached [`NavigatorWidget`] at every
67    /// transition edge *and* on every paint frame that advances the driver. The
68    /// read seam is [`transition`](Self::transition), whose doc carries the
69    /// timing contract.
70    ///
71    /// Same reactive-free idiom as [`depth`](Self::depth)/
72    /// [`back_interest`](Self::back_interest) — a plain `Rc<Cell<_>>` of `Copy`
73    /// data, never a signal. Unlike those two it is published from *paint* as
74    /// well as build, which is what makes a frame-exact read possible.
75    pub(super) transition: Rc<Cell<TransitionState>>,
76    /// How many live [`NavigatorWidget`]s currently render this controller's
77    /// stack — incremented by [`NavigatorView::build`] and (if a live widget's
78    /// controller is swapped) by [`NavigatorView::rebuild`]; decremented by
79    /// `teardown` and by that same swap handling for the controller being
80    /// swapped *away from*. Read through [`is_mounted`](Self::is_mounted).
81    ///
82    /// A **liveness** seam, not a published-state one: the three cells above
83    /// answer "what does the stack look like?", this one answers "is this
84    /// navigator in the retained tree at all?". The facade's back arbitration
85    /// needs the latter to tell a navigator that merely did not wire this pass
86    /// from one whose screen was torn down (see `frust::back_glue`'s R44-back
87    /// prune). A count, not a bool, so a reconcile that builds the replacement
88    /// widget before tearing down the old one never reads as unmounted.
89    ///
90    /// **The widget never decrements this cell by looking `self.controller` up
91    /// again** — [`NavigatorWidget`] holds its own clone (`mounted`, alongside
92    /// `depth`/`back_interest`/`transition`), rebound only at `build` and at a
93    /// controller-swap `rebuild`, and every decrement goes through that field.
94    /// A `NavigatorView`'s `self.controller` is whatever the app currently
95    /// hands it — after a swap that is already the *new* controller — so
96    /// `teardown` reading it instead would double-unmount the new one and never
97    /// correct the old one, exactly the structural gap this field closes (see
98    /// [`NavigatorView::rebuild`]'s controller-swap comment).
99    ///
100    /// Same reactive-free `Rc<Cell<_>>` idiom as the rest of the controller.
101    pub(super) mounted: Rc<Cell<usize>>,
102    /// The [`PageEntry::reach`] cell of the page **hosting** this navigator,
103    /// bound by the attached [`NavigatorWidget`] at `build`/`rebuild`; `None`
104    /// for a top-level navigator (and until a widget attaches).
105    ///
106    /// The R23 back-reach gate [`back_interest`](Self::back_interest) reads
107    /// *live*, rather than a value baked into the published cell: the page
108    /// hosting a nested navigator can stop being input-routed on a pass in which
109    /// that navigator does not rebuild at all (a page frozen by
110    /// [`cull_covered_builds`](NavigatorView::cull_covered_builds), or one
111    /// stashed out of the stack by a pop transition), and a baked-in value would
112    /// go stale exactly there — the worst case for this gate.
113    ///
114    /// A `RefCell` slot around a plain `Rc<Cell<bool>>`, like `ops` — a
115    /// *binding* that moves when the widget re-captures its host, wrapping the
116    /// same reactive-free cell idiom as the published state.
117    pub(super) host_reach: Rc<RefCell<Option<Rc<Cell<bool>>>>>,
118    /// The published route-state snapshot — a fourth published slot
119    /// beside `depth`/`back_interest`/`transition`, written by
120    /// [`NavigatorWidget::publish_state`] after every committed stack
121    /// mutation (see `route_state`'s module docs for the staleness contract
122    /// and why an in-flight interactive edge swipe does not publish here).
123    ///
124    /// `RefCell`, not `Cell`: the payload (`RouteStack`) is not `Copy` —
125    /// precedented on this same type by [`ops`](Self::ops) and
126    /// [`host_reach`](Self::host_reach).
127    pub(super) route_stack: Rc<RefCell<RouteStack>>,
128}
129
130impl<State: 'static> Clone for NavigatorController<State> {
131    fn clone(&self) -> Self {
132        Self {
133            ops: Rc::clone(&self.ops),
134            depth: Rc::clone(&self.depth),
135            back_interest: Rc::clone(&self.back_interest),
136            transition: Rc::clone(&self.transition),
137            mounted: Rc::clone(&self.mounted),
138            host_reach: Rc::clone(&self.host_reach),
139            route_stack: Rc::clone(&self.route_stack),
140        }
141    }
142}
143
144impl<State: 'static> Default for NavigatorController<State> {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150impl<State: 'static> NavigatorController<State> {
151    /// A fresh controller with an empty op queue.
152    pub fn new() -> Self {
153        Self {
154            ops: Rc::new(RefCell::new(Vec::new())),
155            depth: Rc::new(Cell::new(0)),
156            back_interest: Rc::new(Cell::new(false)),
157            transition: Rc::new(Cell::new(TransitionState::default())),
158            mounted: Rc::new(Cell::new(0)),
159            host_reach: Rc::new(RefCell::new(None)),
160            route_stack: Rc::new(RefCell::new(RouteStack::default())),
161        }
162    }
163
164    /// Bind (or re-bind) the hosting page's reach cell — called by the attached
165    /// [`NavigatorWidget`] from `build` and every `rebuild` with whatever
166    /// [`ambient_page_reach`] says at that point, so the binding follows the
167    /// navigator if its subtree ever moves between pages.
168    ///
169    /// Deliberately not public: reach is derived by the navigator hosting this
170    /// one, never declared by an app.
171    pub(super) fn bind_host_reach(&self, reach: Option<Rc<Cell<bool>>>) {
172        *self.host_reach.borrow_mut() = reach;
173    }
174
175    /// Whether the page hosting this navigator is input-routed right now — the
176    /// **R23 back-reach gate**, read live (see
177    /// [`host_reach`](Self::host_reach)). `true` for a top-level navigator and
178    /// before a widget attaches.
179    fn host_reachable(&self) -> bool {
180        host_reachable(self.host_reach.borrow().as_ref())
181    }
182
183    /// Whether a live [`NavigatorWidget`] currently renders this controller's
184    /// stack — i.e. whether this navigator is in the retained tree *right now*.
185    ///
186    /// `false` before the first `build` and again after the widget's `teardown`
187    /// (a screen with its own nested navigator, popped). Unlike
188    /// [`depth`](Self::depth)/[`back_interest`](Self::back_interest) this is not
189    /// an advisory snapshot of the stack: it is exact at every point after the
190    /// widget's `build` began, because `build`/`teardown` write it directly.
191    ///
192    /// The facade's back arbitration is the intended consumer: a registered
193    /// controller that is still mounted is still part of the tree, so it must
194    /// keep its place in the arbitration list even on a pass in which it did not
195    /// re-wire; one that is no longer mounted can be released.
196    pub fn is_mounted(&self) -> bool {
197        self.mounted.get() > 0
198    }
199
200    /// Record that a [`NavigatorWidget`] attached to this controller. Called at
201    /// the very top of [`NavigatorView::build`], *before* the root page builder
202    /// runs: that builder may itself wire a nested navigator, and the facade's
203    /// back arbitration must already see this navigator as mounted by then.
204    pub(super) fn mount(&self) {
205        self.mounted.set(self.mounted.get() + 1);
206    }
207
208    // No `unmount` method here deliberately: unmounting always goes through
209    // the widget-owned `mounted` cell (`unmount_cell`, below), never back
210    // through a `NavigatorController` reference — see the `mounted` field
211    // doc's structural-pairing note and `NavigatorView::rebuild`'s
212    // controller-swap handling.
213
214    /// This controller's [`NavigatorId`] — stable across clones, distinct per
215    /// independently constructed controller. See [`NavigatorId`] for the
216    /// liveness caveat.
217    pub fn id(&self) -> NavigatorId {
218        NavigatorId(Rc::as_ptr(&self.ops) as *const u8 as usize)
219    }
220
221    /// The current page-stack depth of the navigator this controller drives, as
222    /// last published by that navigator's `build`/`rebuild`, or `0` if no
223    /// navigator is attached yet.
224    ///
225    /// **Advisory**: this reflects the depth at the last rebuild, so a query
226    /// racing a same-frame stack change sees the previous value (the
227    /// rebuild-time refresh contract — see [`can_pop`](Self::can_pop) and
228    /// `frust-reactive::back`'s timing note).
229    pub fn depth(&self) -> usize {
230        self.depth.get()
231    }
232
233    /// Whether a [`pop`](Self::pop) would actually remove a page — `true` iff
234    /// the navigator has more than one page ([`depth`](Self::depth)` > 1`).
235    ///
236    /// **Advisory**, for exactly the Android back contract: the
237    /// facade's back handler reads this to decide whether a back press pops or
238    /// bubbles to the platform, and publishes it as
239    /// `frust-reactive::set_handles_back`. The authoritative guard stays the
240    /// widget's own `len > 1` check in [`apply_ops`](NavigatorWidget) — a pop at
241    /// the root remains a safe no-op even if this raced stale, so a
242    /// mis-predicted root-level back never removes the last page.
243    pub fn can_pop(&self) -> bool {
244        self.depth.get() > 1
245    }
246
247    /// Whether the navigator claims the next back press ahead-of-time
248    /// (predictive-back parity) — `true` iff the stack is poppable
249    /// **or** the top page declares a non-[`Pop`](BackPolicy::Pop) policy (a
250    /// dismissable/veto overlay). The facade's back handler reads this
251    /// (in preference to [`can_pop`](Self::can_pop)) to compute the shell's
252    /// `handles_back`, so a dismissable overlay at the root still consumes back
253    /// rather than exiting the app.
254    ///
255    /// # Nested navigators: reach follows input routing (R23)
256    ///
257    /// A navigator hosted on a page its own host navigator routes **no input**
258    /// to (a covered page, or the page under a transparent overlay) reports
259    /// `false` here regardless of its own stack: back arbitration reaches
260    /// exactly as far as input does, so a press can never pop an off-screen
261    /// stack while the visible page stays put. Unconditional `true` for the
262    /// reach term at the top level, so a single-navigator app is unaffected.
263    ///
264    /// **Advisory**, published at the last rebuild like [`depth`](Self::depth) —
265    /// a query racing a same-frame stack change sees the previous value; the
266    /// navigator's own [`request_back`](Self::request_back) routing stays
267    /// authoritative regardless (see `frust-reactive::back`'s timing note).
268    pub fn back_interest(&self) -> bool {
269        // The published cell answers for this navigator's own stack; the reach
270        // gate is ANDed HERE (live) rather than baked into the cell, because the
271        // hosting page can stop being input-routed on a pass in which this
272        // navigator never rebuilds — see `host_reach`.
273        self.back_interest.get() && self.host_reachable()
274    }
275
276    /// The navigator's current [`TransitionState`] — the observation seam chrome
277    /// *outside* the navigator subtree (an app bar, a tab bar, a progress
278    /// indicator) drives its own motion from. [`TransitionState::default`] (an
279    /// at-rest depth-0 snapshot) until a navigator attaches.
280    ///
281    /// Published on the **controller**, not the widget, deliberately: chrome that
282    /// wants to match page motion is a *sibling* of the navigator, not a
283    /// descendant, so it can never reach the widget — but it can hold a
284    /// controller clone, exactly as it already does to `push`.
285    ///
286    /// # The timing contract
287    ///
288    /// The progress driver advances in exactly one place — `paint`, off
289    /// `PaintCtx::frame_time` (the No-`Instant::now()` rule in
290    /// `docs/REVIEW_FOCUS.md` forbids any other clock in `frust-widgets`).
291    /// Therefore:
292    ///
293    /// - **A read during your own `Widget::paint`, from a widget painted *after*
294    ///   the navigator, is exact for the current frame.** In a root
295    ///   `Stack(vec![navigator_subtree, chrome])`, `StackWidget::paint` walks its
296    ///   children in order, so `chrome` paints second and reads the value the
297    ///   navigator wrote microseconds earlier **in the same frame**. This is the
298    ///   frame-perfect path; it is the one to use for choreography.
299    /// - **A read during `Component::build` (or any `View::build`/`rebuild`) is
300    ///   always exactly one frame stale** for `progress`, because build precedes
301    ///   paint. Fine for "is a transition running?"; wrong for choreography.
302    /// - **The [`active`](TransitionState::active) edges are the exception.**
303    ///   Both `start_transition` and `finalize_transition` publish from a
304    ///   `BuildCtx` pass, so a build-time reader that builds *after* the navigator
305    ///   sees `active` flip on the very frame it happens. Only intermediate
306    ///   `progress` lags.
307    ///
308    /// The navigator already requests a frame for every frame a transition runs,
309    /// so a paint-time observer needs no wake of its own.
310    pub fn transition(&self) -> TransitionState {
311        self.transition.get()
312    }
313
314    /// The navigator's currently published route-state snapshot — a
315    /// clone, authoritative as of the last publish (see `route_state`'s
316    /// module docs' staleness contract, in particular the interactive-swipe
317    /// window).
318    pub fn route_stack(&self) -> RouteStack {
319        self.route_stack.borrow().clone()
320    }
321
322    /// The route stack's current generation — an O(1) change gate equivalent
323    /// to `route_stack().generation()` but without cloning the whole
324    /// snapshot.
325    pub fn route_generation(&self) -> u64 {
326        self.route_stack.borrow().generation()
327    }
328
329    /// Push an **opaque** page built by `builder` on top of the stack, using the
330    /// navigator's default transition (instant unless the navigator sets one).
331    ///
332    /// Every `push*`/`replace*` builder may return any [`View`]; it is erased
333    /// here.
334    ///
335    /// ```no_run
336    /// use frust_widgets::{NavigatorController, text};
337    /// let nav: NavigatorController<()> = NavigatorController::new();
338    /// nav.push(|| text("details"));
339    /// ```
340    pub fn push<V: View<State>>(&self, builder: impl Fn() -> V + 'static) {
341        self.push_impl(erase_page(builder), true, None, None);
342    }
343
344    /// Push an **opaque** page with an explicit [`TransitionSpec`], overriding the
345    /// navigator's default for this push only. The spec is stored on the pushed
346    /// page and *reversed* when it is later popped.
347    pub fn push_with<V: View<State>>(
348        &self,
349        builder: impl Fn() -> V + 'static,
350        transition: TransitionSpec,
351    ) {
352        self.push_impl(erase_page(builder), true, None, Some(transition));
353    }
354
355    /// Push a **transparent** page (e.g. a dialog/overlay) — the page below it
356    /// stays visible and painted (see [module docs](self)'s paint culling).
357    pub fn push_transparent<V: View<State>>(&self, builder: impl Fn() -> V + 'static) {
358        self.push_impl(erase_page(builder), false, None, None);
359    }
360
361    /// Push an opaque page and register `on_result`, invoked with `&mut State`
362    /// when *this* page is later popped (carrying the pop's [`PopResult`]).
363    ///
364    /// The callback is delivered at the start of the [`NavigatorWidget::event`]
365    /// pass after the pop's rebuild — the first point after the pop where the
366    /// erased app state is in scope (a rebuild carries only a `BuildCtx`).
367    pub fn push_for_result<V: View<State>>(
368        &self,
369        builder: impl Fn() -> V + 'static,
370        on_result: impl Fn(&mut State, PopResult) + 'static,
371    ) {
372        self.push_impl(erase_page(builder), true, Some(Rc::new(on_result)), None);
373    }
374
375    /// Push a **transparent** page (e.g. a dialog/bottom sheet) with an explicit
376    /// [`TransitionSpec`] (e.g. [`PageTransition::M3FadeThrough`] for a dialog,
377    /// [`PageTransition::SlideUp`] for a bottom sheet — a design system's own
378    /// dialog/sheet helpers are the shipped callers),
379    /// and register `on_result`, invoked with `&mut State` when *this* page is
380    /// later popped (carrying the pop's [`PopResult`]) — the modal-with-a-result
381    /// combination [`push_transparent`](Self::push_transparent) and
382    /// [`push_for_result`](Self::push_for_result) each cover only half of.
383    ///
384    /// ```ignore
385    /// // A confirm dialog that reports whether the user confirmed:
386    /// controller.push_transparent_for_result(
387    ///     || dialog_view(),
388    ///     TransitionSpec::duration(PageTransition::M3FadeThrough),
389    ///     |state: &mut State, result: PopResult| {
390    ///         state.confirmed = result.take::<bool>().unwrap_or(false);
391    ///     },
392    /// );
393    /// ```
394    ///
395    /// The callback is delivered the same way [`push_for_result`](Self::push_for_result)'s
396    /// is: at the start of the [`NavigatorWidget::event`] pass after the pop's
397    /// rebuild.
398    pub fn push_transparent_for_result<V: View<State>>(
399        &self,
400        builder: impl Fn() -> V + 'static,
401        transition: TransitionSpec,
402        on_result: impl Fn(&mut State, PopResult) + 'static,
403    ) {
404        self.push_impl(
405            erase_page(builder),
406            false,
407            Some(Rc::new(on_result)),
408            Some(transition),
409        );
410    }
411
412    /// Push a page with an explicit [`PushOptions`] — the full-control variant
413    /// carrying a back-press [`BackPolicy`] (and, for a
414    /// [`DismissAnimated`](BackPolicy::DismissAnimated) overlay, its dismiss
415    /// signal) alongside opacity/transition/result. The dismissable-overlay
416    /// helpers push through this; every other `push*` method
417    /// pushes with [`BackPolicy::Pop`].
418    pub fn push_with_options<V: View<State>>(
419        &self,
420        builder: impl Fn() -> V + 'static,
421        options: PushOptions<State>,
422    ) {
423        self.enqueue(NavOp::Push {
424            builder: erase_page(builder),
425            opaque: options.opaque,
426            on_result: options.on_result,
427            transition: options.transition,
428            back: options.back,
429            dismiss_signal: options.dismiss_signal,
430            on_visibility: options.on_visibility,
431            route: options.route,
432            pop_swipe: options.pop_swipe,
433        });
434    }
435
436    /// Shared push-op construction every `push*` method above funnels through —
437    /// the five public variants differ only in which of `opaque`/`on_result`/
438    /// `transition` they fix vs. expose. All push with [`BackPolicy::Pop`] and
439    /// no dismiss signal, and no visibility observer; a page wanting any of those
440    /// uses [`push_with_options`](Self::push_with_options).
441    fn push_impl(
442        &self,
443        builder: PageBuilder<State>,
444        opaque: bool,
445        on_result: Option<ResultCallback<State>>,
446        transition: Option<TransitionSpec>,
447    ) {
448        self.enqueue(NavOp::Push {
449            builder,
450            opaque,
451            on_result,
452            transition,
453            back: BackPolicy::Pop,
454            dismiss_signal: None,
455            on_visibility: None,
456            route: None,
457            pop_swipe: None,
458        });
459    }
460
461    /// Pop the top page with no result payload (a plain back-navigation). A pop
462    /// of the last/root page is ignored (a navigator always keeps one page).
463    pub fn pop(&self) {
464        self.enqueue(NavOp::Pop {
465            result: PopResult::empty(),
466        });
467    }
468
469    /// Pop the top page, handing `result` to its pusher-registered
470    /// [`push_for_result`](Self::push_for_result) callback.
471    pub fn pop_with_result(&self, result: PopResult) {
472        self.enqueue(NavOp::Pop { result });
473    }
474
475    /// Route a back press through the top page's [`BackPolicy`] (the
476    /// entry the facade's back handler drives instead of a bare
477    /// [`pop`](Self::pop)):
478    ///
479    /// - [`Pop`](BackPolicy::Pop) → a normal pop (transitions preserved; a safe
480    ///   no-op at the root);
481    /// - [`DismissAnimated`](BackPolicy::DismissAnimated) → fires the top page's
482    ///   dismiss signal (stack unchanged; the overlay animates its own exit and
483    ///   pops itself), see [`BackPolicy`]'s observation seam;
484    /// - [`Veto`](BackPolicy::Veto) → the press is consumed but nothing happens.
485    ///
486    /// Recorded like every other op and applied at the next rebuild (never
487    /// self-mutating mid-event). Whether this call *would* claim the press is
488    /// [`back_interest`](Self::back_interest).
489    pub fn request_back(&self) {
490        self.enqueue(NavOp::RequestBack);
491    }
492
493    /// Replace the top page in place with an opaque page built by `builder`,
494    /// using the navigator's default transition.
495    pub fn replace<V: View<State>>(&self, builder: impl Fn() -> V + 'static) {
496        self.enqueue(NavOp::Replace {
497            builder: erase_page(builder),
498            opaque: true,
499            transition: None,
500            route: None,
501        });
502    }
503
504    /// Replace the top page with an explicit [`TransitionSpec`], overriding the
505    /// navigator's default for this replace only.
506    pub fn replace_with<V: View<State>>(
507        &self,
508        builder: impl Fn() -> V + 'static,
509        transition: TransitionSpec,
510    ) {
511        self.enqueue(NavOp::Replace {
512            builder: erase_page(builder),
513            opaque: true,
514            transition: Some(transition),
515            route: None,
516        });
517    }
518
519    /// Replace the top page with an explicit [`ReplaceOptions`] — the
520    /// full-control variant carrying a route identity alongside opacity
521    /// and transition. [`Router::go`](super::router::Router::go)/
522    /// [`Router::replace`](super::router::Router::replace) push through this.
523    pub fn replace_with_options<V: View<State>>(
524        &self,
525        builder: impl Fn() -> V + 'static,
526        options: ReplaceOptions,
527    ) {
528        self.enqueue(NavOp::Replace {
529            builder: erase_page(builder),
530            opaque: options.opaque,
531            transition: options.transition,
532            route: options.route,
533        });
534    }
535
536    /// Record `op`, then raise [`frust_core::mark_pending_result_flush`] so the
537    /// next tick's mobile frame gate `Run`s and reaches the rebuild that drains
538    /// it — the same guarantee [`finalize_transition`](NavigatorWidget::finalize_transition)
539    /// already gives a pop-result callback, reused here for a different reason:
540    /// this flag is not just "a callback needs `&mut State`", it is the shell's
541    /// one thread-affine "something is owed, run the next frame regardless of
542    /// what else is dirty" side channel, and a queued op recorded from outside
543    /// any input/signal path (a `spawn_local` continuation, e.g.) needs exactly
544    /// that with no callback involved at all. Without it a page could mount and
545    /// sit unpainted until whatever input happened to arrive next forced a
546    /// frame — see the [module docs](self).
547    ///
548    /// Unconditional, on every op, deliberately, even though the shared flag's
549    /// other reader (`RenderRoot::rebuild`'s pending-flush convergence loop)
550    /// cannot tell "just force a run" apart from "a callback is genuinely
551    /// owed": the frame that applies a queued op also pays one extra, empty
552    /// build + view-diff pass it did not strictly need. That pass is
553    /// bounded (never more than one here, since nothing re-raises the flag for
554    /// a plain structural op) and lands only on the frame a nav op was actually
555    /// queued, not on every frame — a cost this crate's authoring toolkit
556    /// already treats as affordable (rebuilds are cheap by construction) and a
557    /// small, known price next to the bug it replaces: a page mounted with zero
558    /// frames painted for 15+ seconds.
559    fn enqueue(&self, op: NavOp<State>) {
560        self.ops.borrow_mut().push(op);
561        frust_core::mark_pending_result_flush();
562    }
563
564    /// Take the queued ops (leaving the queue empty). Called by
565    /// [`NavigatorView::rebuild`]/`build`.
566    pub(super) fn drain(&self) -> Vec<NavOp<State>> {
567        std::mem::take(&mut *self.ops.borrow_mut())
568    }
569}
570
571/// Erase a page builder at the API boundary: the public `push*`/`replace*`
572/// family (and the navigator/router entry points) accept a closure returning
573/// any [`View`] and store it as the erased [`PageBuilder`] the op queue holds.
574pub(super) fn erase_page<State: 'static, V: View<State>>(
575    builder: impl Fn() -> V + 'static,
576) -> PageBuilder<State> {
577    Rc::new(move || AnyView::new(builder()))
578}