|
| 1 | +const accountCenterBasePath = '/account-center'; |
| 2 | +const storageKey = 'account-center-route-cache'; |
| 3 | + |
| 4 | +const knownRoutePrefixes: readonly string[] = ['/email', '/phone', '/username', '/password']; |
| 5 | + |
| 6 | +const isKnownRoute = (pathname?: string): pathname is string => |
| 7 | + pathname !== undefined && |
| 8 | + knownRoutePrefixes.some((prefix) => |
| 9 | + pathname.replace(accountCenterBasePath, '').startsWith(prefix) |
| 10 | + ); |
| 11 | + |
| 12 | +const parseStoredRoute = (storedRoute: string | undefined): string | undefined => { |
| 13 | + if (storedRoute && isKnownRoute(storedRoute)) { |
| 14 | + return storedRoute; |
| 15 | + } |
| 16 | + return undefined; |
| 17 | +}; |
| 18 | + |
| 19 | +const shouldSkipHandling = (search: string) => { |
| 20 | + const parameters = new URLSearchParams(search); |
| 21 | + return parameters.has('code') || parameters.has('error'); |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * Handle Account Center route restoration for sign in redirect. |
| 26 | + */ |
| 27 | +export const handleAccountCenterRoute = () => { |
| 28 | + if (shouldSkipHandling(window.location.search)) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + // Restore the stored route if the current path is the base path. |
| 33 | + if (window.location.pathname === accountCenterBasePath) { |
| 34 | + const storedRoute = parseStoredRoute(sessionStorage.getItem(storageKey) ?? undefined); |
| 35 | + if (!storedRoute) { |
| 36 | + sessionStorage.removeItem(storageKey); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + const { search, hash } = window.location; |
| 41 | + window.history.replaceState({}, '', `${storedRoute}${search}${hash}`); |
| 42 | + } else if (isKnownRoute(window.location.pathname)) { |
| 43 | + sessionStorage.setItem(storageKey, window.location.pathname); |
| 44 | + } |
| 45 | +}; |
0 commit comments