Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
36 changes: 36 additions & 0 deletions e2e/phone-journey.mobile.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { z } from 'zod'
import { expect } from '@playwright/test'
import { COOKIE_ALGOLIA_USER_TOKEN_KEY } from '~/constants/cookie'
import { HTTP_STATUS } from '~/constants/http'
import { m } from '~/paraglide/messages'
import {
AI_SEARCH_PATH,
Expand All @@ -21,6 +22,8 @@ const LIBRARY_PATHNAME = '/memes/category/all'

const FAR_DOWN_CARD_INDEX = 19

const REELS_MODULE_PATTERN = /\/assets\/use-register-meme-view-[\w-]+\.js$/u

const ALGOLIA_INSIGHTS_EVENTS_URL = new URL('/1/events', E2E_ALGOLIA_ORIGIN)
.href

Expand Down Expand Up @@ -75,6 +78,39 @@ test.describe('the phone journey', () => {
await expect(page).toHaveURL('/')
})

test('the Reels feed recovers from a module that failed to load once', async ({
page
}) => {
await page.goto('/')
await expect(
page.getByRole('region', { name: /^Notifications/u })
).toBeAttached()

let hasFailedAModule = false

await page.route(REELS_MODULE_PATTERN, (route) => {
if (hasFailedAModule) {
return route.fallback()
}

hasFailedAModule = true

return route.fulfill({ status: HTTP_STATUS.SERVICE_UNAVAILABLE })
})

const tabBar = page.getByTestId('tab-bar')

await tabBar.getByRole('link', { name: m.nav_reels(), exact: true }).click()

await expect(page).toHaveURL('/reels')
await expect(
page.getByRole('feed', { name: m.meme_video_feed() })
).toBeFocused()
await tabBar.getByRole('link', { name: m.nav_home(), exact: true }).click()
await expect(page).toHaveURL('/')
expect(hasFailedAModule).toBe(true)
})

test('the search tab finds a Meme by its title', async ({ page }) => {
await page.goto('/')

Expand Down
69 changes: 59 additions & 10 deletions src/lib/__tests__/stale-chunk-reload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,21 @@ type NavigationStub = {
downloadRequest?: string | null
}

const reload = vi.fn<() => void>()
const PAGE_ORIGIN = 'https://petit-meme.test'

const PAGE_MODULE_URL = `${PAGE_ORIGIN}/assets/reels-a1b2c3.js`

const steps: string[] = []

const reload = vi.fn<() => void>(() => {
steps.push('reload')
})

const refetch = vi.fn<(url: string) => Promise<Response>>((url) => {
steps.push(`fetch ${url}`)

return Promise.resolve(new Response())
})

const stubPage = () => {
const page = new EventTarget()
Expand All @@ -15,8 +29,25 @@ const stubPage = () => {

vi.stubGlobal(
'window',
Object.assign(page, { navigation, location: { reload } })
Object.assign(page, {
navigation,
location: { reload, origin: PAGE_ORIGIN }
})
)
vi.stubGlobal('performance', {
getEntriesByType: () => {
return [
{ name: PAGE_MODULE_URL },
{ name: `${PAGE_ORIGIN}/fonts/bricolage.woff2` }
]
}
})
vi.stubGlobal('document', {
querySelectorAll: () => {
return []
}
})
vi.stubGlobal('fetch', refetch)
vi.stubGlobal('sessionStorage', {
getItem: (key: string) => {
return storage.get(key) ?? null
Expand Down Expand Up @@ -61,13 +92,25 @@ describe('reloadOnStaleChunk', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.clearAllMocks()
steps.length = 0
})

it('should reload once when a chunk fails to import', () => {
it('should reload once when a chunk fails to import', async () => {
failChunkImport(page)
failChunkImport(page)

await vi.waitFor(() => {
expect(reload).toHaveBeenCalledTimes(1)
})
})

it('should ask the page modules again before it reloads', async () => {
failChunkImport(page)
await vi.waitFor(() => {
expect(reload).toHaveBeenCalledTimes(1)
})

expect(reload).toHaveBeenCalledTimes(1)
expect(steps).toStrictEqual([`fetch ${PAGE_MODULE_URL}`, 'reload'])
})

it('should not reload when the import failed because the page is leaving', () => {
Expand All @@ -77,25 +120,31 @@ describe('reloadOnStaleChunk', () => {
expect(reload).not.toHaveBeenCalled()
})

it('should still reload after a client-side navigation', () => {
it('should still reload after a client-side navigation', async () => {
navigate(navigation, { sameDocument: true })
failChunkImport(page)

expect(reload).toHaveBeenCalledTimes(1)
await vi.waitFor(() => {
expect(reload).toHaveBeenCalledTimes(1)
})
})

it('should still reload after a download, which keeps the page', () => {
it('should still reload after a download, which keeps the page', async () => {
navigate(navigation, { sameDocument: false, downloadRequest: 'meme.mp4' })
failChunkImport(page)

expect(reload).toHaveBeenCalledTimes(1)
await vi.waitFor(() => {
expect(reload).toHaveBeenCalledTimes(1)
})
})

it('should reload again once the page is back from the back-forward cache', () => {
it('should reload again once the page is back from the back-forward cache', async () => {
navigate(navigation, { sameDocument: false })
restoreFromBackForwardCache(page)
failChunkImport(page)

expect(reload).toHaveBeenCalledTimes(1)
await vi.waitFor(() => {
expect(reload).toHaveBeenCalledTimes(1)
})
})
})
48 changes: 45 additions & 3 deletions src/lib/stale-chunk-reload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,40 @@ const matchLeavesTheDocument = (event: NavigateEvent) => {
return !event.destination.sameDocument && event.downloadRequest === null
}

const PAGE_MODULE_SELECTOR = 'link[rel="modulepreload"], script[type="module"]'

const readPageModuleUrls = () => {
const assetsUrl = new URL('/assets/', window.location.origin).href
const resourceUrls = performance.getEntriesByType('resource').map((entry) => {
return entry.name
})
const elementUrls = Array.from(
document.querySelectorAll<HTMLLinkElement | HTMLScriptElement>(
PAGE_MODULE_SELECTOR
),
(element) => {
return element instanceof HTMLLinkElement ? element.href : element.src
}
)

return new Set(
[...resourceUrls, ...elementUrls].filter((url) => {
return url.startsWith(assetsUrl) && url.endsWith('.js')
})
)
}

const forgetFailedPageModules = () => {
return Promise.allSettled(
Array.from(readPageModuleUrls(), (url) => {
return fetch(url)
})
)
}

export const reloadOnStaleChunk = () => {
let isImportCancelledByLeaving = false
let isReloading = false

window.navigation?.addEventListener('navigate', (event) => {
isImportCancelledByLeaving = matchLeavesTheDocument(event)
Expand All @@ -30,12 +62,22 @@ export const reloadOnStaleChunk = () => {
}
})

const reloadWithFreshModules = async () => {
isReloading = true
await forgetFailedPageModules()
writeStorageTimestamp(sessionStorage, LAST_RELOAD_STORAGE_KEY)
window.location.reload()
}

window.addEventListener('vite:preloadError', () => {
if (isImportCancelledByLeaving || matchHasReloadedRecently()) {
if (
isReloading ||
isImportCancelledByLeaving ||
matchHasReloadedRecently()
) {
return
}

writeStorageTimestamp(sessionStorage, LAST_RELOAD_STORAGE_KEY)
window.location.reload()
void reloadWithFreshModules()
})
}
Loading