diff --git a/client/src/App.tsx b/client/src/App.tsx index d9ff8b209..d7f64da73 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -97,6 +97,26 @@ const MJourneyDetailScreen = lazyWithRetry(() => import('./mobile/screens/journe const MCollectionsScreen = lazyWithRetry(() => import('./mobile/screens/collections/MCollections')) const MNotificationsScreen = lazyWithRetry(() => import('./mobile/screens/notifications/MNotifications')) +// The main sections, loaded ahead once signed in and settled, so the first +// switch to one does not wait for its code. A load that fails here is no +// error: the route loads it again when it is opened. +const DESKTOP_SECTIONS = [ + () => import('./pages/DashboardPage'), + () => import('./pages/VacayPage'), + () => import('./pages/AtlasPage'), + () => import('./pages/CollectionsPage'), + () => import('./pages/JourneyPage'), +] +const PHONE_SECTIONS = [ + () => import('./mobile/screens/dashboard/MDashboard'), + () => import('./mobile/screens/vacay/MVacay'), + () => import('./mobile/screens/atlas/MAtlas'), + () => import('./mobile/screens/collections/MCollections'), + () => import('./mobile/screens/journey/MJourney'), +] +const SECTIONS_AHEAD_AFTER_MS = 1500 +function loadedOnOpenInstead(): void {} + interface ProtectedRouteProps { children: ReactNode adminRequired?: boolean @@ -313,7 +333,7 @@ function RouteFallback() { if (isAppBoot()) return if (isPhone) return return ( -
+
) @@ -428,9 +448,18 @@ export default function App() { }, [settings.dark_mode, settings.appearance, isSharedPage]) const isPhone = useIsPhone() - // On the phone, pages slide like a native navigation stack (mobile/routeTransition.ts). + // On the phone, pages slide like a native navigation stack; on the desktop they + // cross-fade under a navbar that stands still (mobile/routeTransition.ts). const navigationType = useNavigationType() - const routedLocation = useRouteTransition(location, navigationType, isPhone) + const routedLocation = useRouteTransition(location, navigationType, isPhone ? 'phone' : 'desktop') + + useEffect(() => { + if (!isAuthenticated) return + const timer = window.setTimeout(() => { + for (const load of isPhone ? PHONE_SECTIONS : DESKTOP_SECTIONS) load().catch(loadedOnOpenInstead) + }, SECTIONS_AHEAD_AFTER_MS) + return () => window.clearTimeout(timer) + }, [isAuthenticated, isPhone]) const keepingTour = useSaveToCollectionStore(s => s.tour !== null) const isAuthPage = location.pathname.startsWith('/login') || location.pathname.startsWith('/register') diff --git a/client/src/components/Layout/Navbar.tsx b/client/src/components/Layout/Navbar.tsx index 1e703a7cb..63b53d622 100644 --- a/client/src/components/Layout/Navbar.tsx +++ b/client/src/components/Layout/Navbar.tsx @@ -228,7 +228,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings const isActive = location.pathname === tab.path return ( ({ pathname, key, search: '', hash: '', state: null }); @@ -34,9 +39,9 @@ describe('useRouteTransition', () => { vi.unstubAllGlobals(); }); - function render(initial: Location, enabled = true) { + function render(initial: Location, mode: RouteTransitionMode = 'phone') { return renderHook( - ({ location, type }: { location: Location; type: NavigationType }) => useRouteTransition(location, type, enabled), + ({ location, type }: { location: Location; type: NavigationType }) => useRouteTransition(location, type, mode), { initialProps: { location: initial, type: NavigationType.Push } } ); } @@ -62,9 +67,25 @@ describe('useRouteTransition', () => { expect(start).not.toHaveBeenCalled(); expect(hook.result.current.key).toBe('k2'); - const off = render(loc('/dashboard'), false); + const off = render(loc('/dashboard'), 'off'); off.rerender({ location: loc('/trips/2'), type: NavigationType.Push }); expect(off.result.current.pathname).toBe('/trips/2'); expect(start).not.toHaveBeenCalled(); }); + + it('cross-fades every change of page on the desktop, deeper ones too', async () => { + let marked: string | undefined; + start.mockImplementation((update: () => Promise) => { + marked = document.documentElement.dataset.routeTransition; + const done = update(); + return { finished: done, ready: done, updateCallbackDone: done, skipTransition: vi.fn() }; + }); + const hook = render(loc('/dashboard'), 'desktop'); + await act(async () => { + hook.rerender({ location: loc('/trips/3'), type: NavigationType.Push }); + }); + expect(start).toHaveBeenCalledTimes(1); + expect(marked).toBe('page'); + expect(hook.result.current.pathname).toBe('/trips/3'); + }); }); diff --git a/client/src/mobile/routeTransition.ts b/client/src/mobile/routeTransition.ts index 456f07759..54f1dfa2f 100644 --- a/client/src/mobile/routeTransition.ts +++ b/client/src/mobile/routeTransition.ts @@ -1,31 +1,28 @@ import { useLayoutEffect, useRef, useState } from 'react'; -import { flushSync } from 'react-dom'; import type { Location, NavigationType } from 'react-router'; +import { canAnimate, transitionTo } from '../utils/viewTransition'; /** - * Page transitions on the phone, the way a native navigation stack moves: a + * Page transitions. On the phone the way a native navigation stack moves: a * page opened from another slides in from the trailing edge over the one it * leaves, going back slides it away again, and switching between the main - * sections (the dock's destinations) only cross-fades. Built on the View - * Transitions API, so the browser animates snapshots and the pages themselves - * render as before; mobile.css holds the motion. + * sections (the dock's destinations) only cross-fades. On the desktop every + * change of page is one calm cross-fade under a navbar that stands still. + * Built on the View Transitions API, so the browser animates snapshots and the + * pages themselves render as before; mobile.css and styles/pageTransition.css + * hold the motion. * * The router is a declarative BrowserRouter, whose `viewTransition` option does * nothing, so App renders with the location this hook hands out and * the hook swaps it inside the transition. Routes load lazily: the swap waits - * (at most SETTLE_MS) until the new page replaced the route fallback, while the + * (at most a moment, see utils/viewTransition.ts) until the new page replaced the route fallback, while the * browser keeps showing the old snapshot, so the skeleton never flashes. */ -export type RouteTransitionKind = 'forward' | 'back' | 'tab'; +export type RouteTransitionKind = 'forward' | 'back' | 'tab' | 'page'; +/** Which motion the shell runs: the phone's stack, the desktop's cross-fade, or none. */ +export type RouteTransitionMode = 'phone' | 'desktop' | 'off'; -// Short on purpose: while it waits the browser shows a frozen snapshot of the old -// page, so on a slow connection a longer wait reads as the app hanging. -const SETTLE_MS = 350; let skipNext = false; -let current: ViewTransition | null = null; - -/** A newer navigation skipped this transition: its promises reject, and that is no error. */ -function skippedByNewer(): void {} /** The edge-swipe back gesture already slid the page away: the next change goes without a transition. */ export function skipNextRouteTransition(): void { @@ -41,33 +38,11 @@ export function transitionKind(from: Location, to: Location, navigationType: Nav return navigationType === 'POP' ? 'back' : 'forward'; } -function canAnimate(): boolean { - return ( - typeof document !== 'undefined' && - typeof document.startViewTransition === 'function' && - !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches - ); -} - -/** - * Resolves once no route fallback is on screen, or after SETTLE_MS. Polled with - * a timer, never requestAnimationFrame: while a view transition waits for its - * update, the browser renders no frames, so a frame callback never came and the - * transition hung until the browser gave up after four seconds, on every - * navigation. - */ -function settled(): Promise { - const began = performance.now(); - return new Promise((resolve) => { - const check = () => { - if (!document.querySelector('[data-route-fallback]') || performance.now() - began > SETTLE_MS) resolve(); - else window.setTimeout(check, 16); - }; - check(); - }); -} - -export function useRouteTransition(location: Location, navigationType: NavigationType, enabled: boolean): Location { +export function useRouteTransition( + location: Location, + navigationType: NavigationType, + mode: RouteTransitionMode +): Location { const [shown, setShown] = useState(location); const shownRef = useRef(location); @@ -78,25 +53,14 @@ export function useRouteTransition(location: Location, navigationType: Navigatio const skip = skipNext; skipNext = false; // A changed query or hash on the same page (a tab inside the trip, a filter) is not a navigation. - if (!enabled || skip || from.pathname === location.pathname || !canAnimate()) { + if (mode === 'off' || skip || from.pathname === location.pathname || !canAnimate()) { setShown(location); return; } - const root = document.documentElement; - root.dataset.routeTransition = transitionKind(from, location, navigationType); - const transition = document.startViewTransition(async () => { - flushSync(() => setShown(location)); - await settled(); - }); - current = transition; - // A newer navigation skips this one: both promises then reject, which is no error. - transition.ready.catch(skippedByNewer); - void transition.finished.catch(skippedByNewer).finally(() => { - // Only the newest transition clears the direction, or a skipped one would - // take it away from the one that replaced it. - if (current === transition) delete root.dataset.routeTransition; - }); - }, [location, navigationType, enabled]); + transitionTo(mode === 'desktop' ? 'page' : transitionKind(from, location, navigationType), () => + setShown(location) + ); + }, [location, navigationType, mode]); - return enabled ? shown : location; + return mode === 'off' ? location : shown; } diff --git a/client/src/styles/pageTransition.css b/client/src/styles/pageTransition.css new file mode 100644 index 000000000..7296fe829 --- /dev/null +++ b/client/src/styles/pageTransition.css @@ -0,0 +1,46 @@ +/* + * Changing page on the desktop (mobile/routeTransition.ts marks it 'page'): one + * short cross-fade, the old page and the new at the same time, with nothing + * moving. Short on purpose: a page change has to feel like an answer to the + * click, not like something to wait for. The navbar keeps its own name, so it + * stands still above the pages instead of fading with them; it switches to its + * new state at once. + */ +[data-desktop-navbar] { + view-transition-name: trek-navbar; +} + +@keyframes trek-page-out { + to { + opacity: 0; + } +} + +@keyframes trek-page-in { + from { + opacity: 0; + } +} + +:root[data-route-transition='page']::view-transition-old(root) { + animation: trek-page-out 0.14s ease-out both; +} + +:root[data-route-transition='page']::view-transition-new(root) { + animation: trek-page-in 0.14s ease-out both; +} + +::view-transition-old(trek-navbar) { + display: none; +} + +::view-transition-new(trek-navbar) { + animation: none; +} + +@media (prefers-reduced-motion: reduce) { + :root[data-route-transition='page']::view-transition-old(root), + :root[data-route-transition='page']::view-transition-new(root) { + animation: none; + } +} diff --git a/client/src/utils/viewTransition.ts b/client/src/utils/viewTransition.ts new file mode 100644 index 000000000..d95280fc6 --- /dev/null +++ b/client/src/utils/viewTransition.ts @@ -0,0 +1,66 @@ +import { flushSync } from 'react-dom'; + +/** + * The View Transitions groundwork the app's page changes share: whether to + * animate at all, how long to hold the old picture while new code arrives, and + * the plain cross-fade a change inside a page (a trip's tab) runs. The browser + * animates snapshots, so the views themselves render as before; + * styles/pageTransition.css holds the motion. + */ + +// Short on purpose: while it waits the browser shows a frozen snapshot of the old +// page, so on a slow connection a longer wait reads as the app hanging. +const SETTLE_MS = 350; +let current: ViewTransition | null = null; + +/** A newer change skipped this transition: its promises reject, and that is no error. */ +function skippedByNewer(): void {} + +export function canAnimate(): boolean { + return ( + typeof document !== 'undefined' && + typeof document.startViewTransition === 'function' && + !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches + ); +} + +/** + * Resolves once no placeholder for code still loading (`data-route-fallback`) + * is on screen, or after SETTLE_MS. Polled with a timer, never + * requestAnimationFrame: while a view transition waits for its update, the + * browser renders no frames, so a frame callback never came and the + * transition hung until the browser gave up after four seconds. + */ +export function settled(): Promise { + const began = performance.now(); + return new Promise((resolve) => { + const check = () => { + if (!document.querySelector('[data-route-fallback]') || performance.now() - began > SETTLE_MS) resolve(); + else window.setTimeout(check, 16); + }; + check(); + }); +} + +/** + * Runs `update` inside a view transition marked `kind` on the root, which the + * stylesheets read for the motion. Only the newest transition clears the mark, + * or a skipped one would take it away from the one that replaced it. + */ +export function transitionTo(kind: string, update: () => void): void { + if (!canAnimate()) { + update(); + return; + } + const root = document.documentElement; + root.dataset.routeTransition = kind; + const transition = document.startViewTransition(async () => { + flushSync(update); + await settled(); + }); + current = transition; + transition.ready.catch(skippedByNewer); + void transition.finished.catch(skippedByNewer).finally(() => { + if (current === transition) delete root.dataset.routeTransition; + }); +}