diff --git a/.changeset/lazy-chunk-unload-no-reload.md b/.changeset/lazy-chunk-unload-no-reload.md new file mode 100644 index 00000000000..8eadefd9fda --- /dev/null +++ b/.changeset/lazy-chunk-unload-no-reload.md @@ -0,0 +1,8 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +--- + +Do not reload the page when Firefox or Safari cancel a pending route chunk because the user is leaving the page. The cancellation has the same message as a missing chunk, and the stale-deploy reload replaced the user's navigation. If the page stays after all, the chunk import is retried. diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index a7b58c44991..932edbe3331 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -1,5 +1,9 @@ import * as React from 'react' -import { isModuleNotFoundError } from '@tanstack/router-core' +import { + isModuleNotFoundError, + waitForPageToStay, + watchPageUnload, +} from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { reactUse } from './utils' import type { AsyncRouteComponent } from './route' @@ -25,12 +29,17 @@ export function lazyRouteComponent< let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any + let cancelledByUnload = false + let staying: Promise | undefined const load = () => { if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() // Resolved clients have no preload work; SSR can reuse the import. if (!(isServer ?? typeof window === 'undefined')) { loadPromise = undefined @@ -40,10 +49,22 @@ export function lazyRouteComponent< }) .catch((err) => { loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. error = err + // Start listening now: a pageshow before the next render would + // otherwise go unseen and leave the route suspended. Only clear the + // error if a newer attempt has not replaced it in the meantime. + staying = cancelledByUnload + ? waitForPageToStay().then(() => { + if (error !== err) return + staying = undefined + error = undefined + cancelledByUnload = false + }) + : undefined }) } @@ -51,6 +72,12 @@ export function lazyRouteComponent< } const lazyComp = function Lazy(props: any) { if (error) { + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page + // stays after all, retry the import instead. + if (cancelledByUnload && staying) { + throw staying + } // A missing module can mean that a newer deployment replaced the URL. // Reload only for the error that is still current at render time, so a // successful retry cannot leave a stale reload request armed. diff --git a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..54940d120be --- /dev/null +++ b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,188 @@ +import * as React from 'react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) + sessionStorage.clear() + vi.restoreAllMocks() +}) + +// jsdom cannot reload, so React retries the render and reaches the error that +// the reload guard rethrows once its key is set. +class ErrorBoundary extends React.Component< + { children: React.ReactNode }, + { error: unknown } +> { + state: { error: unknown } = { error: undefined } + static getDerivedStateFromError(error: unknown) { + return { error } + } + render() { + return this.state.error ?
Error
: this.props.children + } +} + +function renderLazy(Page: ReturnType) { + return render( + + Loading}> + + + , + ) +} + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + renderLazy(Page) + expect(screen.getByText('Loading')).toBeInTheDocument() + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('reloads once if the retried import is still missing after the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new TypeError(message)) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + renderLazy(Page) + fireEvent.keyDown(document.body) + await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) + expect(importer).toHaveBeenCalledTimes(2) +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + renderLazy(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) + +test('stops watching for unload once the import settles', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + // A later unload must not be attributed to the import that already failed. + window.dispatchEvent(new Event('beforeunload')) + renderLazy(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + renderLazy(Page) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + renderLazy(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('a newer failed preload keeps its error when the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new Error('Broken module')) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // A second preload fails for another reason before the route renders. + await Page.preload!() + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + renderLazy(Page) + expect(screen.getByText('Error')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 9206ef60dd8..2bd981f229c 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -322,6 +322,8 @@ export { createControlledPromise, isPromise, isModuleNotFoundError, + watchPageUnload, + waitForPageToStay, DEFAULT_PROTOCOL_ALLOWLIST, escapeHtml, getUrlScheme, diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 63aa5186953..6131d5fbc75 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -516,6 +516,80 @@ export function isModuleNotFoundError(error: any): boolean { ) } +const stayEvents = ['pageshow', 'pointerdown', 'keydown'] as const + +// Shared between imports, so one that starts after `beforeunload` still knows +// the page is leaving. The `beforeunload` listener is only attached while an +// import is pending, because Firefox keeps a page with one out of the +// back/forward cache. +let pendingImports = 0 +let pageIsLeaving = false +let leaveCount = 0 + +function onBeforeUnload() { + leaveCount++ + if (pageIsLeaving) return + pageIsLeaving = true + for (const event of stayEvents) { + window.addEventListener(event, onStay, true) + } +} + +function onStay() { + pageIsLeaving = false + for (const event of stayEvents) { + window.removeEventListener(event, onStay, true) + } +} + +/** + * Firefox and Safari cancel a pending dynamic import when the page starts to + * unload, and reject it with the same message as a missing module. Call this + * before an import, and the returned function after it settles: it stops + * watching and reports whether the page was leaving at any point in between, + * including when the import started after `beforeunload`. In that case the + * failure says nothing about a stale deployment. + */ +export function watchPageUnload(): () => boolean { + if (typeof window === 'undefined') { + return () => false + } + const leavingAtStart = pageIsLeaving + const leaveCountAtStart = leaveCount + if (pendingImports++ === 0) { + window.addEventListener('beforeunload', onBeforeUnload) + } + let stopped = false + return () => { + if (!stopped) { + stopped = true + if (--pendingImports === 0) { + window.removeEventListener('beforeunload', onBeforeUnload) + } + } + return leavingAtStart || leaveCount !== leaveCountAtStart + } +} + +/** + * Resolves on the first sign that the page is still in use after + * `beforeunload`. Some browsers fire it for `mailto:` or download links without + * leaving, and a page restored from the back/forward cache comes back too. + */ +export function waitForPageToStay(): Promise { + return new Promise((resolve) => { + const stay = () => { + for (const event of stayEvents) { + window.removeEventListener(event, stay, true) + } + resolve() + } + for (const event of stayEvents) { + window.addEventListener(event, stay, true) + } + }) +} + export function isPromise( value: Promise> | T, ): value is Promise> { diff --git a/packages/router-core/tests/page-unload.test.ts b/packages/router-core/tests/page-unload.test.ts new file mode 100644 index 00000000000..a8f079cff8a --- /dev/null +++ b/packages/router-core/tests/page-unload.test.ts @@ -0,0 +1,67 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { waitForPageToStay, watchPageUnload } from '../src/utils' + +// https://github.com/TanStack/router/issues/8827 +afterEach(() => { + // Any leftover "leaving" state ends when the page is shown again. + window.dispatchEvent(new Event('pageshow')) + vi.restoreAllMocks() +}) + +test('reports an unload that happens while the import is pending', () => { + const stop = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + expect(stop()).toBe(true) +}) + +test('reports nothing when the page does not unload', () => { + const stop = watchPageUnload() + expect(stop()).toBe(false) +}) + +test('reports an import that starts after beforeunload', () => { + const first = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + + // Started while the page was already leaving. + const second = watchPageUnload() + first() + expect(second()).toBe(true) +}) + +test('an import that starts after the page stayed is not affected', () => { + const first = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + first() + + window.dispatchEvent(new Event('pointerdown')) + const second = watchPageUnload() + expect(second()).toBe(false) +}) + +test('only listens for beforeunload while an import is pending', () => { + const add = vi.spyOn(window, 'addEventListener') + const remove = vi.spyOn(window, 'removeEventListener') + const beforeUnloadCalls = (spy: typeof add) => + spy.mock.calls.filter(([event]) => event === 'beforeunload').length + + const first = watchPageUnload() + const second = watchPageUnload() + expect(beforeUnloadCalls(add)).toBe(1) + + first() + expect(beforeUnloadCalls(remove)).toBe(0) + second() + second() + expect(beforeUnloadCalls(remove)).toBe(1) +}) + +test('waitForPageToStay resolves on the first stay event', async () => { + const stayed = vi.fn() + waitForPageToStay().then(stayed) + await Promise.resolve() + expect(stayed).not.toHaveBeenCalled() + + window.dispatchEvent(new Event('keydown')) + await vi.waitFor(() => expect(stayed).toHaveBeenCalled()) +}) diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 32d4f071102..ba5687bfb6e 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -1,6 +1,10 @@ import { Dynamic } from 'solid-js/web' import { lazy } from 'solid-js' -import { isModuleNotFoundError } from '@tanstack/router-core' +import { + isModuleNotFoundError, + waitForPageToStay, + watchPageUnload, +} from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import type { AsyncRouteComponent } from './route' @@ -16,12 +20,17 @@ export function lazyRouteComponent< let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any + let cancelledByUnload = false + let staying: Promise | undefined const load = () => { if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() // Resolved clients have no preload work; SSR can reuse the import. if (!(isServer ?? typeof window === 'undefined')) { loadPromise = undefined @@ -32,6 +41,10 @@ export function lazyRouteComponent< }) .catch((err) => { loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) + // Start listening now: a pageshow before the retry is rendered + // would otherwise go unseen and leave the route suspended. + staying = cancelledByUnload ? waitForPageToStay() : undefined error = err }) } @@ -48,6 +61,19 @@ export function lazyRouteComponent< // Both preload and lazy resolution end here without starting another load. function render(props: any) { + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page stays + // after all, retry the import instead. + if (error && cancelledByUnload && staying) { + const stay = staying + const Retry = lazy(async () => { + await stay + await load() + return { default: render } + }) + return + } + // Now that we're out of preload and into actual render path, // throw the error if it was a module not found error during preload if (error) { diff --git a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..08ad789ed08 --- /dev/null +++ b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,104 @@ +import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) + sessionStorage.clear() + vi.restoreAllMocks() +}) + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(() => ) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + render(() => ) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + render(() => ) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + render(() => ) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index 3137e15ba4f..67c5df7d9a1 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -1,4 +1,5 @@ import * as Vue from 'vue' +import { waitForPageToStay, watchPageUnload } from '@tanstack/router-core' import { Outlet } from './Match' import { ClientOnly } from './ClientOnly' import type { AsyncRouteComponent } from './route' @@ -34,6 +35,8 @@ export function lazyRouteComponent< let comp: T[TKey] | T['default'] | null = null let error: any = null let attemptedReload = false + let cancelledByUnload = false + let staying: Promise | undefined const load = () => { // If we're on the server and SSR is disabled for this component @@ -45,8 +48,11 @@ export function lazyRouteComponent< // Use existing promise or create new one if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() if (typeof document !== 'undefined') { loadPromise = undefined ;(lazyComp as any).preload = undefined @@ -57,6 +63,10 @@ export function lazyRouteComponent< .catch((err) => { error = err loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) + // Start listening now: a pageshow before the component mounts + // would otherwise go unseen and leave the route empty. + staying = cancelledByUnload ? waitForPageToStay() : undefined // If it's a module not found error, we'll try to handle it in the component if (isModuleNotFoundError(error)) { @@ -69,6 +79,39 @@ export function lazyRouteComponent< return loadPromise } + // Reload once for a missing module. Returns true if a reload was started. + const reloadOnce = (err: any) => { + if ( + attemptedReload || + typeof window === 'undefined' || + typeof sessionStorage === 'undefined' + ) { + return false + } + const storageKey = `tanstack_router_reload:${err.message}` + if (sessionStorage.getItem(storageKey)) { + return false + } + sessionStorage.setItem(storageKey, '1') + attemptedReload = true + window.location.reload() + return true + } + + // After a retry, a failed import comes back as null with the error recorded. + // Wait again if this import was also cancelled by an unload, otherwise give + // the missing module the same single reload as the first render would. + const settleRetry = (result: any): any => { + if (result || !error) return result + if (cancelledByUnload && staying) { + return staying.then(load).then(settleRetry) + } + if (isModuleNotFoundError(error) && reloadOnce(error)) { + return null + } + throw error + } + // Create a lazy component wrapper using defineComponent so it works in Vue SFC templates const lazyComp = Vue.defineComponent({ name: 'LazyRouteComponent', @@ -76,15 +119,20 @@ export function lazyRouteComponent< // Create refs to track component state // Use shallowRef for component to avoid making it reactive (Vue warning) const component = Vue.shallowRef(comp ? Vue.markRaw(comp) : comp) - const errorState = Vue.ref(error) + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page + // stays after all, retry the import instead. + const retryAfterUnload = !!error && cancelledByUnload && !!staying + const stay = staying + const errorState = Vue.ref(retryAfterUnload ? null : error) const loading = Vue.ref(!component.value && !errorState.value) // Setup effect to load the component when this component is used Vue.onMounted(() => { if (!component.value && !errorState.value) { loading.value = true - - load() + ;(retryAfterUnload ? stay!.then(load) : load()) + .then(settleRetry) .then((result) => { // Use markRaw to prevent Vue from making the component reactive component.value = result ? Vue.markRaw(result) : result @@ -101,21 +149,9 @@ export function lazyRouteComponent< if ( errorState.value && isModuleNotFoundError(errorState.value) && - !attemptedReload + reloadOnce(errorState.value) ) { - if ( - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Try to reload once on module not found error - const storageKey = `tanstack_router_reload:${errorState.value.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - attemptedReload = true - window.location.reload() - return () => null // Return empty while reloading - } - } + return () => null // Return empty while reloading } // If we have a non-module-not-found error, throw it diff --git a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..2d32109f63d --- /dev/null +++ b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,147 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/vue' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) + sessionStorage.clear() + vi.restoreAllMocks() +}) + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + render(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + render(Page) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('reloads once if the retried import is still missing after the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new TypeError(message)) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(Page) + await fireEvent.keyDown(document.body) + await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) + expect(importer).toHaveBeenCalledTimes(2) +}) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + render(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('retries an import that the unload cancels after the route mounted', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Mounting starts the import. + render(Page) + await vi.waitFor(() => expect(importer).toHaveBeenCalledTimes(1)) + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + // Let the failed import settle before the page shows it stayed. + await new Promise((resolve) => setTimeout(resolve)) + + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +})