File size: 2,430 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import pagejs from '@automattic/calypso-router';
import { createMemoryHistory } from '@tanstack/react-router';
import { getQueryArgs } from '@wordpress/url';
import type { AnyRoute, AnyRouter } from '@tanstack/react-router';

export function getRouterOptions() {
	return {
		defaultPreload: 'intent' as const,
		defaultPreloadStaleTime: 0,
		defaultNotFoundComponent: () => null,
		defaultViewTransition: true,

		// Use memory history to compartmentalize TanStack Router's history management.
		// This way, we separate TanStack Router's history implementation from the browser history used by page.js.
		history: createMemoryHistory( { initialEntries: [ window.location.pathname ] } ),
	};
}

export function createBrowserHistoryAndMemoryRouterSync( {
	compatibilityRoutes,
}: {
	compatibilityRoutes?: AnyRoute[];
} = {} ) {
	let lastPath = '';

	const syncBrowserHistoryToRouter = ( router: AnyRouter ) => {
		const currentPath = `${ window.location.pathname }${ window.location.search }`;
		const basepath = router.options.basepath;

		// Avoid handling routes outside of the basepath.
		if ( basepath && ! currentPath.startsWith( basepath ) ) {
			return;
		}

		if ( currentPath !== lastPath ) {
			router.navigate( {
				to: window.location.pathname,
				search: getQueryArgs( window.location.search ),
				replace: true,
			} );
			lastPath = currentPath;
		}
	};

	const isCompatibilityRoute = ( router: AnyRouter, url: string ) => {
		const matches = router.matchRoutes( url );
		if ( ! matches ) {
			return false;
		}

		const compatibilityRouteIds = compatibilityRoutes?.map( ( route: AnyRoute ) => route.id ) ?? [];
		return matches.some( ( match: { routeId: string } ) =>
			compatibilityRouteIds.includes( match.routeId )
		);
	};

	const syncMemoryRouterToBrowserHistory = ( router: AnyRouter ) => {
		// Sync TanStack Router's history to the browser history (pagejs).
		return router.history.subscribe( ( { location }: { location: Location } ) => {
			const { pathname, search } = location;
			const newUrl = `${ pathname }${ search }`;

			// Avoid pushing redirect routes to the browser history.
			if ( compatibilityRoutes && isCompatibilityRoute( router, newUrl ) ) {
				return;
			}

			if ( window.location.pathname + window.location.search !== newUrl ) {
				pagejs.show( newUrl );
				lastPath = newUrl;
			}
		} );
	};

	return {
		syncBrowserHistoryToRouter,
		syncMemoryRouterToBrowserHistory,
	};
}