Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions packages/react-router/src/headContentUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,16 @@ function buildTagsFromMatches(
children,
}))

const unmaskOnReloadScript = buildUnmaskOnReloadHeadScript(router, nonce)

return uniqBy(
[
...resultMeta,
...preloadLinks,
...constructedLinks,
...assetLinks,
...styles,
...(unmaskOnReloadScript ? [unmaskOnReloadScript] : []),
...headScripts,
] as Array<RouterManagedTag>,
(d) => JSON.stringify(d),
Expand Down Expand Up @@ -397,12 +400,19 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => {
deepEqual,
)

// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
const unmaskOnReloadScript = React.useMemo(
() => buildUnmaskOnReloadHeadScript(router, nonce),
[router, nonce],
)

return uniqBy(
[
...meta,
...preloadLinks,
...links,
...styles,
...(unmaskOnReloadScript ? [unmaskOnReloadScript] : []),
...headScripts,
] as Array<RouterManagedTag>,
(d) => {
Expand All @@ -411,6 +421,109 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => {
)
}

function buildUnmaskOnReloadHeadScript(
router: ReturnType<typeof useRouter>,
nonce: string | undefined,
) {
const routeMaskSources = (router.options.routeMasks ?? [])
.filter((routeMask) => routeMask.unmaskOnReload && typeof routeMask.from === 'string')
.map((routeMask) => routePathToRegExpSource(routeMask.from))

if (!routeMaskSources.length) return undefined

return {
tag: 'script',
attrs: nonce ? { nonce } : undefined,
children: `
(() => {
const maskedRoutePathPatterns = ${JSON.stringify(routeMaskSources)}
.map((source) => new RegExp(source))
const tempLocation = window.history.state?.__tempLocation
if (!tempLocation?.pathname) return
if (
tempLocation.pathname === window.location.pathname &&
(tempLocation.search ?? '') === window.location.search &&
(tempLocation.hash ?? '') === window.location.hash
) return
if (!maskedRoutePathPatterns.some((pattern) => pattern.test(tempLocation.pathname)))
return
window.location.replace(
tempLocation.pathname + (tempLocation.search ?? '') + (tempLocation.hash ?? ''),
)
})()
`,
} satisfies RouterManagedTag
}

function routePathToRegExpSource(routePath: string) {
let regExpSource = '^'

for (const segment of routePath.split('/').filter(Boolean)) {
const routeSegment = parseRoutePathSegment(segment)

if (routeSegment.type === 'optional-param') {
regExpSource += `(?:/${routeSegment.source})?`
continue
}

if (routeSegment.type === 'wildcard') {
regExpSource += `(?:/${routeSegment.source})?`
continue
}

regExpSource += `/${routeSegment.source}`
}

return `${regExpSource}$`
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

function parseRoutePathSegment(segment: string) {
if (!segment.includes('$')) {
return { source: escapeRegExp(segment), type: 'pathname' as const }
}

if (segment === '$') {
return { source: '.*', type: 'wildcard' as const }
}

if (segment.startsWith('$')) {
return { source: '[^/]+', type: 'param' as const }
}

const openBraceIndex = segment.indexOf('{')
if (openBraceIndex === -1) {
return { source: escapeRegExp(segment), type: 'pathname' as const }
}

const closeBraceIndex = segment.indexOf('}', openBraceIndex)
if (closeBraceIndex === -1) {
return { source: escapeRegExp(segment), type: 'pathname' as const }
}

const prefix = segment.slice(0, openBraceIndex)
const suffix = segment.slice(closeBraceIndex + 1)
const token = segment.slice(openBraceIndex + 1, closeBraceIndex)
const source = `${escapeRegExp(prefix)}${token === '$' ? '.*' : '[^/]+'}${escapeRegExp(suffix)}`

if (token === '$') {
return { source, type: 'wildcard' as const }
}

if (token.startsWith('-$') && token.length > 2) {
return { source, type: 'optional-param' as const }
}

if (token.startsWith('$') && token.length > 1) {
return { source, type: 'param' as const }
}

return { source: escapeRegExp(segment), type: 'pathname' as const }
}

function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

export function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) {
const seen = new Set<string>()
return arr.filter((item) => {
Expand Down
90 changes: 90 additions & 0 deletions packages/react-router/tests/Scripts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouteMask,
createRouter,
} from '../src'
import { Scripts } from '../src/Scripts'
Expand Down Expand Up @@ -371,6 +372,95 @@ describe('ssr HeadContent', () => {
)
})

test('injects a nonce-aware preload script for masks that unmask on reload', async () => {
const rootRoute = createRootRoute({
component: () => <HeadContent />,
})

const indexRoute = createRoute({
path: '/',
getParentRoute: () => rootRoute,
})

const modalRoute = createRoute({
path: '/modal',
getParentRoute: () => rootRoute,
})

const routeTree = rootRoute.addChildren([indexRoute, modalRoute])

const router = createRouter({
history: createMemoryHistory({
initialEntries: ['/'],
}),
isServer: true,
routeMasks: [
createRouteMask({
from: '/modal',
routeTree,
to: '/',
unmaskOnReload: true,
}),
],
routeTree,
ssr: {
nonce: 'test-nonce',
},
})

await router.load()

const html = ReactDOMServer.renderToString(
<RouterProvider router={router} />,
)

expect(html).toContain('<script nonce="test-nonce">')
expect(html).toContain('window.history.state?.__tempLocation')
expect(html).toContain('window.location.replace(')
expect(html).toContain('^/modal$')
})

test('does not inject an unmask-on-reload script for ordinary route masks', async () => {
const rootRoute = createRootRoute({
component: () => <HeadContent />,
})

const indexRoute = createRoute({
path: '/',
getParentRoute: () => rootRoute,
})

const modalRoute = createRoute({
path: '/modal',
getParentRoute: () => rootRoute,
})

const routeTree = rootRoute.addChildren([indexRoute, modalRoute])

const router = createRouter({
history: createMemoryHistory({
initialEntries: ['/'],
}),
isServer: true,
routeMasks: [
createRouteMask({
from: '/modal',
routeTree,
to: '/',
}),
],
routeTree,
})

await router.load()

const html = ReactDOMServer.renderToString(
<RouterProvider router={router} />,
)

expect(html).not.toContain('window.history.state?.__tempLocation')
})

test('keeps manifest stylesheet links mounted when history state changes', async () => {
const history = createTestBrowserHistory()

Expand Down