/** * Hash routes, as on the CookieYes screen: #/models, #/chatbot … One route * per page ID; unknown IDs and the bare screen go to the first page. Field * anchors (#wtofe_ai_model_title) are turned into routes before the router * sees them (see watchFieldAnchors()). */ import { createHashHistory, createRootRoute, createRoute, createRouter, redirect } from '@tanstack/react-router'; import App from './App'; import PageView from './pages/PageView'; import { availablePages } from './pages/registry'; import { useSettingsStore } from './store/settings-store'; function pageIds(): string[] { return availablePages( useSettingsStore.getState().sections ).map( ( page ) => page.id ); } /** Sends the visitor to the first page, if there is one. */ function toFirstPage(): void { const [ first ] = pageIds(); if ( first ) { throw redirect( { to: '/$page', params: { page: first }, replace: true } ); } } const rootRoute = createRootRoute( { component: App } ); const indexRoute = createRoute( { getParentRoute: () => rootRoute, path: '/', beforeLoad: toFirstPage, } ); const pageRoute = createRoute( { getParentRoute: () => rootRoute, path: '$page', beforeLoad: ( { params } ) => { if ( ! pageIds().includes( params.page ) ) { toFirstPage(); } }, component: PageView, } ); export const router = createRouter( { routeTree: rootRoute.addChildren( [ indexRoute, pageRoute ] ), history: createHashHistory(), defaultNotFoundComponent: () => null, } ); /* * WordPress 6.0 and 6.1 ship React 17, which renders on every state update * made outside its own event handlers. To navigate, the router sets a state * and then fills its route stores (router.startTransition(), reassigned on * every render of its Transitioner); React 18 renders once for both, React 17 * would render in between, with the stores still empty. Running each call in * one batch gives React 17 the single render React 18 does. */ if ( ! ( 'startTransition' in window.React ) ) { let startTransition: typeof router.startTransition; Object.defineProperty( router, 'startTransition', { configurable: true, get: () => startTransition, set( next: typeof router.startTransition ) { startTransition = ( ...args ) => { let result!: ReturnType; window.ReactDOM.unstable_batchedUpdates( () => { result = next( ...args ); } ); return result; }; }, } ); } declare module '@tanstack/react-router' { interface Register { router: typeof router; } }