1#![warn(missing_docs)]
2mod 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};
158pub static ROUTE_TRANSITIONS_CSS: Asset = asset!("/assets/route_transitions.css");
167pub const ROUTE_TRANSITION_BASE_REGION_CLASS: &str = "route-transition-base-region";
176pub const ROUTE_TRANSITION_OVERLAY_REGION_CLASS: &str = "route-transition-overlay-region";
183pub const ROUTE_TRANSITION_SEGMENT_REGION_CLASS: &str = "route-transition-segment-region";
189pub const ROUTE_TRANSITION_PAGE_REGION_CLASS: &str = "route-transition-page-region";
196pub const ROUTE_TRANSITION_PERSISTENT_REGION_CLASS: &str = "route-transition-persistent-region";
206pub 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#[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#[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#[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#[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#[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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
342pub enum NavigationTransition {
343 Instant,
347 #[default]
350 CrossFade,
351 Forward,
356 Backward,
358 PresentSheet,
362 DismissSheet,
365}
366impl NavigationTransition {
367 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum Platform {
387 Ios,
391 Material,
394}
395impl Platform {
396 pub fn data_value(self) -> &'static str {
399 match self {
400 Platform::Ios => "ios",
401 Platform::Material => "material",
402 }
403 }
404}
405static GLOBAL_PLATFORM: AtomicU8 = AtomicU8::new(0);
409pub 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}
419pub fn platform() -> Platform {
422 match GLOBAL_PLATFORM.load(Ordering::Relaxed) {
423 1 => Platform::Ios,
424 2 => Platform::Material,
425 _ => detect_platform(),
426 }
427}
428pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
477pub enum RouteTransitionLayer {
478 #[default]
481 Plain,
482 Sheet,
485 StackRoot,
488 StackPage,
491}
492pub trait RouteTransitions: PartialEq {
499 fn transition_to(&self, next: &Self) -> NavigationTransition;
504 fn replaces_history(&self, _next: &Self) -> bool {
510 false
511 }
512 fn transition_back(&self) -> NavigationTransition {
520 NavigationTransition::CrossFade
521 }
522}
523#[component]
529pub fn RouteTransitionStyles(children: Element) -> Element {
530 rsx! {
531 document::Link { rel: "stylesheet", href: ROUTE_TRANSITIONS_CSS }
532 {children}
533 }
534}
535#[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}
554const 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__\"";
568fn 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"#;
769fn 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}
793fn 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}
839pub 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}
867pub 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}
882async 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}
907pub 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}
934pub 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}
950pub 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")]
1005pub 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#[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#[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 let layer_open = *layer_open.read();
1118 use_native_back::<Route>(layer_open);
1119}
1120#[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 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 let intercept_at_root = use_hook(|| Rc::new(Cell::new(layer_open)));
1148 intercept_at_root.set(layer_open);
1149 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 #[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 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 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 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 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 #[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 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 #[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 #[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 #[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 #[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 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 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 assert!(!block.contains("opacity"), "{name} should not fade");
1704 assert!(!block.contains("brightness"), "{name} should not dim");
1705 }
1706
1707 assert!(stylesheet.contains("--route-transition-segment-ease"));
1710 assert!(!stylesheet.contains(
1711 "\"material\"][data-route-transition=\"forward\"]::view-transition-old(segment)"
1712 ));
1713
1714 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 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 #[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 #[test]
1845 fn navigation_helpers_do_not_call_hooks() {
1846 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}