|
1 | 1 | import { useClerk } from '@clerk/shared/react'; |
2 | 2 | import type { NavigateOptions } from '@clerk/shared/types'; |
3 | 3 | import React from 'react'; |
| 4 | +import { flushSync } from 'react-dom'; |
4 | 5 |
|
5 | 6 | import { getQueryParams, stringifyQueryParams, trimTrailingSlash } from '../../utils'; |
6 | | -import { useWindowEventListener } from '../hooks'; |
7 | 7 | import { newPaths } from './newPaths'; |
8 | 8 | import { match } from './pathToRegexp'; |
9 | 9 | import { Route } from './Route'; |
10 | 10 | import { RouteContext } from './RouteContext'; |
11 | 11 |
|
| 12 | +// Custom events that don't exist on WindowEventMap but are handled |
| 13 | +// by wrapping history.pushState/replaceState in the fallback path. |
| 14 | +type HistoryEvent = 'pushstate' | 'replacestate'; |
| 15 | +type RefreshEvent = keyof WindowEventMap | HistoryEvent; |
| 16 | +type NavigationType = 'push' | 'replace' | 'traverse'; |
| 17 | + |
| 18 | +const isWindowRefreshEvent = (event: RefreshEvent): event is keyof WindowEventMap => { |
| 19 | + return event !== 'pushstate' && event !== 'replacestate'; |
| 20 | +}; |
| 21 | + |
| 22 | +// Maps refresh events to Navigation API navigationType values. |
| 23 | +const eventToNavigationType: Partial<Record<RefreshEvent, NavigationType>> = { |
| 24 | + popstate: 'traverse', |
| 25 | + pushstate: 'push', |
| 26 | + replacestate: 'replace', |
| 27 | +}; |
| 28 | + |
| 29 | +// Global subscription sets for the history monkey-patching fallback. |
| 30 | +// Using a single patch with subscriber sets avoids conflicts when |
| 31 | +// multiple BaseRouter instances mount simultaneously. |
| 32 | +const pushStateSubscribers = new Set<() => void>(); |
| 33 | +const replaceStateSubscribers = new Set<() => void>(); |
| 34 | +let originalPushState: History['pushState'] | null = null; |
| 35 | +let originalReplaceState: History['replaceState'] | null = null; |
| 36 | + |
| 37 | +function ensurePushStatePatched(): void { |
| 38 | + if (originalPushState) { |
| 39 | + return; |
| 40 | + } |
| 41 | + originalPushState = history.pushState.bind(history); |
| 42 | + history.pushState = (...args: Parameters<History['pushState']>) => { |
| 43 | + originalPushState!(...args); |
| 44 | + pushStateSubscribers.forEach(fn => fn()); |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +function ensureReplaceStatePatched(): void { |
| 49 | + if (originalReplaceState) { |
| 50 | + return; |
| 51 | + } |
| 52 | + originalReplaceState = history.replaceState.bind(history); |
| 53 | + history.replaceState = (...args: Parameters<History['replaceState']>) => { |
| 54 | + originalReplaceState!(...args); |
| 55 | + replaceStateSubscribers.forEach(fn => fn()); |
| 56 | + }; |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Observes history changes so the router's internal state stays in sync |
| 61 | + * with the URL. Uses the Navigation API when available, falling back to |
| 62 | + * monkey-patching history.pushState/replaceState plus native window events. |
| 63 | + * |
| 64 | + * Note: `events` should be a stable array reference to avoid |
| 65 | + * re-subscribing on every render. |
| 66 | + */ |
| 67 | +function useHistoryChangeObserver(events: Array<RefreshEvent> | undefined, callback: () => void): void { |
| 68 | + const callbackRef = React.useRef(callback); |
| 69 | + callbackRef.current = callback; |
| 70 | + |
| 71 | + React.useEffect(() => { |
| 72 | + if (!events) { |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + const notify = () => callbackRef.current(); |
| 77 | + const windowEvents = events.filter(isWindowRefreshEvent); |
| 78 | + const navigationTypes = events |
| 79 | + .map(e => eventToNavigationType[e]) |
| 80 | + .filter((type): type is NavigationType => Boolean(type)); |
| 81 | + |
| 82 | + const hasNavigationAPI = |
| 83 | + typeof window !== 'undefined' && |
| 84 | + 'navigation' in window && |
| 85 | + typeof (window as any).navigation?.addEventListener === 'function'; |
| 86 | + |
| 87 | + if (hasNavigationAPI) { |
| 88 | + const nav = (window as any).navigation; |
| 89 | + const allowedTypes = new Set(navigationTypes); |
| 90 | + const handler = (e: { navigationType: NavigationType }) => { |
| 91 | + if (allowedTypes.has(e.navigationType)) { |
| 92 | + Promise.resolve().then(notify); |
| 93 | + } |
| 94 | + }; |
| 95 | + nav.addEventListener('currententrychange', handler); |
| 96 | + |
| 97 | + // Events without a navigationType mapping (e.g. hashchange) still |
| 98 | + // need native listeners even when the Navigation API is available. |
| 99 | + const unmappedEvents = windowEvents.filter(e => !eventToNavigationType[e]); |
| 100 | + unmappedEvents.forEach(e => window.addEventListener(e, notify)); |
| 101 | + |
| 102 | + return () => { |
| 103 | + nav.removeEventListener('currententrychange', handler); |
| 104 | + unmappedEvents.forEach(e => window.removeEventListener(e, notify)); |
| 105 | + }; |
| 106 | + } |
| 107 | + |
| 108 | + // Fallback: use global subscriber sets for pushState/replaceState |
| 109 | + // so that multiple BaseRouter instances don't conflict. |
| 110 | + if (events.includes('pushstate')) { |
| 111 | + ensurePushStatePatched(); |
| 112 | + pushStateSubscribers.add(notify); |
| 113 | + } |
| 114 | + if (events.includes('replacestate')) { |
| 115 | + ensureReplaceStatePatched(); |
| 116 | + replaceStateSubscribers.add(notify); |
| 117 | + } |
| 118 | + |
| 119 | + windowEvents.forEach(e => window.addEventListener(e, notify)); |
| 120 | + |
| 121 | + return () => { |
| 122 | + pushStateSubscribers.delete(notify); |
| 123 | + replaceStateSubscribers.delete(notify); |
| 124 | + windowEvents.forEach(e => window.removeEventListener(e, notify)); |
| 125 | + }; |
| 126 | + }, [events]); |
| 127 | +} |
| 128 | + |
12 | 129 | interface BaseRouterProps { |
13 | 130 | basePath: string; |
14 | 131 | startPath: string; |
15 | 132 | getPath: () => string; |
16 | 133 | getQueryString: () => string; |
17 | 134 | internalNavigate: (toURL: URL, options?: NavigateOptions) => Promise<any> | any; |
18 | | - refreshEvents?: Array<keyof WindowEventMap>; |
| 135 | + refreshEvents?: Array<RefreshEvent>; |
19 | 136 | preservedParams?: string[]; |
20 | 137 | urlStateParam?: { |
21 | 138 | startPath: string; |
@@ -86,7 +203,23 @@ export const BaseRouter = ({ |
86 | 203 | } |
87 | 204 | }, [currentPath, currentQueryString, getPath, getQueryString]); |
88 | 205 |
|
89 | | - useWindowEventListener(refreshEvents, refresh); |
| 206 | + // Suppresses the history observer during baseNavigate's internal navigation. |
| 207 | + // Without this, the observer's microtask triggers a render before setActive's |
| 208 | + // #updateAccessors sets clerk.session, causing task guards to see stale state. |
| 209 | + const isNavigatingRef = React.useRef(false); |
| 210 | + |
| 211 | + const observerRefresh = React.useCallback((): void => { |
| 212 | + if (isNavigatingRef.current) { |
| 213 | + return; |
| 214 | + } |
| 215 | + const newPath = getPath(); |
| 216 | + if (basePath && !newPath.startsWith('/' + basePath)) { |
| 217 | + return; |
| 218 | + } |
| 219 | + refresh(); |
| 220 | + }, [basePath, getPath, refresh]); |
| 221 | + |
| 222 | + useHistoryChangeObserver(refreshEvents, observerRefresh); |
90 | 223 |
|
91 | 224 | // TODO: Look into the real possible types of globalNavigate |
92 | 225 | const baseNavigate = async (toURL: URL | undefined): Promise<unknown> => { |
@@ -116,9 +249,20 @@ export const BaseRouter = ({ |
116 | 249 |
|
117 | 250 | toURL.search = stringifyQueryParams(toQueryParams); |
118 | 251 | } |
119 | | - const internalNavRes = await internalNavigate(toURL, { metadata: { navigationType: 'internal' } }); |
120 | | - setRouteParts({ path: toURL.pathname, queryString: toURL.search }); |
121 | | - return internalNavRes; |
| 252 | + isNavigatingRef.current = true; |
| 253 | + try { |
| 254 | + const internalNavRes = await internalNavigate(toURL, { metadata: { navigationType: 'internal' } }); |
| 255 | + // We need to flushSync to guarantee the re-render happens before handing things back to the caller, |
| 256 | + // otherwise setActive might emit, and children re-render with the old navigation state. |
| 257 | + // An alternative solution here could be to return a deferred promise, set that to state together |
| 258 | + // with the routeParts and resolve it in an effect. That way we could avoid the flushSync performance penalty. |
| 259 | + flushSync(() => { |
| 260 | + setRouteParts({ path: toURL.pathname, queryString: toURL.search }); |
| 261 | + }); |
| 262 | + return internalNavRes; |
| 263 | + } finally { |
| 264 | + isNavigatingRef.current = false; |
| 265 | + } |
122 | 266 | }; |
123 | 267 |
|
124 | 268 | return ( |
|
0 commit comments