Skip to main content

g3_route_transitions/
lib.rs

1#![warn(missing_docs)]
2//! Route-owned View Transition helpers for Dioxus Router.
3//!
4//! Using the crate takes three pieces, and all three are needed before every
5//! transition is visible:
6//!
7//! 1. **Route metadata.** `#[derive(RouteTransitions)]` on your `Routable`
8//!    enum decides *which* [`NavigationTransition`] runs between two routes.
9//! 2. **Snapshot regions.** Wrapper components mark *which parts of the DOM*
10//!    move. A transition only animates the regions it knows about (see
11//!    [What moves](#what-moves)).
12//! 3. **Animated navigation.** [`animated_navigate`], [`try_animated_back`],
13//!    and [`animated_back_or_navigate`] capture the old page before changing
14//!    the route. Calling `navigator().push(...)` directly skips the animation.
15//!
16//! # Quick start
17//!
18//! ```rust,no_run
19//! use dioxus::prelude::*;
20//! use g3_route_transitions::{
21//!     RouteTransitionApp, RouteTransitionBaseRegion, RouteTransitionPageRegion, RouteTransitions,
22//!     animated_back_or_navigate, animated_navigate,
23//! };
24//!
25//! #[derive(Clone, PartialEq, Routable, RouteTransitions)]
26//! enum Route {
27//!     #[transition(layer = stack_root)]
28//!     #[route("/")]
29//!     Home {},
30//!
31//!     #[transition(layer = stack_page)]
32//!     #[route("/details/:id")]
33//!     Details { id: u32 },
34//!
35//!     #[transition(layer = sheet)]
36//!     #[route("/compose")]
37//!     Compose {},
38//! }
39//!
40//! #[component]
41//! fn App() -> Element {
42//!     // The overlay region: the part that rises and falls for sheets.
43//!     rsx! { RouteTransitionApp { Router::<Route> {} } }
44//! }
45//!
46//! // Ordinary (non-sheet) pages sit in a base region and wrap their content in
47//! // a page region. The base region stays put and dims under a sheet; the page
48//! // region slides for `Forward`/`Backward`.
49//! #[component]
50//! fn Home() -> Element {
51//!     rsx! {
52//!         RouteTransitionBaseRegion {
53//!             RouteTransitionPageRegion {
54//!                 h1 { "Home" }
55//!                 button {
56//!                     onclick: move |_| async move { animated_navigate(Route::Details { id: 1 }).await },
57//!                     "Open details"
58//!                 }
59//!                 button {
60//!                     onclick: move |_| async move { animated_navigate(Route::Compose {}).await },
61//!                     "Compose"
62//!                 }
63//!             }
64//!         }
65//!     }
66//! }
67//!
68//! #[component]
69//! fn Details(id: u32) -> Element {
70//!     rsx! {
71//!         RouteTransitionBaseRegion {
72//!             RouteTransitionPageRegion {
73//!                 button {
74//!                     onclick: move |_| async move { animated_back_or_navigate(Route::Home {}).await },
75//!                     "Back"
76//!                 }
77//!                 "Details {id}"
78//!             }
79//!         }
80//!     }
81//! }
82//!
83//! // Sheets render *without* a base or page region, so the whole sheet is
84//! // captured as part of the overlay.
85//! #[component]
86//! fn Compose() -> Element {
87//!     rsx! {
88//!         button {
89//!             onclick: move |_| async move { animated_back_or_navigate(Route::Home {}).await },
90//!             "Close"
91//!         }
92//!     }
93//! }
94//!
95//! fn main() {
96//!     dioxus::launch(App);
97//! }
98//! ```
99//!
100//! With this setup:
101//!
102//! | Navigation | Transition |
103//! |---|---|
104//! | Home → Details | `Forward`, and Back is `Backward` |
105//! | Home or Details → Compose | `PresentSheet`, and Back is `DismissSheet` |
106//! | Details(1) → Details(2) | `CrossFade`, since nothing relates two `stack_page` values |
107//!
108//! The [`RouteTransitions` derive](derive@RouteTransitions) documents every
109//! option and the exact rule order.
110//!
111//! # What moves
112//!
113//! Each transition animates specific snapshot regions. Anything outside them
114//! is part of the root snapshot.
115//!
116//! | Transition | Animated regions | Everything else |
117//! |---|---|---|
118//! | `CrossFade` | root and [`RouteTransitionBaseRegion`] fade | – |
119//! | `Forward` / `Backward` | [`RouteTransitionPageRegion`] slides with platform motion; a [`RouteTransitionSegmentRegion`] *outside* any page slides as a full-width filmstrip | root and base region switch instantly |
120//! | `PresentSheet` / `DismissSheet` | [`RouteTransitionOverlayRegion`] (added by [`RouteTransitionApp`]) rises or falls; the base region and page region underneath dim (and on iOS, scale) | root is hidden |
121//! | `Instant` | nothing; the route changes without a View Transition | – |
122//!
123//! In every transition, [`RouteTransitionPersistentRegion`] stays in place above
124//! all other snapshots, such as a desktop rail beside a rising sheet.
125//!
126//! Consequences worth knowing:
127//!
128//! - [`RouteTransitionApp`] on its own only produces visible cross-fades.
129//!   `Forward`/`Backward` need a [`RouteTransitionPageRegion`] or
130//!   [`RouteTransitionSegmentRegion`], and sheets need a base region to rise over.
131//! - A sheet route must not render a base region or page region. Those are
132//!   captured separately from the overlay, so the sheet's content would be
133//!   missing from the rising image.
134//! - A segment inside a [`RouteTransitionPageRegion`] never moves by itself; the
135//!   whole page moves instead. Use segments without a page wrapper for tabbed
136//!   content that should slide under a fixed header.
137//! - Persistent chrome only stays still if both routes render it in the same
138//!   place, sheet routes included. Otherwise it fades.
139//! - Each region may appear at most once in the document at a time. Duplicate
140//!   `view-transition-name`s make the browser skip the animation.
141//!
142//! # Platform motion
143//!
144//! [`Platform`] picks the visual style for the same semantic transition.
145//! Call [`set_platform`] at startup (and whenever the app's mode changes);
146//! otherwise [`platform`] falls back to [`detect_platform`].
147//!
148//! Animations are skipped, and the route is changed directly, when the
149//! browser lacks `document.startViewTransition` or the user prefers reduced
150//! motion.
151mod browser_history;
152
153pub use browser_history::use_browser_history_transitions;
154use dioxus::{document::eval, prelude::*};
155pub use g3_route_transitions_macros::RouteTransitions;
156use manganis::{Asset, asset};
157use std::sync::atomic::{AtomicU8, Ordering};
158/// The stylesheet backing every transition. Link it once via
159/// [`RouteTransitionStyles`] (or [`RouteTransitionApp`]), or attach it
160/// yourself if the app manages its own `document::Link` tags.
161///
162/// Besides the transition rules, the stylesheet gives `html` and `body`
163/// `min-height: 100%` and a background of `--route-transition-bg` (falling
164/// back to `--color-bg`, then `#f8f8f8`). The region classes also set layout
165/// styles; see each class constant.
166pub static ROUTE_TRANSITIONS_CSS: Asset = asset!("/assets/route_transitions.css");
167/// Class applied by [`RouteTransitionBaseRegion`].
168///
169/// The element always has `view-transition-name: base`. It cross-fades in
170/// `CrossFade`, switches instantly in `Forward`/`Backward`, and dims under a
171/// sheet. It is styled as a full-height flex column
172/// (`display: flex; flex-direction: column; min-height: 100dvh`) with an
173/// opaque background. A base region that is a direct child of a
174/// [`RouteTransitionPageRegion`] is not named.
175pub const ROUTE_TRANSITION_BASE_REGION_CLASS: &str = "route-transition-base-region";
176/// Class applied by [`RouteTransitionOverlayRegion`] and
177/// [`RouteTransitionApp`].
178///
179/// The element is named `overlay` only during `PresentSheet` and
180/// `DismissSheet`, when it rises or falls above the base region. It is styled
181/// as a full-height flex column with an opaque background.
182pub const ROUTE_TRANSITION_OVERLAY_REGION_CLASS: &str = "route-transition-overlay-region";
183/// Class applied by [`RouteTransitionSegmentRegion`].
184///
185/// The element is named `segment` only during `Forward` and `Backward`, when
186/// it slides the full width of its own box as a filmstrip on both platforms.
187/// Inside a [`RouteTransitionPageRegion`] it is not named.
188pub const ROUTE_TRANSITION_SEGMENT_REGION_CLASS: &str = "route-transition-segment-region";
189/// Class applied by [`RouteTransitionPageRegion`].
190///
191/// The element is named `page` during `Forward`, `Backward`, `PresentSheet`,
192/// and `DismissSheet`. It slides with platform motion for the first two and
193/// dims under a sheet for the others. It is styled as a viewport-height flex
194/// column (`height: 100dvh; overflow: hidden`) with an opaque background.
195pub const ROUTE_TRANSITION_PAGE_REGION_CLASS: &str = "route-transition-page-region";
196/// Class applied by [`RouteTransitionPersistentRegion`].
197///
198/// The element is always named `persistent` and never animates. It paints
199/// above every other snapshot, a rising or falling sheet included, so chrome
200/// a sheet should cover must not carry it. If only one of the two
201/// routes renders it, it fades in or out instead. The stylesheet applies no
202/// layout to it. Libraries that only want this behavior at some breakpoints
203/// can set `view-transition-name: persistent` themselves instead of using the
204/// class.
205pub const ROUTE_TRANSITION_PERSISTENT_REGION_CLASS: &str = "route-transition-persistent-region";
206/// Class for a shell around a [`RouteTransitionPageRegion`] that holds chrome a
207/// sheet should cover, such as a phone's bottom tab bar.
208///
209/// The page slides by itself for `Forward` and `Backward`, so chrome beside
210/// it stays still. But under a routed sheet only the named page stays on
211/// screen (it dims, and scales on iOS) while the rest of the old route is
212/// hidden, so a tab bar beside the page vanished the moment a sheet started to
213/// rise. During sheet transitions a frame whose direct child is the page is
214/// captured as the page instead, tab bar included.
215///
216/// A frame with persistent chrome among its direct children (a desktop rail)
217/// is left alone: the rail is already captured on its own, and the page is the
218/// part to dim beside it. Apply the class to the shell unconditionally, or
219/// render a [`RouteTransitionPageFrame`]; g3-ui's `TabLayout` carries the class.
220pub const ROUTE_TRANSITION_PAGE_FRAME_CLASS: &str = "route-transition-page-frame";
221fn merge_transition_class(base: &'static str, extra: Option<&str>) -> String {
222    match extra {
223        Some(extra) if !extra.is_empty() => format!("{base} {extra}"),
224        _ => base.to_string(),
225    }
226}
227/// Content that stays in place during navigation and dims underneath a
228/// presented sheet: typically an ordinary page's shell, including a tab bar.
229///
230/// Render one in every non-sheet route. Sheet routes must not render one,
231/// or the sheet's content is captured here instead of rising with the
232/// overlay. See [What moves](crate#what-moves).
233///
234/// `class` is appended to [`ROUTE_TRANSITION_BASE_REGION_CLASS`].
235#[component]
236pub fn RouteTransitionBaseRegion(children: Element, class: Option<String>) -> Element {
237    let class = merge_transition_class(ROUTE_TRANSITION_BASE_REGION_CLASS, class.as_deref());
238    rsx! {
239        div { class, {children} }
240    }
241}
242/// Content that rises over the base region for `PresentSheet` and falls away
243/// for `DismissSheet`.
244///
245/// [`RouteTransitionApp`] already provides one around the whole app, which is
246/// what most applications want. Use this component directly only when the
247/// app shell is assembled from [`RouteTransitionStyles`] by hand. Render at
248/// most one at a time.
249///
250/// `class` is appended to [`ROUTE_TRANSITION_OVERLAY_REGION_CLASS`].
251#[component]
252pub fn RouteTransitionOverlayRegion(children: Element, class: Option<String>) -> Element {
253    let class = merge_transition_class(ROUTE_TRANSITION_OVERLAY_REGION_CLASS, class.as_deref());
254    rsx! {
255        div { class, {children} }
256    }
257}
258/// Content that slides by itself for `Forward` and `Backward`, such as the
259/// body of a segmented control under a fixed header.
260///
261/// Both the outgoing and incoming segments travel the full width of the box
262/// together, clipped to it. This is the same on iOS and Material. Everything
263/// outside the segment switches instantly. A segment inside a
264/// [`RouteTransitionPageRegion`] does not move by itself, because the page moves
265/// instead.
266///
267/// `class` is appended to [`ROUTE_TRANSITION_SEGMENT_REGION_CLASS`].
268#[component]
269pub fn RouteTransitionSegmentRegion(children: Element, class: Option<String>) -> Element {
270    let class = merge_transition_class(ROUTE_TRANSITION_SEGMENT_REGION_CLASS, class.as_deref());
271    rsx! {
272        div { class, {children} }
273    }
274}
275/// One routed page, captured as a single viewport-sized image for `Forward`
276/// and `Backward` (platform push/pop motion) and dimmed under sheets.
277///
278/// This is the region that makes stack navigation visible. Place it inside
279/// the page's [`RouteTransitionBaseRegion`], around the header and body, and
280/// leave persistent chrome such as a tab bar outside it so that chrome stays
281/// still. Segments and direct-child base regions inside the page are
282/// suppressed so the page moves as one piece.
283///
284/// `class` is appended to [`ROUTE_TRANSITION_PAGE_REGION_CLASS`].
285#[component]
286pub fn RouteTransitionPageRegion(children: Element, class: Option<String>) -> Element {
287    let class = merge_transition_class(ROUTE_TRANSITION_PAGE_REGION_CLASS, class.as_deref());
288    rsx! {
289        div { class, {children} }
290    }
291}
292/// Chrome that stays exactly where it is during every transition, such as a
293/// desktop navigation rail beside the page.
294///
295/// It is captured on its own and painted above every other snapshot, so it
296/// doesn't slide with the page, dim under a sheet, or get covered by one. Chrome
297/// a sheet should cover, such as a phone's bottom tab bar, belongs in a
298/// [`ROUTE_TRANSITION_PAGE_FRAME_CLASS`] shell instead. For it to stay still,
299/// the routes on both sides of a transition must render it in the same place,
300/// including sheet routes. If only one side renders it, it fades. Render at
301/// most one at a time.
302///
303/// `class` is appended to [`ROUTE_TRANSITION_PERSISTENT_REGION_CLASS`].
304#[component]
305pub fn RouteTransitionPersistentRegion(children: Element, class: Option<String>) -> Element {
306    let class = merge_transition_class(ROUTE_TRANSITION_PERSISTENT_REGION_CLASS, class.as_deref());
307    rsx! {
308        div { class, {children} }
309    }
310}
311/// A shell around a [`RouteTransitionPageRegion`] and the chrome a sheet should
312/// cover, such as a phone's bottom tab bar.
313///
314/// The page still slides by itself for `Forward` and `Backward`, while the
315/// chrome beside it stays still. Under a routed sheet the whole frame dims
316/// (and scales on iOS) as the page, so the tab bar stays under the rising
317/// sheet instead of vanishing. Make the page a direct child. A frame with a
318/// [`RouteTransitionPersistentRegion`] among its direct children is left
319/// alone, and only the page dims beside it. See
320/// [`ROUTE_TRANSITION_PAGE_FRAME_CLASS`].
321///
322/// `class` is appended to [`ROUTE_TRANSITION_PAGE_FRAME_CLASS`].
323#[component]
324pub fn RouteTransitionPageFrame(children: Element, class: Option<String>) -> Element {
325    let class = merge_transition_class(ROUTE_TRANSITION_PAGE_FRAME_CLASS, class.as_deref());
326    rsx! {
327        div { class, {children} }
328    }
329}
330/// A semantic navigation event chosen by [`RouteTransitions::transition_to`]
331/// or [`RouteTransitions::transition_back`].
332///
333/// The variant says *what happened* (drill in, present a sheet, and so on).
334/// The stylesheet decides how it looks for the current [`Platform`], and
335/// which regions move is described in [What moves](crate#what-moves). While a
336/// transition runs, [`data_value`](Self::data_value) is published on `<html>`
337/// as `data-route-transition`.
338///
339/// Directions are physical. `Forward` always brings the new page in from the
340/// right, including in right-to-left documents.
341#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
342pub enum NavigationTransition {
343    /// No View Transition: the route changes immediately. The derive returns
344    /// this for identical routes, equal peer `order`s, and same-variant
345    /// `history = replace` updates.
346    Instant,
347    /// A quick cross-dissolve of the root and base region, the same on both
348    /// platforms. This is what unrelated routes get.
349    #[default]
350    CrossFade,
351    /// Drill in: the new page enters from the right. On iOS it slides over the
352    /// old page, which shifts 30% left and dims (UINavigationController push).
353    /// On Material both pages move 30px with a fade-through (Shared Axis X).
354    /// A standalone segment slides full-width on both platforms.
355    Forward,
356    /// Drill out: the exact reverse of [`Forward`](Self::Forward).
357    Backward,
358    /// A routed sheet rises from the bottom over the current page, which dims
359    /// in place. On iOS the page also scales down and rounds its corners. On
360    /// Material the sheet moves 20% while fading in.
361    PresentSheet,
362    /// The sheet falls away to reveal the page beneath: the reverse of
363    /// [`PresentSheet`](Self::PresentSheet).
364    DismissSheet,
365}
366impl NavigationTransition {
367    /// The `data-route-transition` attribute value the stylesheet keys on:
368    /// `cross-fade`, `forward`, `backward`, `present-sheet`, or
369    /// `dismiss-sheet`. `Instant` is `instant`, though no transition runs to
370    /// publish it.
371    pub fn data_value(self) -> &'static str {
372        match self {
373            NavigationTransition::Instant => "instant",
374            NavigationTransition::CrossFade => "cross-fade",
375            NavigationTransition::Forward => "forward",
376            NavigationTransition::Backward => "backward",
377            NavigationTransition::PresentSheet => "present-sheet",
378            NavigationTransition::DismissSheet => "dismiss-sheet",
379        }
380    }
381}
382/// Platform styling mode for the transition stylesheet - mirrors the
383/// iOS-vs-Material split app component libraries (e.g. Ionic, g3-ui) already
384/// use for widget styling, so the same signal can drive both.
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum Platform {
387    /// UINavigationController/UIKit-flavored motion: parallax push where the
388    /// outgoing page slides back and dims rather than leaving the screen,
389    /// page-sheet presentation, quick cross-dissolves.
390    Ios,
391    /// Material Design 3 motion: shared-axis slides, quick cross-dissolves,
392    /// and bottom sheets with a scrim.
393    Material,
394}
395impl Platform {
396    /// The `data-route-transition-platform` attribute value the stylesheet
397    /// keys on.
398    pub fn data_value(self) -> &'static str {
399        match self {
400            Platform::Ios => "ios",
401            Platform::Material => "material",
402        }
403    }
404}
405/// The platform set by [`set_platform`]: `0` until it is called, then `1` for
406/// iOS or `2` for Material. Process-wide, so a platform set on one thread
407/// applies to navigation started on another.
408static GLOBAL_PLATFORM: AtomicU8 = AtomicU8::new(0);
409/// Explicitly set the platform used to pick a transition's visual style.
410/// Call this once at startup and again whenever the app's platform mode
411/// changes (e.g. a user-facing iOS/Material style toggle).
412pub fn set_platform(platform: Platform) {
413    let value = match platform {
414        Platform::Ios => 1,
415        Platform::Material => 2,
416    };
417    GLOBAL_PLATFORM.store(value, Ordering::Relaxed);
418}
419/// The platform currently used to style transitions. Falls back to
420/// compile-time/runtime auto-detection if [`set_platform`] was never called.
421pub fn platform() -> Platform {
422    match GLOBAL_PLATFORM.load(Ordering::Relaxed) {
423        1 => Platform::Ios,
424        2 => Platform::Material,
425        _ => detect_platform(),
426    }
427}
428/// Detect a reasonable default platform from `cfg(target_os)` (native
429/// mobile builds) or, on wasm, from the user agent.
430pub fn detect_platform() -> Platform {
431    #[cfg(target_os = "ios")]
432    {
433        Platform::Ios
434    }
435    #[cfg(target_os = "android")]
436    {
437        Platform::Material
438    }
439    #[cfg(all(
440        target_arch = "wasm32",
441        not(target_os = "ios"),
442        not(target_os = "android")
443    ))]
444    {
445        detect_platform_web()
446    }
447    #[cfg(not(any(target_os = "ios", target_os = "android", target_arch = "wasm32")))]
448    {
449        Platform::Material
450    }
451}
452#[cfg(target_arch = "wasm32")]
453fn detect_platform_web() -> Platform {
454    let Some(window) = web_sys::window() else {
455        return Platform::Material;
456    };
457    let navigator = window.navigator();
458    let user_agent = navigator.user_agent().unwrap_or_default().to_lowercase();
459    let platform = navigator.platform().unwrap_or_default().to_lowercase();
460    let max_touch_points = navigator.max_touch_points();
461    let is_iphone_or_ipod = user_agent.contains("iphone") || user_agent.contains("ipod");
462    let is_ipad = user_agent.contains("ipad")
463        || (platform.contains("mac") && max_touch_points > 1 && user_agent.contains("safari"));
464    if is_iphone_or_ipod || is_ipad {
465        Platform::Ios
466    } else {
467        Platform::Material
468    }
469}
470/// The navigation role a route declares with `#[transition(layer = ...)]`.
471///
472/// Code generated by the [`RouteTransitions` derive](derive@RouteTransitions)
473/// uses the layer to pick transitions. It does not choose which DOM element
474/// moves; snapshot regions do that. See the derive documentation for the rules
475/// each layer takes part in.
476#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
477pub enum RouteTransitionLayer {
478    /// `layer = plain`: an ordinary page with no stack or sheet role. This is
479    /// the default.
480    #[default]
481    Plain,
482    /// `layer = sheet`: presented over the previous page with `PresentSheet`
483    /// and removed with `DismissSheet`.
484    Sheet,
485    /// `layer = stack_root`: the root of a navigation stack, such as a
486    /// bottom-tab destination. Moving to a `StackPage` is `Forward`.
487    StackRoot,
488    /// `layer = stack_page`: a full-screen page above a stack root. Moving to
489    /// a `StackRoot` and Back are both `Backward`.
490    StackPage,
491}
492/// Decides which [`NavigationTransition`] runs between two routes and how
493/// history is written.
494///
495/// Usually generated by the [`RouteTransitions` derive](derive@RouteTransitions),
496/// whose documentation lists the exact rules. Implement it by hand when the
497/// choice depends on route data the derive cannot express.
498pub trait RouteTransitions: PartialEq {
499    /// The transition for [`animated_navigate`] from `self` to `next`.
500    ///
501    /// Returning [`NavigationTransition::Instant`] changes the route without a
502    /// View Transition.
503    fn transition_to(&self, next: &Self) -> NavigationTransition;
504    /// Whether [`animated_navigate`] from `self` to `next` replaces the current
505    /// history entry instead of pushing a new one.
506    ///
507    /// The derive returns `true` for matching `history = replace` rules and
508    /// for `handoff_from` sources. The default always pushes.
509    fn replaces_history(&self, _next: &Self) -> bool {
510        false
511    }
512    /// The transition for [`try_animated_back`] and
513    /// [`animated_back_or_navigate`] when leaving `self`.
514    ///
515    /// No destination is passed, because the router does not reveal the
516    /// previous entry until after the old page has been captured. The derive
517    /// uses only `self`'s layer: `DismissSheet` for a sheet, `Backward` for a
518    /// stack page, and `CrossFade` otherwise. The default is `CrossFade`.
519    fn transition_back(&self) -> NavigationTransition {
520        NavigationTransition::CrossFade
521    }
522}
523/// Links [`ROUTE_TRANSITIONS_CSS`] and renders its children unchanged.
524///
525/// Use it when building the app shell from
526/// [`RouteTransitionOverlayRegion`] by hand. Otherwise use
527/// [`RouteTransitionApp`], which includes it. It provides no context.
528#[component]
529pub fn RouteTransitionStyles(children: Element) -> Element {
530    rsx! {
531        document::Link { rel: "stylesheet", href: ROUTE_TRANSITIONS_CSS }
532        {children}
533    }
534}
535/// The app-level wrapper: links the stylesheet and wraps its children in an
536/// overlay region (the part that rises and falls for sheets). Place
537/// `Router::<Route> {}` inside it.
538///
539/// On its own this only produces visible cross-fades. Pages also need a
540/// [`RouteTransitionBaseRegion`] and a [`RouteTransitionPageRegion`] (or
541/// [`RouteTransitionSegmentRegion`]) for stack and sheet motion; see
542/// [What moves](crate#what-moves).
543///
544/// `class` is appended to [`ROUTE_TRANSITION_OVERLAY_REGION_CLASS`].
545#[component]
546pub fn RouteTransitionApp(children: Element, class: Option<String>) -> Element {
547    let class = merge_transition_class(ROUTE_TRANSITION_OVERLAY_REGION_CLASS, class.as_deref());
548    rsx! {
549        RouteTransitionStyles {
550            div { class, {children} }
551        }
552    }
553}
554/// Placeholders substituted before the script is evaluated.
555///
556/// These used to arrive over the eval channel, which cost two round trips
557/// between wasm and JS before the transition could start — dead time between
558/// the tap and the first frame of the animation. Both values are known on the
559/// Rust side already, so they are written into the script instead. The
560/// animation and platform come from fixed enums, so there is nothing to escape;
561/// the route paths are written as escaped string literals, placeholder quotes
562/// included.
563const ANIMATION_PLACEHOLDER: &str = "__DX_ROUTE_TRANSITION_ANIMATION__";
564const PLATFORM_PLACEHOLDER: &str = "__DX_ROUTE_TRANSITION_PLATFORM__";
565const FROM_PLACEHOLDER: &str = "\"__DX_ROUTE_TRANSITION_FROM__\"";
566const TO_PLACEHOLDER: &str = "\"__DX_ROUTE_TRANSITION_TO__\"";
567const SURFACE_SELECTOR_PLACEHOLDER: &str = "\"__DX_ROUTE_TRANSITION_SURFACE_SELECTOR__\"";
568/// The selector the script reads the app's surface color from, built from the
569/// class constants so the two cannot drift apart.
570fn surface_selector() -> String {
571    format!(".{ROUTE_TRANSITION_PAGE_REGION_CLASS}, .{ROUTE_TRANSITION_BASE_REGION_CLASS}")
572}
573const VIEW_TRANSITION_NAVIGATE: &str = r#"
574const animation = "__DX_ROUTE_TRANSITION_ANIMATION__";
575const platform = "__DX_ROUTE_TRANSITION_PLATFORM__";
576// The route being left, and the one being entered when it is known. Back does
577// not know its destination until the router has popped, so it leaves `to`
578// empty. Published on <html> so app CSS can scope snapshot naming to the routes
579// involved - one sheet opening can want an element lifted that another does not.
580const from = "__DX_ROUTE_TRANSITION_FROM__";
581const to = "__DX_ROUTE_TRANSITION_TO__";
582// The regions whose background is the app's surface, page first.
583const surfaceSelector = "__DX_ROUTE_TRANSITION_SURFACE_SELECTOR__";
584const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches ?? false;
585
586// View-transition snapshots are painted in a document-level pseudo tree. They
587// do not inherit a theme that is scoped to an app shell, and they are not
588// clipped by an embedded shell's rounded/overflow-hidden ancestor. Capture the
589// resolved paint values for both routes and publish them on <html>, where the
590// pseudo tree can inherit them.
591const dxRouteTransitionOpaqueBackground = (element) => {
592    if (!element) return null;
593    const color = window.getComputedStyle(element).backgroundColor;
594    return color && color !== "transparent" && color !== "rgba(0, 0, 0, 0)" ? color : null;
595};
596const dxRouteTransitionSurfaceBackground = () => {
597    const root = document.documentElement;
598    const surface = document.querySelector(surfaceSelector);
599    return dxRouteTransitionOpaqueBackground(surface)
600        ?? dxRouteTransitionOpaqueBackground(document.body)
601        ?? dxRouteTransitionOpaqueBackground(root)
602        ?? "Canvas";
603};
604const dxRouteTransitionPaintContext = () => {
605    const root = document.documentElement;
606    const surface = document.querySelector(surfaceSelector);
607    const surfaceBackground = dxRouteTransitionSurfaceBackground();
608    const documentBackground = dxRouteTransitionOpaqueBackground(document.body)
609        ?? dxRouteTransitionOpaqueBackground(root)
610        ?? surfaceBackground;
611
612    let clipRadius = "0px";
613    for (let current = surface; current && current !== document.body; current = current.parentElement) {
614        const style = window.getComputedStyle(current);
615        const clips = [style.overflow, style.overflowX, style.overflowY]
616            .some((value) => value === "hidden" || value === "clip");
617        const radius = style.borderTopLeftRadius;
618        if (clips && radius && radius !== "0px") {
619            clipRadius = radius;
620            break;
621        }
622    }
623
624    root.style.setProperty("--route-transition-surface-bg", surfaceBackground);
625    root.style.setProperty("--route-transition-document-bg", documentBackground);
626    root.style.setProperty("--route-transition-clip-radius", clipRadius);
627};
628const dxRouteTransitionIncomingPaintContext = () => {
629    document.documentElement.style.setProperty(
630        "--route-transition-incoming-surface-bg",
631        dxRouteTransitionSurfaceBackground(),
632    );
633};
634// How long a navigation waits for the browser to capture the old page before
635// giving up on the animation. A painted page captures within a frame or two.
636const UNPAINTED_PAGE_MS = 1000;
637
638// Resolves once the router has replaced the page, or after a ceiling if it
639// renders something indistinguishable.
640//
641// This must be started *before* the route is asked for, so the observer is
642// already live when the update lands. Starting it afterwards meant the mutation
643// had usually already happened, leaving nothing to observe and the ceiling as
644// the de facto wait — measured at a flat ~133ms of doing nothing after the new
645// route was on screen, on every navigation.
646//
647// There is deliberately no requestAnimationFrame fallback: rendering is paused
648// inside a view transition's update callback, so frames do not tick and it
649// could never fire.
650const dxRouteTransitionRouteRendered = () => new Promise((resolve) => {
651    let settled = false;
652    const finish = () => {
653        if (settled) return;
654        settled = true;
655        window.clearTimeout(ceiling);
656        observer?.disconnect?.();
657        resolve();
658    };
659    const observer = typeof MutationObserver === "undefined" ? null : new MutationObserver(() => finish());
660    // Only structural changes: an attribute tick from a clock or a progress bar
661    // is not the route arriving.
662    observer?.observe?.(document.body ?? document.documentElement, {
663        childList: true,
664        subtree: true,
665    });
666    const ceiling = window.setTimeout(() => finish(), 120);
667    if (!observer) finish();
668});
669
670// A navigation that starts while another is running skips the older one, whose
671// cleanup then runs while the newer one is still waiting to capture the old
672// page. The attributes and properties on <html> belong to the newest run, and
673// only that run may remove them.
674const runKey = Symbol.for("g3-route-transitions.navigation");
675const run = {};
676window[runKey] = run;
677
678try {
679    if (!document.startViewTransition || prefersReducedMotion) {
680        dioxus.send("navigate");
681        dioxus.send("done");
682    } else {
683        document.documentElement.dataset.routeTransition = animation;
684        document.documentElement.dataset.routeTransitionPlatform = platform;
685        // Set or cleared, so nothing is inherited from a run this one skipped.
686        if (from) document.documentElement.dataset.routeTransitionFrom = from;
687        else delete document.documentElement.dataset.routeTransitionFrom;
688        if (to) document.documentElement.dataset.routeTransitionTo = to;
689        else delete document.documentElement.dataset.routeTransitionTo;
690        document.documentElement.style.removeProperty("--route-transition-incoming-surface-bg");
691        dxRouteTransitionPaintContext();
692
693        // The outgoing snapshot is taken synchronously inside
694        // startViewTransition, so the attributes set above have to reach
695        // computed style before that call. Without this flush an element whose
696        // `view-transition-name` is granted by those attributes is still
697        // unnamed when it is captured, and so gets no group at all.
698        //
699        // The failure is asymmetric and easy to miss: an overlay entering needs
700        // its name only in the *new* state, which is styled later anyway and
701        // works, while the same overlay leaving needs it in the old state and
702        // silently drops out of the transition.
703        void document.documentElement.offsetHeight;
704
705        let updateStarted = false;
706        const transition = document.startViewTransition(async () => {
707            updateStarted = true;
708            // Watch first, then ask. The router usually renders while the ack
709            // is still in flight, so an observer started afterwards has already
710            // missed the only mutation it cares about.
711            const rendered = dxRouteTransitionRouteRendered();
712
713            dioxus.send("navigate");
714
715            const routeCommit = await dioxus.recv();
716            if (routeCommit !== "navigated") {
717                throw new Error(`unexpected route transition ack: ${routeCommit}`);
718            }
719
720            await rendered;
721            // A browser Back or Forward returns to a remembered scroll offset.
722            // Restored here, so the new snapshot is taken where the page lands.
723            window[Symbol.for("g3-route-transitions.browser-history")]?.restoreScroll?.();
724            // Dismissal reveals the newly rendered route, not the outgoing
725            // sheet. Capture its resolved theme color before the new snapshot
726            // is taken so dark pages do not inherit a light sheet backdrop.
727            dxRouteTransitionIncomingPaintContext();
728        });
729
730        // The old page is captured on the next rendering opportunity, and the
731        // update callback, which asks for the route, runs only after that. A
732        // page the browser does not paint (a background tab, an occluded
733        // window or preview pane) may report itself visible yet never render,
734        // so neither happens and the navigation waits forever. Skipping still
735        // runs the update callback, so the route changes, just without motion.
736        const unpainted = window.setTimeout(() => {
737            if (!updateStarted) transition.skipTransition();
738        }, UNPAINTED_PAGE_MS);
739
740        try {
741            await transition.ready;
742        } catch (_) {
743        }
744
745        try {
746            await transition.finished;
747        } catch (_) {
748        }
749        window.clearTimeout(unpainted);
750
751        dioxus.send("done");
752    }
753} catch (_) {
754    dioxus.send("fallback");
755} finally {
756    if (window[runKey] === run) {
757        delete window[runKey];
758        delete document.documentElement.dataset.routeTransition;
759        delete document.documentElement.dataset.routeTransitionPlatform;
760        delete document.documentElement.dataset.routeTransitionFrom;
761        delete document.documentElement.dataset.routeTransitionTo;
762        document.documentElement.style.removeProperty("--route-transition-surface-bg");
763        document.documentElement.style.removeProperty("--route-transition-incoming-surface-bg");
764        document.documentElement.style.removeProperty("--route-transition-document-bg");
765        document.documentElement.style.removeProperty("--route-transition-clip-radius");
766    }
767}
768"#;
769/// `value` as a double-quoted JavaScript string literal.
770///
771/// Route paths carry their parameters, which can hold quotes, backslashes or
772/// line separators; any of those written raw would end the literal early.
773fn js_string_literal(value: &str) -> String {
774    let mut literal = String::with_capacity(value.len() + 2);
775    literal.push('"');
776    for character in value.chars() {
777        match character {
778            '"' => literal.push_str("\\\""),
779            '\\' => literal.push_str("\\\\"),
780            '\n' => literal.push_str("\\n"),
781            '\r' => literal.push_str("\\r"),
782            '\u{2028}' => literal.push_str("\\u2028"),
783            '\u{2029}' => literal.push_str("\\u2029"),
784            character if character.is_control() => {
785                literal.push_str(&format!("\\u{:04x}", character as u32));
786            }
787            character => literal.push(character),
788        }
789    }
790    literal.push('"');
791    literal
792}
793/// [`VIEW_TRANSITION_NAVIGATE`] with every placeholder filled in.
794fn navigate_script(
795    animation: NavigationTransition,
796    platform: Platform,
797    from: &str,
798    to: Option<&str>,
799) -> String {
800    VIEW_TRANSITION_NAVIGATE
801        .replace(ANIMATION_PLACEHOLDER, animation.data_value())
802        .replace(PLATFORM_PLACEHOLDER, platform.data_value())
803        .replace(FROM_PLACEHOLDER, &js_string_literal(from))
804        .replace(TO_PLACEHOLDER, &js_string_literal(to.unwrap_or_default()))
805        .replace(
806            SURFACE_SELECTOR_PLACEHOLDER,
807            &js_string_literal(&surface_selector()),
808        )
809}
810async fn run_animated_navigation(
811    animation: NavigationTransition,
812    from: &str,
813    to: Option<&str>,
814    mut navigate: impl FnMut(),
815) {
816    let script = navigate_script(animation, platform(), from, to);
817    let mut transition = eval(&script);
818    let mut navigated = false;
819    loop {
820        match transition.recv::<String>().await.as_deref() {
821            Ok("navigate") => {
822                if !navigated {
823                    navigate();
824                    navigated = true;
825                }
826                _ = transition.send("navigated");
827            }
828            Ok("done") => break,
829            Ok("fallback") | Err(_) => {
830                if !navigated {
831                    navigate();
832                }
833                break;
834            }
835            _ => {}
836        }
837    }
838}
839/// Navigate to `route` with the transition chosen by
840/// `current.transition_to(&route)`, pushing or replacing history according to
841/// `current.replaces_history(&route)`.
842///
843/// The old page is captured before the router changes, which is why this must
844/// be used instead of `navigator().push(...)`. The call does nothing if
845/// `route` equals the current route. It changes the route without animation
846/// when the transition is [`NavigationTransition::Instant`], the browser lacks
847/// View Transitions, or the user prefers reduced motion.
848///
849/// Call it from an event handler, for example
850/// `onclick: move |_| async move { animated_navigate(Route::Home {}).await }`.
851/// It must run beneath `Router::<Route>`.
852///
853/// The future resolves once the animation has finished, but only if the task
854/// awaiting it survives that long. An event handler's task belongs to its
855/// component, and the component on the page being left is unmounted by the
856/// navigation, which drops the task: code after the `.await` in a handler on
857/// the old page does not run. Do follow-up work on the destination page, or
858/// in a task owned by a component that stays mounted.
859pub async fn animated_navigate<Route>(route: Route)
860where
861    Route: Routable + RouteTransitions,
862{
863    let current_route = router().current::<Route>();
864    let animation = current_route.transition_to(&route);
865    navigate_from(current_route, route, animation).await;
866}
867/// Navigate to `route` with `animation` instead of the one the route rules
868/// choose, still pushing or replacing history by
869/// `current.replaces_history(&route)`.
870///
871/// This is for UI state encoded in a route whose visual relationship only the
872/// caller knows, such as a filter the route rules deliberately treat as
873/// [`NavigationTransition::Instant`] but one control slides between. Otherwise it
874/// behaves exactly like [`animated_navigate`], including doing nothing when
875/// `route` is current. It must run beneath `Router::<Route>`.
876pub async fn animated_navigate_with<Route>(route: Route, animation: NavigationTransition)
877where
878    Route: Routable + RouteTransitions,
879{
880    navigate_from(router().current::<Route>(), route, animation).await;
881}
882/// The shared body of [`animated_navigate`] and [`animated_navigate_with`].
883async fn navigate_from<Route>(current_route: Route, route: Route, animation: NavigationTransition)
884where
885    Route: Routable + RouteTransitions,
886{
887    if current_route == route {
888        return;
889    }
890    let replace = current_route.replaces_history(&route);
891    let navigator = navigator();
892    let from = current_route.to_string();
893    let route = route.to_string();
894    let commit = || {
895        if replace {
896            _ = navigator.replace(route.clone());
897        } else {
898            _ = navigator.push(route.clone());
899        }
900    };
901    if animation == NavigationTransition::Instant {
902        commit();
903        return;
904    }
905    run_animated_navigation(animation, &from, Some(&route), commit).await;
906}
907/// Pop real router history with `current.transition_back()`.
908///
909/// Calling `navigator().go_back()` directly changes the route before the old
910/// page can be captured. This helper captures it first, then pops.
911///
912/// Returns `false` without doing anything when there is no previous entry, so
913/// callers such as platform Back handlers can keep their own root behavior.
914/// It must run beneath `Router::<Route>`, and its future is dropped with the
915/// calling component just as [`animated_navigate`]'s is.
916pub async fn try_animated_back<Route>() -> bool
917where
918    Route: Routable + RouteTransitions,
919{
920    let navigator = navigator();
921    if !navigator.can_go_back() {
922        return false;
923    }
924    let current_route = router().current::<Route>();
925    let animation = current_route.transition_back();
926    if animation == NavigationTransition::Instant {
927        navigator.go_back();
928        return true;
929    }
930    let from = current_route.to_string();
931    run_animated_navigation(animation, &from, None, || navigator.go_back()).await;
932    true
933}
934/// Pop real router history like [`try_animated_back`], or, when there is no
935/// previous entry (for example after a deep link), navigate to `fallback` with
936/// [`animated_navigate`].
937///
938/// Use this for visible Back buttons. When falling back, the transition comes
939/// from the forward rules (`current.transition_to(&fallback)`), so a stack
940/// page returning to its root still animates `Backward`. It must run beneath
941/// `Router::<Route>`.
942pub async fn animated_back_or_navigate<Route>(fallback: Route)
943where
944    Route: Routable + RouteTransitions,
945{
946    if !try_animated_back::<Route>().await {
947        animated_navigate(fallback).await;
948    }
949}
950/// False until the transition that brought this component in has finished,
951/// then true. Call it in the page, or in a list on it.
952///
953/// A navigation animates only once the new page has rendered, because the
954/// browser snapshots the incoming page before it can slide it in. Whatever the
955/// page draws before then is time between the tap and the first moving frame,
956/// and a long list or a wall of images makes that time visible. Drawing only a
957/// first screenful until this reads true keeps the cost of every page's first
958/// frame small and the same, whether its data was cached or not:
959///
960/// ```rust,no_run
961/// use dioxus::prelude::*;
962/// use g3_route_transitions::use_route_transition_settled;
963///
964/// #[component]
965/// fn Feed(items: Vec<String>) -> Element {
966///     let settled = use_route_transition_settled();
967///     let shown = if settled() { items.len() } else { 8 };
968///     rsx! {
969///         for item in items.iter().take(shown) {
970///             p { "{item}" }
971///         }
972///     }
973/// }
974/// ```
975///
976/// Rendering that happens while the slide runs also competes with it for the
977/// main thread, so this suits anything that can wait a moment, such as a
978/// request that re-renders the page when it lands.
979///
980/// Outside a transition (a first load, a reload) it settles after two frames.
981/// A ceiling of a second and a half covers a webview that has stopped drawing.
982pub fn use_route_transition_settled() -> ReadSignal<bool> {
983    let mut settled = use_signal(|| false);
984    use_effect(move || {
985        spawn(async move {
986            let mut done = eval(ROUTE_TRANSITION_SETTLED);
987            _ = done.recv::<bool>().await;
988            settled.set(true);
989        });
990    });
991    settled.into()
992}
993const ROUTE_TRANSITION_SETTLED: &str = r#"
994let sent = false;
995const done = () => { if (!sent) { sent = true; dioxus.send(true); } };
996setTimeout(done, 1500);
997// Frames do not tick inside a view transition's update callback, but they do
998// once its animations run, so this settles when they end.
999const frame = () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1000while (!sent && document.documentElement.dataset.routeTransition) await frame();
1001if (!sent) await frame();
1002done();
1003"#;
1004#[cfg(feature = "native-back")]
1005/// Window event emitted after native Back has completed an animated router pop.
1006///
1007/// Apps normally do not need this. It is available for route-adjacent work
1008/// such as restoring scroll after the destination has rendered.
1009pub const NATIVE_BACK_TRANSITION_FINISHED_EVENT: &str = "g3routebacktransitionend";
1010#[cfg(all(feature = "native-back", any(target_os = "android", target_os = "ios")))]
1011const NATIVE_BACK_EVENT_PLACEHOLDER: &str = "__G3_NATIVE_BACK_EVENT__";
1012#[cfg(all(feature = "native-back", any(target_os = "android", target_os = "ios")))]
1013const NATIVE_BACK_FINISHED_EVENT_PLACEHOLDER: &str = "__G3_NATIVE_BACK_FINISHED_EVENT__";
1014#[cfg(all(
1015    feature = "native-back",
1016    any(target_os = "android", target_os = "ios", test)
1017))]
1018const NATIVE_BACK_NAVIGATION_BRIDGE: &str = r#"
1019const nativeBackEvent = "__G3_NATIVE_BACK_EVENT__";
1020const transitionFinishedEvent = "__G3_NATIVE_BACK_FINISHED_EVENT__";
1021const stateKey = Symbol.for("g3-route-transitions.native-back");
1022
1023window[stateKey]?.dispose?.();
1024
1025const state = { pending: false };
1026const defer = window.queueMicrotask?.bind(window)
1027    ?? ((callback) => Promise.resolve().then(callback));
1028const onNativeBack = (event) => {
1029    // Give dialogs, sheets, menus, and fullscreen players the rest of the
1030    // current dispatch to claim this cancelable event first.
1031    defer(async () => {
1032        if (event.defaultPrevented || state.pending) return;
1033
1034        state.pending = true;
1035        event.preventDefault();
1036        dioxus.send("back");
1037
1038        try {
1039            const outcome = await dioxus.recv();
1040            if (outcome === "navigated") {
1041                window.dispatchEvent(new Event(transitionFinishedEvent));
1042            }
1043        } finally {
1044            state.pending = false;
1045        }
1046    });
1047};
1048
1049window.addEventListener(nativeBackEvent, onNativeBack);
1050
1051// Native renderers close an eval's channel as soon as its script returns, after
1052// which Rust's replies never arrive: the first press would leave `pending` set
1053// and every later press would be swallowed. Stay alive until replaced.
1054let release;
1055const released = new Promise((resolve) => {
1056    release = resolve;
1057});
1058window[stateKey] = {
1059    dispose() {
1060        window.removeEventListener(nativeBackEvent, onNativeBack);
1061        release();
1062    },
1063};
1064await released;
1065"#;
1066/// Connect native Back from `g3-native-plugins` to [`try_animated_back`]:
1067/// Android's system Back gesture or key, and iOS's swipe in from the left
1068/// screen edge.
1069///
1070/// Call this hook once from a layout rendered beneath `Router<Route>`. It
1071/// subscribes to the current route, enables native interception only while the
1072/// router can go back, and uses the route's generated reverse animation. At a
1073/// root route interception is off, so Android Back exits normally and an iOS
1074/// edge swipe does nothing, as it would in any other app. On other targets the
1075/// hook does nothing; see [`use_browser_history_transitions`] for the web.
1076///
1077/// Enable the crate's `native-back` feature to use this hook. It reuses the
1078/// nearest `NativePluginsProvider` when present and otherwise owns a standalone
1079/// Back plugin, so no handwritten Rust/JavaScript connector is required.
1080///
1081/// Higher-priority UI may claim the cancelable `g3nativeback` window event by
1082/// synchronously calling `preventDefault()`. See
1083/// [`use_native_back_navigation_with_layer`] when such UI can be open without
1084/// router history.
1085#[cfg(feature = "native-back")]
1086pub fn use_native_back_navigation<Route>()
1087where
1088    Route: Routable + RouteTransitions,
1089{
1090    use_native_back::<Route>(false);
1091}
1092/// [`use_native_back_navigation`] for an app with UI that sits above the
1093/// routes, such as a dialog, a non-routed sheet, or a fullscreen player.
1094///
1095/// While `layer_open` reads `true`, native Back is taken even with no router
1096/// history to pop, so the layer can close. The layer must listen for the
1097/// `g3nativeback` window event, close itself, and synchronously call
1098/// `preventDefault()` on it. If no layer claims the event and no router
1099/// history exists, the press goes back to the platform: Android handles it
1100/// (usually by leaving the app), and iOS drops the swipe.
1101///
1102/// Pass a `Signal<bool>`, a `Memo<bool>`, or any other readable `bool`. Call
1103/// this hook once from a layout rendered beneath `Router<Route>`.
1104///
1105/// ```rust,ignore
1106/// let mut player_open = use_signal(|| false);
1107/// use_native_back_navigation_with_layer::<Route>(player_open);
1108/// ```
1109#[cfg(feature = "native-back")]
1110pub fn use_native_back_navigation_with_layer<Route>(
1111    layer_open: impl Readable<Target = bool> + 'static,
1112) where
1113    Route: Routable + RouteTransitions,
1114{
1115    // Read in the body so this component re-renders when the layer opens or
1116    // closes, and the interception is re-applied after that render.
1117    let layer_open = *layer_open.read();
1118    use_native_back::<Route>(layer_open);
1119}
1120/// The shared body of the native-back hooks: take native Back while history
1121/// can be popped, or while `layer_open` is true.
1122#[cfg(feature = "native-back")]
1123#[cfg_attr(
1124    not(any(target_os = "android", target_os = "ios")),
1125    allow(clippy::extra_unused_type_parameters)
1126)]
1127fn use_native_back<Route>(layer_open: bool)
1128where
1129    Route: Routable + RouteTransitions,
1130{
1131    #[cfg(any(target_os = "android", target_os = "ios"))]
1132    {
1133        use g3_native_plugins::{BackButton, NativePlugins};
1134        use std::{cell::Cell, rc::Rc};
1135        // Subscribes this component to the route, so it re-renders, and the
1136        // interception below is re-applied, whenever history changes.
1137        let _current_route: Route = use_route();
1138        let navigator = navigator();
1139        let standalone = use_signal(BackButton::new);
1140        let mut back_button = use_hook(|| {
1141            try_consume_context::<NativePlugins>()
1142                .map(|plugins| plugins.back_button)
1143                .unwrap_or(standalone)
1144        });
1145        // The after-render callback is registered once, so it reads the
1146        // latest value from here.
1147        let intercept_at_root = use_hook(|| Rc::new(Cell::new(layer_open)));
1148        intercept_at_root.set(layer_open);
1149        // Native calls and the signal write wait until the render is done.
1150        dioxus::core::use_after_render({
1151            let intercept_at_root = intercept_at_root.clone();
1152            move || {
1153                let intercepting = navigator.can_go_back() || intercept_at_root.get();
1154                let mut back_button = back_button.write();
1155                let _ = back_button.prepare();
1156                let _ = back_button.set_intercepting(intercepting);
1157            }
1158        });
1159        use_future(move || async move {
1160            let script = NATIVE_BACK_NAVIGATION_BRIDGE
1161                .replace(
1162                    NATIVE_BACK_EVENT_PLACEHOLDER,
1163                    g3_native_plugins::NATIVE_BACK_EVENT,
1164                )
1165                .replace(
1166                    NATIVE_BACK_FINISHED_EVENT_PLACEHOLDER,
1167                    NATIVE_BACK_TRANSITION_FINISHED_EVENT,
1168                );
1169            let mut bridge = eval(&script);
1170            loop {
1171                if !matches!(bridge.recv::<String>().await.as_deref(), Ok("back")) {
1172                    break;
1173                }
1174                let navigated = try_animated_back::<Route>().await;
1175                if !navigated {
1176                    let _ = back_button.write().fall_through();
1177                }
1178                let outcome = if navigated { "navigated" } else { "ignored" };
1179                if bridge.send(outcome).is_err() {
1180                    break;
1181                }
1182            }
1183        });
1184    }
1185    #[cfg(not(any(target_os = "android", target_os = "ios")))]
1186    let _ = layer_open;
1187}
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191    #[test]
1192    fn sheet_transitions_dim_the_full_base_snapshot_per_platform() {
1193        let stylesheet = include_str!("../assets/route_transitions.css");
1194        assert!(stylesheet.contains("present-sheet\"]::view-transition-new(overlay)"));
1195        assert!(stylesheet.contains("dismiss-sheet\"]::view-transition-old(overlay)"));
1196        assert!(!stylesheet.contains("[data-route-transition-layer=\"sheet\"]"));
1197        assert!(stylesheet.contains("route-transition-ios-dim-base"));
1198        assert!(stylesheet.contains("route-transition-material-dim-base"));
1199        assert!(stylesheet.contains("filter: brightness"));
1200        assert!(stylesheet.contains("--route-transition-ios-presentation-backdrop"));
1201        assert!(stylesheet.contains("box-shadow: 0 -14px 20px -14px"));
1202        assert!(stylesheet.contains("present-sheet\"]::view-transition-old(overlay)"));
1203        assert!(stylesheet.contains("dismiss-sheet\"]::view-transition-new(overlay)"));
1204        assert!(stylesheet.contains("opacity: 0"));
1205    }
1206    #[test]
1207    fn sheet_transitions_are_scoped_by_platform_attribute() {
1208        let stylesheet = include_str!("../assets/route_transitions.css");
1209        assert!(
1210            stylesheet
1211                .contains(
1212                    "html[data-route-transition-platform=\"ios\"][data-route-transition=\"present-sheet\"]::view-transition-old(base)",
1213                ),
1214        );
1215        assert!(
1216            stylesheet
1217                .contains(
1218                    "html[data-route-transition-platform=\"material\"][data-route-transition=\"present-sheet\"]::view-transition-old(base)",
1219                ),
1220        );
1221        assert!(!stylesheet.contains("route-transition-mobile-dim-base"));
1222        assert!(!stylesheet.contains("route-transition-mobile-undim-base"));
1223        assert!(stylesheet.contains("border-radius: 12px"));
1224    }
1225    #[test]
1226    fn sheet_transitions_do_not_apply_debug_offsets_to_snapshots() {
1227        let stylesheet = include_str!("../assets/route_transitions.css");
1228        assert!(!stylesheet.contains("--route-transition-debug-peek"));
1229        assert!(!stylesheet.contains("--route-transition-cover-x"));
1230        assert!(!stylesheet.contains("--route-transition-base-x"));
1231        assert!(stylesheet.contains("transform: translateY(100%)"));
1232        assert!(stylesheet.contains("transform: translateY(0)"));
1233        assert!(!stylesheet.contains("translateX(var(--route-transition-base-x))"));
1234    }
1235    #[test]
1236    fn sheet_transitions_force_active_snapshots_to_paint_above_base() {
1237        let stylesheet = include_str!("../assets/route_transitions.css");
1238        assert!(stylesheet.contains("present-sheet\"]::view-transition-new(overlay),"));
1239        assert!(stylesheet.contains("dismiss-sheet\"]::view-transition-old(overlay)"));
1240        assert!(stylesheet.contains("mix-blend-mode: normal"));
1241        assert!(stylesheet.contains("opacity: 1"));
1242        assert!(stylesheet.contains("z-index: 2"));
1243        assert!(stylesheet.contains("present-sheet\"]::view-transition-old(base),"));
1244        assert!(stylesheet.contains("dismiss-sheet\"]::view-transition-new(base)"));
1245        assert!(stylesheet.contains("z-index: 1"));
1246    }
1247    #[test]
1248    fn hidden_base_pair_cannot_cover_a_full_page_snapshot() {
1249        let stylesheet = include_str!("../assets/route_transitions.css");
1250        let base_group = stylesheet
1251            .split("html[data-route-transition=\"present-sheet\"]::view-transition-group(base),")
1252            .nth(2)
1253            .and_then(|block| block.split('}').next())
1254            .expect("missing sheet base stacking rule");
1255        let page_group = stylesheet
1256            .split("html[data-route-transition=\"present-sheet\"]::view-transition-group(page),")
1257            .nth(2)
1258            .and_then(|block| block.split('}').next())
1259            .expect("missing sheet page stacking rule");
1260
1261        assert!(base_group.contains("z-index: 0"));
1262        assert!(page_group.contains("z-index: 1"));
1263    }
1264    /// Persistent chrome never moves, stays above every other snapshot
1265    /// including a routed sheet, and fades instead of popping when only one
1266    /// route renders it.
1267    #[test]
1268    fn persistent_chrome_is_static_and_stays_above_sheets() {
1269        let stylesheet = include_str!("../assets/route_transitions.css");
1270        let rule = |selector: &str| {
1271            stylesheet
1272                .split(&format!("{selector} {{"))
1273                .nth(1)
1274                .and_then(|block| block.split('}').next())
1275                .unwrap_or_else(|| panic!("missing {selector}"))
1276                .to_string()
1277        };
1278        assert!(
1279            rule(".route-transition-persistent-region")
1280                .contains("view-transition-name: persistent")
1281        );
1282        let group = rule("html[data-route-transition]::view-transition-group(persistent)");
1283        assert!(group.contains("animation: none"));
1284        assert!(group.contains("z-index: 10000"));
1285        // A sheet must not be given its own higher stacking than the rail. The
1286        // rail outranks the overlay so a desktop rail stays reachable while a
1287        // sheet is up; chrome a sheet should cover is simply not persistent.
1288        for transition in ["present-sheet", "dismiss-sheet"] {
1289            let selector = format!(
1290                "html[data-route-transition=\"{transition}\"]::view-transition-group(persistent)"
1291            );
1292            assert!(
1293                !stylesheet.contains(&format!("{selector} {{")),
1294                "{selector} must not override the persistent stacking order"
1295            );
1296        }
1297        assert!(
1298            rule("html[data-route-transition]::view-transition-old(persistent):only-child")
1299                .contains("route-transition-fade-out")
1300        );
1301        assert!(
1302            rule("html[data-route-transition]::view-transition-new(persistent):only-child")
1303                .contains("route-transition-persistent-fade-in")
1304        );
1305        assert!(
1306            rule("html[data-route-transition]::view-transition-old(persistent):not(:only-child)")
1307                .contains("opacity: 0")
1308        );
1309    }
1310    #[test]
1311    fn full_page_snapshots_own_nested_stack_motion() {
1312        let stylesheet = include_str!("../assets/route_transitions.css");
1313        assert!(stylesheet.contains(".route-transition-page-region"));
1314        assert!(stylesheet.contains("view-transition-name: page"));
1315        assert!(
1316            stylesheet.contains(".route-transition-page-region > .route-transition-base-region")
1317        );
1318        assert!(
1319            stylesheet.contains(".route-transition-page-region .route-transition-segment-region")
1320        );
1321        assert!(stylesheet.contains("view-transition-old(page)"));
1322        assert!(stylesheet.contains("view-transition-new(page)"));
1323    }
1324    #[test]
1325    fn style_is_flushed_before_the_outgoing_snapshot_is_taken() {
1326        let script = VIEW_TRANSITION_NAVIGATE;
1327        let attributes = script
1328            .find("dataset.routeTransitionPlatform = platform")
1329            .expect("platform attribute is set");
1330        let flush = script
1331            .find("void document.documentElement.offsetHeight")
1332            .expect("style is flushed");
1333        let capture = script
1334            .find("document.startViewTransition(async () =>")
1335            .expect("transition is started");
1336        assert!(
1337            attributes < flush,
1338            "the flush must come after the attributes"
1339        );
1340        assert!(flush < capture, "the flush must come before the snapshot");
1341    }
1342    #[test]
1343    fn a_page_frame_is_the_page_under_a_sheet_unless_it_holds_persistent_chrome() {
1344        let css = include_str!("../assets/route_transitions.css");
1345        for kind in ["present-sheet", "dismiss-sheet"] {
1346            let frame = format!(
1347                "html[data-route-transition=\"{kind}\"] .route-transition-page-frame:has(> .route-transition-page-region):not(:has(> .route-transition-persistent-region))"
1348            );
1349            let inner = format!(
1350                "html[data-route-transition=\"{kind}\"] .route-transition-page-frame:not(:has(> .route-transition-persistent-region)) > .route-transition-page-region"
1351            );
1352            assert!(css.contains(&frame), "the frame is named for {kind}");
1353            assert!(css.contains(&inner), "the inner page is unnamed for {kind}");
1354        }
1355        // Only sheets: a push still slides the bare page past still chrome.
1356        assert!(
1357            !css.contains("html[data-route-transition=\"forward\"] .route-transition-page-frame")
1358        );
1359    }
1360    #[test]
1361    fn a_page_that_never_paints_still_navigates() {
1362        // Without the watchdog, an occluded window or background tab never
1363        // captures the old page, the update callback never runs, and the
1364        // route never changes.
1365        let script = VIEW_TRANSITION_NAVIGATE;
1366        let started = script
1367            .find("updateStarted = true;")
1368            .expect("the update callback marks itself started");
1369        let navigate = script
1370            .find("dioxus.send(\"navigate\");\n\n            const routeCommit")
1371            .expect("the update callback asks for the route");
1372        assert!(
1373            started < navigate,
1374            "mark the start before asking for the route"
1375        );
1376        assert!(script.contains("if (!updateStarted) transition.skipTransition();"));
1377        assert!(script.contains("window.clearTimeout(unpainted);"));
1378    }
1379    #[test]
1380    fn runtime_exports_the_shell_paint_context_to_the_snapshot_tree() {
1381        let script = VIEW_TRANSITION_NAVIGATE;
1382        let paint_context = script
1383            .find("dxRouteTransitionPaintContext();")
1384            .expect("paint context is captured");
1385        let capture = script
1386            .find("document.startViewTransition(async () =>")
1387            .expect("transition is started");
1388
1389        assert!(
1390            paint_context < capture,
1391            "paint context must precede capture"
1392        );
1393        let filled = navigate_script(NavigationTransition::Forward, Platform::Ios, "/", None);
1394        assert!(filled.contains(
1395            r#"const surfaceSelector = ".route-transition-page-region, .route-transition-base-region";"#
1396        ));
1397        assert!(script.contains("--route-transition-surface-bg"));
1398        assert!(script.contains("--route-transition-incoming-surface-bg"));
1399        assert!(script.contains("--route-transition-document-bg"));
1400        assert!(script.contains("--route-transition-clip-radius"));
1401        assert!(script.contains("style.removeProperty(\"--route-transition-surface-bg\")"));
1402        assert!(
1403            script.contains("style.removeProperty(\"--route-transition-incoming-surface-bg\")"),
1404        );
1405    }
1406    #[test]
1407    fn runtime_captures_the_incoming_surface_before_the_new_snapshot() {
1408        let script = VIEW_TRANSITION_NAVIGATE;
1409        let callback = script
1410            .find("document.startViewTransition(async () =>")
1411            .expect("the transition is started");
1412        let body = &script[callback..];
1413        let rendered = body.find("await rendered;").expect("the new route renders");
1414        let incoming = body
1415            .find("dxRouteTransitionIncomingPaintContext();")
1416            .expect("the incoming paint context is captured");
1417
1418        assert!(
1419            rendered < incoming,
1420            "the incoming color must be read from the newly rendered route",
1421        );
1422    }
1423    #[test]
1424    fn spatial_snapshot_groups_clip_to_embedded_shells() {
1425        let stylesheet = include_str!("../assets/route_transitions.css");
1426
1427        for selector in [
1428            "[data-route-transition=\"forward\"]::view-transition-group(page)",
1429            "[data-route-transition=\"backward\"]::view-transition-group(page)",
1430            "[data-route-transition=\"forward\"]::view-transition-image-pair(page)",
1431            "[data-route-transition=\"backward\"]::view-transition-image-pair(page)",
1432            "[data-route-transition=\"present-sheet\"]::view-transition-group(overlay)",
1433            "[data-route-transition=\"dismiss-sheet\"]::view-transition-group(overlay)",
1434            "[data-route-transition=\"present-sheet\"]::view-transition-image-pair(overlay)",
1435            "[data-route-transition=\"dismiss-sheet\"]::view-transition-image-pair(overlay)",
1436        ] {
1437            assert!(stylesheet.contains(selector), "missing {selector}");
1438        }
1439        assert!(stylesheet.contains("overflow: hidden;"));
1440        assert!(stylesheet.contains("border-radius: var(--route-transition-clip-radius, 0px)"));
1441        assert!(
1442            stylesheet
1443                .contains("clip-path: inset(0 round var(--route-transition-clip-radius, 0px))",)
1444        );
1445    }
1446    #[test]
1447    fn sheet_backdrop_uses_the_resolved_theme_surface() {
1448        let stylesheet = include_str!("../assets/route_transitions.css");
1449
1450        assert!(stylesheet.contains("--route-transition-document-bg"));
1451        assert!(stylesheet.contains("--route-transition-surface-bg"));
1452        assert!(stylesheet.contains("--route-transition-incoming-surface-bg"));
1453        assert!(stylesheet.contains(
1454            "[data-route-transition=\"present-sheet\"]::view-transition-image-pair(page)",
1455        ));
1456        assert!(stylesheet.contains(
1457            "[data-route-transition=\"dismiss-sheet\"]::view-transition-image-pair(base)",
1458        ));
1459    }
1460    #[test]
1461    fn view_transition_update_waits_for_native_route_commit_without_blocking_on_raf() {
1462        assert!(VIEW_TRANSITION_NAVIGATE.contains("document.startViewTransition(async () =>"),);
1463        assert!(VIEW_TRANSITION_NAVIGATE.contains("dioxus.send(\"navigate\")"));
1464        assert!(VIEW_TRANSITION_NAVIGATE.contains("const routeCommit = await dioxus.recv()"),);
1465        assert!(VIEW_TRANSITION_NAVIGATE.contains("routeCommit !== \"navigated\""));
1466        let callback = VIEW_TRANSITION_NAVIGATE
1467            .find("document.startViewTransition(async () =>")
1468            .expect("the transition is started");
1469        let body = &VIEW_TRANSITION_NAVIGATE[callback..];
1470        let armed = body
1471            .find("const rendered = dxRouteTransitionRouteRendered();")
1472            .expect("the wait is armed");
1473        let asked = body
1474            .find("dioxus.send(\"navigate\")")
1475            .expect("the route is asked for");
1476        assert!(
1477            armed < asked,
1478            "the observer must be live before the request"
1479        );
1480        assert!(VIEW_TRANSITION_NAVIGATE.contains("await rendered;"));
1481        assert!(!VIEW_TRANSITION_NAVIGATE.contains("dxRouteTransitionNextFrame"));
1482        assert!(VIEW_TRANSITION_NAVIGATE.contains("await transition.ready"));
1483        assert!(!VIEW_TRANSITION_NAVIGATE.contains("console.info"));
1484        assert!(!VIEW_TRANSITION_NAVIGATE.contains("g3RouteTransition"));
1485    }
1486    #[test]
1487    fn transitions_publish_the_routes_they_move_between_and_clear_them() {
1488        assert!(VIEW_TRANSITION_NAVIGATE.contains(FROM_PLACEHOLDER));
1489        assert!(VIEW_TRANSITION_NAVIGATE.contains(TO_PLACEHOLDER));
1490        // Set before the outgoing snapshot is taken, like the animation itself,
1491        // so CSS keyed on them names elements in the old state too.
1492        let set_from = VIEW_TRANSITION_NAVIGATE
1493            .find("dataset.routeTransitionFrom = from")
1494            .expect("from is published");
1495        let started = VIEW_TRANSITION_NAVIGATE
1496            .find("document.startViewTransition(async () =>")
1497            .expect("the transition is started");
1498        assert!(set_from < started);
1499        assert!(VIEW_TRANSITION_NAVIGATE.contains("dataset.routeTransitionTo = to"));
1500        let cleanup = VIEW_TRANSITION_NAVIGATE
1501            .split("} finally {")
1502            .nth(1)
1503            .expect("the script cleans up");
1504        assert!(cleanup.contains("delete document.documentElement.dataset.routeTransitionFrom;"));
1505        assert!(cleanup.contains("delete document.documentElement.dataset.routeTransitionTo;"));
1506    }
1507    /// A second navigation skips the first, whose cleanup then runs before the
1508    /// second has captured the old page. Removing the attributes there would
1509    /// leave the second transition unstyled.
1510    #[test]
1511    fn only_the_newest_navigation_cleans_up() {
1512        let script = VIEW_TRANSITION_NAVIGATE;
1513        let claimed = script
1514            .find("window[runKey] = run;")
1515            .expect("each run claims the document");
1516        let started = script
1517            .find("document.startViewTransition(async () =>")
1518            .expect("the transition is started");
1519        assert!(claimed < started, "claim before the transition starts");
1520        let cleanup = script
1521            .split("} finally {")
1522            .nth(1)
1523            .expect("the script cleans up");
1524        let owned = cleanup
1525            .find("if (window[runKey] === run) {")
1526            .expect("cleanup checks ownership");
1527        let removed = cleanup
1528            .find("delete document.documentElement.dataset.routeTransition;")
1529            .expect("cleanup removes the transition attribute");
1530        assert!(owned < removed, "remove only what this run owns");
1531        // A skipped run's destination must not leak into a Back, which has none.
1532        assert!(script.contains("else delete document.documentElement.dataset.routeTransitionTo;"));
1533    }
1534    #[test]
1535    fn route_paths_are_escaped_into_string_literals() {
1536        assert_eq!(js_string_literal("/watch/abc"), "\"/watch/abc\"");
1537        assert_eq!(js_string_literal("a\"b\\c"), "\"a\\\"b\\\\c\"");
1538        assert_eq!(js_string_literal("a\nb\u{2028}"), "\"a\\nb\\u2028\"");
1539        assert_eq!(js_string_literal(""), "\"\"");
1540    }
1541    #[cfg(feature = "native-back")]
1542    #[test]
1543    fn native_back_bridge_is_cancelable_prioritized_and_acknowledged() {
1544        let source = include_str!("lib.rs");
1545        assert!(NATIVE_BACK_NAVIGATION_BRIDGE.contains("event.defaultPrevented"));
1546        assert!(NATIVE_BACK_NAVIGATION_BRIDGE.contains("queueMicrotask"));
1547        assert!(NATIVE_BACK_NAVIGATION_BRIDGE.contains("dioxus.send(\"back\")"));
1548        assert!(NATIVE_BACK_NAVIGATION_BRIDGE.contains("await dioxus.recv()"));
1549        assert!(NATIVE_BACK_NAVIGATION_BRIDGE.contains("g3-route-transitions.native-back"),);
1550        assert_eq!(
1551            NATIVE_BACK_TRANSITION_FINISHED_EVENT,
1552            "g3routebacktransitionend"
1553        );
1554        assert!(source.contains("back_button.write().fall_through()"));
1555    }
1556    /// Native renderers close an eval channel when its script returns. A
1557    /// bridge that only registers a listener and returns would never hear
1558    /// Rust's reply, leaving the first press pending and swallowing the rest.
1559    #[cfg(feature = "native-back")]
1560    #[test]
1561    fn native_back_bridge_stays_alive_to_receive_replies() {
1562        let bridge = NATIVE_BACK_NAVIGATION_BRIDGE.trim_end();
1563        assert!(bridge.ends_with("await released;"));
1564        let dispose = bridge
1565            .split("dispose() {")
1566            .nth(1)
1567            .expect("the bridge can be disposed");
1568        assert!(dispose.contains("release();"));
1569        assert!(bridge.contains("state.pending = false"));
1570    }
1571    /// iOS raises the same `g3nativeback` event from its edge swipe, so the
1572    /// bridge must be compiled for both native platforms, not only Android.
1573    #[test]
1574    fn native_back_is_wired_on_android_and_ios() {
1575        let source = include_str!("lib.rs");
1576        let production_source = source
1577            .split("#[cfg(test)]")
1578            .next()
1579            .expect("production source precedes tests");
1580        let hook = production_source
1581            .split("fn use_native_back<Route>(layer_open: bool)")
1582            .nth(1)
1583            .expect("the hooks share one body");
1584        assert!(hook.contains("#[cfg(any(target_os = \"android\", target_os = \"ios\"))]"));
1585        assert!(hook.contains("#[cfg(not(any(target_os = \"android\", target_os = \"ios\")))]"));
1586        assert!(!production_source.contains("native-back\", target_os = \"android\")"));
1587    }
1588    #[test]
1589    fn a_cross_dissolve_never_uncovers_what_is_behind_the_page() {
1590        let stylesheet = include_str!("../assets/route_transitions.css");
1591        assert!(
1592            !stylesheet.contains("route-transition-fade-in"),
1593            "nothing may fade in during a cross-dissolve",
1594        );
1595        assert!(
1596            stylesheet.contains("route-transition-fade-out"),
1597            "the outgoing page still fades out",
1598        );
1599    }
1600    #[test]
1601    fn route_transition_css_uses_production_durations() {
1602        let stylesheet = include_str!("../assets/route_transitions.css");
1603        assert!(stylesheet.contains("--route-transition-sheet-duration: 0.6s"));
1604        assert!(stylesheet.contains("--route-transition-stack-duration: 260ms"));
1605        assert!(stylesheet.contains("--route-transition-stack-duration: 300ms"));
1606        assert!(stylesheet.contains("--route-transition-fade-duration: 150ms"));
1607        assert!(stylesheet.contains("--route-transition-sheet-duration: 400ms"));
1608        assert!(stylesheet.contains("--route-transition-material-sheet-dismiss-duration: 350ms"),);
1609        assert!(stylesheet.contains("translateY(20%); opacity: 0"));
1610        assert!(stylesheet.contains("to { transform: translateY(100%); }"));
1611        assert!(!stylesheet.contains("route-transition-duration-debug"));
1612        assert!(!stylesheet.contains("route-transition-mobile-dim-base"));
1613        assert!(!stylesheet.contains("route-transition-mobile-undim-base"));
1614        assert!(!stylesheet.contains("morph"));
1615        assert!(!stylesheet.contains("zoom"));
1616    }
1617    /// An app's `:root { --route-transition-stack-duration: .. }` must win on
1618    /// both platforms. A plain `html[data-route-transition-platform=..]` block
1619    /// outranks `:root`, so the Material defaults silently ignored it.
1620    #[test]
1621    fn custom_property_defaults_yield_to_an_apps_root_overrides() {
1622        let stylesheet = include_str!("../assets/route_transitions.css");
1623        let ios = stylesheet
1624            .find(":where(:root) {")
1625            .expect("the defaults have zero specificity");
1626        let material = stylesheet
1627            .find(":where(html[data-route-transition-platform=\"material\"]) {")
1628            .expect("the Material defaults have zero specificity");
1629        assert!(ios < material, "Material must come later to win a tie");
1630        assert!(!stylesheet.contains("\n:root {"));
1631        assert!(!stylesheet.contains("\nhtml[data-route-transition-platform=\"material\"] {"));
1632    }
1633    #[test]
1634    fn stack_transitions_diverge_between_ios_parallax_and_material_shared_axis() {
1635        let stylesheet = include_str!("../assets/route_transitions.css");
1636        assert!(stylesheet.contains("route-transition-ios-push-out-left"));
1637        assert!(stylesheet.contains("translateX(-30%); filter: brightness(0.85)"));
1638        assert!(stylesheet.contains("route-transition-material-axis-out-left"));
1639        assert!(stylesheet.contains("route-transition-material-axis-in-left"));
1640        assert!(stylesheet.contains("route-transition-material-axis-out-right"));
1641        assert!(stylesheet.contains("route-transition-material-axis-in-right"));
1642        assert!(stylesheet.contains("--route-transition-material-spatial-ease"));
1643        assert!(stylesheet.contains("--route-transition-material-shared-axis-distance: 30px"));
1644        assert!(stylesheet.contains("35%, 100% { opacity: 0; }"));
1645        assert!(stylesheet.contains("box-shadow: -16px 0 16px -16px"));
1646    }
1647
1648    /// A segment push is a filmstrip, not a page push. The two tab bodies are
1649    /// neighbouring frames of one strip: they travel the full width on one
1650    /// shared curve, so the gap between them stays exactly one pane wide for
1651    /// the whole transition and neither can appear on top of the other. The
1652    /// platform-specific parallax and shared-axis pairs stay on `page`, where
1653    /// one surface really is moving over another.
1654    #[test]
1655    fn peer_segments_slide_as_one_filmstrip_rather_than_a_stack_page() {
1656        let stylesheet = include_str!("../assets/route_transitions.css");
1657
1658        assert!(stylesheet.contains("route-transition-segment-out-left"));
1659        assert!(stylesheet.contains("route-transition-segment-in-left"));
1660        assert!(stylesheet.contains("route-transition-segment-out-right"));
1661        assert!(stylesheet.contains("route-transition-segment-in-right"));
1662
1663        // Keyframe bodies contain nested braces, so the block ends at the first
1664        // closing brace in column zero rather than the first one seen.
1665        let keyframe_block = |name: &str| {
1666            stylesheet
1667                .split(&format!("@keyframes {name} {{"))
1668                .nth(1)
1669                .and_then(|block| block.split("\n}").next())
1670                .unwrap_or_else(|| panic!("missing @keyframes {name}"))
1671                .to_string()
1672        };
1673
1674        // Full-width travel in both directions, so the outgoing pane clears the
1675        // box exactly as the incoming one lands. A partial offset (the 30% a
1676        // page push uses) leaves the two panes overlapping mid-transition.
1677        for (name, from, to) in [
1678            (
1679                "route-transition-segment-out-left",
1680                "translateX(0)",
1681                "translateX(-100%)",
1682            ),
1683            (
1684                "route-transition-segment-in-left",
1685                "translateX(100%)",
1686                "translateX(0)",
1687            ),
1688            (
1689                "route-transition-segment-out-right",
1690                "translateX(0)",
1691                "translateX(100%)",
1692            ),
1693            (
1694                "route-transition-segment-in-right",
1695                "translateX(-100%)",
1696                "translateX(0)",
1697            ),
1698        ] {
1699            let block = keyframe_block(name);
1700            assert!(block.contains(from), "{name} should start at {from}");
1701            assert!(block.contains(to), "{name} should end at {to}");
1702            // No cross-fade: a filmstrip never dims or dissolves between frames.
1703            assert!(!block.contains("opacity"), "{name} should not fade");
1704            assert!(!block.contains("brightness"), "{name} should not dim");
1705        }
1706
1707        // One shared curve for both panes, rather than the accelerate /
1708        // decelerate pair that makes a page push read as two separate moves.
1709        assert!(stylesheet.contains("--route-transition-segment-ease"));
1710        assert!(!stylesheet.contains(
1711            "\"material\"][data-route-transition=\"forward\"]::view-transition-old(segment)"
1712        ));
1713
1714        // The user agent gives view-transition images `plus-lighter` for smooth
1715        // cross-fades; two opaque panes sliding across each other must
1716        // composite normally or the overlap ghosts.
1717        let segment_images = stylesheet
1718            .split("::view-transition-new(segment) {")
1719            .nth(1)
1720            .and_then(|block| block.split('}').next())
1721            .expect("missing segment image rule");
1722        assert!(segment_images.contains("mix-blend-mode: normal"));
1723
1724        // Full-width travel has to be clipped to the segment's own box.
1725        assert!(stylesheet.contains("::view-transition-group(segment)"));
1726        assert!(stylesheet.contains("::view-transition-image-pair(segment)"));
1727        assert!(stylesheet.contains("clip-path: inset(0)"));
1728    }
1729    #[test]
1730    fn cross_fade_transitions_are_the_same_on_both_platforms() {
1731        let stylesheet = include_str!("../assets/route_transitions.css");
1732        assert!(
1733            stylesheet
1734                .contains("html[data-route-transition=\"cross-fade\"]::view-transition-old(root)",),
1735        );
1736        assert!(stylesheet.contains("route-transition-fade-out"));
1737        assert!(!stylesheet.contains("route-transition-material-fade-through"));
1738    }
1739    #[test]
1740    fn animation_data_values_match_css_contract() {
1741        assert_eq!(NavigationTransition::Instant.data_value(), "instant");
1742        assert_eq!(NavigationTransition::CrossFade.data_value(), "cross-fade");
1743        assert_eq!(NavigationTransition::Forward.data_value(), "forward");
1744        assert_eq!(NavigationTransition::Backward.data_value(), "backward");
1745        assert_eq!(
1746            NavigationTransition::PresentSheet.data_value(),
1747            "present-sheet"
1748        );
1749        assert_eq!(
1750            NavigationTransition::DismissSheet.data_value(),
1751            "dismiss-sheet"
1752        );
1753    }
1754    #[test]
1755    fn platform_data_values_match_css_contract() {
1756        assert_eq!(Platform::Ios.data_value(), "ios");
1757        assert_eq!(Platform::Material.data_value(), "material");
1758    }
1759    #[test]
1760    fn set_platform_overrides_auto_detection() {
1761        set_platform(Platform::Ios);
1762        assert_eq!(platform(), Platform::Ios);
1763        set_platform(Platform::Material);
1764        assert_eq!(platform(), Platform::Material);
1765    }
1766    #[test]
1767    fn animation_and_platform_are_written_in_rather_than_awaited() {
1768        let start = VIEW_TRANSITION_NAVIGATE
1769            .find("document.startViewTransition")
1770            .expect("the transition is started");
1771        assert!(
1772            !VIEW_TRANSITION_NAVIGATE[..start].contains("await dioxus.recv()"),
1773            "no round trip may precede the snapshot",
1774        );
1775        let filled = navigate_script(
1776            NavigationTransition::PresentSheet,
1777            Platform::Ios,
1778            "/queue",
1779            Some("/watch/abc"),
1780        );
1781        assert!(filled.contains(r#"const animation = "present-sheet";"#));
1782        assert!(filled.contains(r#"const platform = "ios";"#));
1783        assert!(filled.contains(r#"const from = "/queue";"#));
1784        assert!(filled.contains(r#"const to = "/watch/abc";"#));
1785        assert!(
1786            !filled.contains("__DX_ROUTE_TRANSITION"),
1787            "every placeholder is substituted",
1788        );
1789        assert!(
1790            filled
1791                .contains("document.documentElement.dataset.routeTransitionPlatform = platform;",),
1792        );
1793        assert!(!filled.contains("navigator.userAgent"));
1794    }
1795    /// The documented CSS contract: every animated transition value and every
1796    /// snapshot name is used, and the pre-0.4 spellings are gone.
1797    #[test]
1798    fn stylesheet_keys_on_the_documented_values_and_snapshot_names() {
1799        let stylesheet = include_str!("../assets/route_transitions.css");
1800        for transition in [
1801            NavigationTransition::CrossFade,
1802            NavigationTransition::Forward,
1803            NavigationTransition::Backward,
1804            NavigationTransition::PresentSheet,
1805            NavigationTransition::DismissSheet,
1806        ] {
1807            let selector = format!("[data-route-transition=\"{}\"]", transition.data_value());
1808            assert!(stylesheet.contains(&selector), "missing {selector}");
1809        }
1810        for name in ["root", "base", "overlay", "page", "segment", "persistent"] {
1811            assert!(
1812                stylesheet.contains(&format!("::view-transition-old({name})")),
1813                "missing snapshot {name}",
1814            );
1815        }
1816        for legacy in [
1817            "\"push-left\"",
1818            "\"push-right\"",
1819            "\"fade\"",
1820            "(cover)",
1821            "-md-",
1822        ] {
1823            assert!(!stylesheet.contains(legacy), "legacy {legacy} remains");
1824        }
1825    }
1826    #[test]
1827    fn cross_fade_holds_the_incoming_base_region_opaque_like_the_root() {
1828        let stylesheet = include_str!("../assets/route_transitions.css");
1829        let outgoing = stylesheet
1830            .split("html[data-route-transition=\"cross-fade\"]::view-transition-old(base) {")
1831            .nth(1)
1832            .and_then(|block| block.split('}').next())
1833            .expect("missing outgoing base fade rule");
1834        assert!(outgoing.contains("route-transition-fade-out"));
1835        let incoming = stylesheet
1836            .split("html[data-route-transition=\"cross-fade\"]::view-transition-new(base) {")
1837            .last()
1838            .and_then(|block| block.split('}').next())
1839            .expect("missing incoming base fade rule");
1840        assert!(incoming.contains("animation: none"));
1841        assert!(incoming.contains("opacity: 1"));
1842    }
1843    /// The helpers run inside spawned futures, where hooks must not be called.
1844    #[test]
1845    fn navigation_helpers_do_not_call_hooks() {
1846        // A CRLF checkout would otherwise never find the end of a body.
1847        let source = include_str!("lib.rs").replace("\r\n", "\n");
1848        for helper in [
1849            "pub async fn animated_navigate<",
1850            "pub async fn animated_navigate_with<",
1851            "async fn navigate_from<",
1852            "pub async fn try_animated_back<",
1853            "pub async fn animated_back_or_navigate<",
1854        ] {
1855            let body = source
1856                .split(helper)
1857                .nth(1)
1858                .and_then(|rest| rest.split("\n}\n").next())
1859                .expect("helper is present");
1860            assert!(!body.contains("use_"), "{helper} calls a hook");
1861        }
1862    }
1863}