mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
feat(client): calm page changes on the desktop and sections loaded ahead
The desktop now runs the View Transition the phone already had: one short cross-fade under a navbar that stands still. The route fallback holds the previous page until the new one is ready (at most 350 ms), so the full-screen spinner no longer flashes. Once signed in, the main sections' code loads in the background, so the first switch to one does not wait for it. The shared transition helpers move to utils/viewTransition.ts. The navbar tabs lose their title tooltips; their aria-label stays.
This commit is contained in:
@@ -1,7 +1,12 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { NavigationType, type Location } from 'react-router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { skipNextRouteTransition, transitionKind, useRouteTransition } from './routeTransition';
|
||||
import {
|
||||
skipNextRouteTransition,
|
||||
transitionKind,
|
||||
useRouteTransition,
|
||||
type RouteTransitionMode,
|
||||
} from './routeTransition';
|
||||
|
||||
const loc = (pathname: string, key = pathname): Location => ({ 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<void>) => {
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 <Routes> 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<void> {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user