Unverified Commit 7bce97d6 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[experiment] Add useOffline hook to expose offline state to userland (#92012)

**Previous:**

1. https://github.com/vercel/next.js/pull/92011

**Current:**

2. (this PR)

---

Adds a `useOffline()` hook exported from `next/navigation` that returns
`true` when the app is offline. The state is owned by a provider
component rendered in the app router, using `useState` + `useOptimistic`
so the value can update even during blocked transitions (e.g., a
navigation that's waiting for connectivity).

Gated behind `experimental.useOffline`.
parent 1e73fa94
export { useOffline } from './dist/client/components/use-offline'
module.exports = require('./dist/client/components/use-offline')
......@@ -39,6 +39,8 @@
"image.d.ts",
"link.js",
"link.d.ts",
"offline.js",
"offline.d.ts",
"form.js",
"form.d.ts",
"router.js",
......
......@@ -536,6 +536,12 @@ function Router({
)
}
if (process.env.__NEXT_USE_OFFLINE) {
const { OfflineProvider } =
require('./use-offline') as typeof import('./use-offline')
content = <OfflineProvider>{content}</OfflineProvider>
}
return (
<>
<HistoryUpdater appRouterState={state} />
......
......@@ -33,6 +33,7 @@ const CONNECTIVITY_CHECK_TIMEOUT_MS = 200
import { pingPrefetchScheduler } from './segment-cache/scheduler'
import { RSC_HEADER } from './app-router-headers'
import { dispatchOfflineChange } from './use-offline'
export type OfflineState = {
promise: Promise<void>
......@@ -89,6 +90,7 @@ function notifyOffline(): OfflineState {
timeoutHandle: null,
backoffStep: 0,
}
dispatchOfflineChange(true)
checkConnectivity(offlineState)
return offlineState
}
......@@ -108,6 +110,7 @@ export function notifyOnline(): void {
const resolve = offlineState.resolve
offlineState = null
resolve()
dispatchOfflineChange(false)
pingPrefetchScheduler()
}
......
'use client'
import React, {
createContext,
useContext,
useState,
useOptimistic,
startTransition,
} from 'react'
const OfflineContext = createContext<boolean>(false)
// Module-level reference to the optimistic setter. Assigned inside the
// provider component on every render. Called by the offline module
// (via dispatchOfflineChange) to update the React tree.
let setOptimistic: ((value: boolean) => void) | null = null
let setCanonical: ((value: boolean) => void) | null = null
/**
* Called by the offline module when the offline state changes.
* Dispatches into React via startTransition + useOptimistic.
*/
export function dispatchOfflineChange(isOffline: boolean): void {
const canonical = setCanonical
const optimistic = setOptimistic
if (canonical === null || optimistic === null) {
return
}
startTransition(() => {
canonical(isOffline)
optimistic(isOffline)
})
}
export function OfflineProvider({ children }: { children: React.ReactNode }) {
const [canonicalOffline, setCanonicalOffline] = useState(false)
const [isOffline, setOptimisticOffline] = useOptimistic(canonicalOffline)
setOptimistic = setOptimisticOffline
setCanonical = setCanonicalOffline
return (
<OfflineContext.Provider value={isOffline}>
{children}
</OfflineContext.Provider>
)
}
/**
* Returns whether the app is currently offline.
* Returns `false` during SSR and hydration.
*/
export function useOffline(): boolean {
return useContext(OfflineContext)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { OfflineStatus } from '../../components/offline-status'
export default async function DestinationPage() {
async function DynamicContent() {
await connection()
return <div id="destination-content">Destination page content</div>
return <div id="destination-dynamic">Dynamic data loaded</div>
}
export default function DestinationPage() {
return (
<div id="destination-content">
<h1>Destination page</h1>
<Suspense
fallback={
<div id="destination-loading">
Waiting for data... <OfflineStatus />
</div>
}
>
<DynamicContent />
</Suspense>
</div>
)
}
import { Suspense } from 'react'
import { OfflineStatus } from '../components/offline-status'
export default function RootLayout({
children,
......@@ -8,9 +8,8 @@ export default function RootLayout({
return (
<html>
<body>
<Suspense fallback={<div id="loading">Loading...</div>}>
{children}
</Suspense>
<OfflineStatus />
{children}
</body>
</html>
)
......
'use client'
import { useOffline } from 'next/offline'
export function OfflineStatus() {
const isOffline = useOffline()
return <div id="offline-status">{isOffline ? 'offline' : 'online'}</div>
}
......@@ -2,8 +2,13 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
useOffline: true,
varyParams: true,
optimisticRouting: true,
cachedNavigations: true,
prefetchInlining: true,
},
}
......
......@@ -3,7 +3,7 @@ import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
describe('useOffline - retry behavior', () => {
describe('useOffline', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
......@@ -33,10 +33,11 @@ describe('useOffline - retry behavior', () => {
},
})
// Verify we're on the home page
// Verify we're on the home page and online
expect(await browser.elementById('home').text()).toContain('Home')
expect(await browser.elementById('offline-status').text()).toBe('online')
// Prefetch the target link
// Prefetch the destination link
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/destination"]'
......@@ -44,27 +45,118 @@ describe('useOffline - retry behavior', () => {
await toggle.click()
})
// Go offline, then click the link.
// Go offline, then click the link. The prefetched static shell should
// render immediately (from the cache), but the dynamic content behind
// the Suspense boundary won't load.
await goOffline(page!)
const link = await browser.elementByCss('a[href="/destination"]')
await link.click()
// The navigation is stuck in a pending transition — React keeps showing
// the current page. The target content should not be visible.
// The destination page's static shell renders from the prefetch cache.
await retry(async () => {
expect(await browser.elementById('destination-content').text()).toContain(
'Destination page'
)
})
// The Suspense fallback is visible and shows the offline indicator.
expect(await browser.elementById('destination-loading').text()).toContain(
'Waiting for data...'
)
// useOffline() returns true in both the layout and the Suspense fallback.
expect(await browser.elementById('offline-status').text()).toBe('offline')
expect(await browser.elementById('destination-loading').text()).toContain(
'offline'
)
// The dynamic content hasn't loaded yet.
expect(await browser.hasElementByCssSelector('#destination-dynamic')).toBe(
false
)
// Restore connectivity. The dynamic content should stream in.
await goOnline(page!)
await retry(async () => {
expect(await browser.elementById('destination-dynamic').text()).toBe(
'Dynamic data loaded'
)
})
// useOffline() should return false after reconnection
expect(await browser.elementById('offline-status').text()).toBe('online')
})
it('shows offline indicator even without prefetch data', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
expect(await browser.elementById('home').text()).toContain('Home')
expect(await browser.elementById('offline-status').text()).toBe('online')
// Go offline BEFORE revealing the link — no prefetch will happen.
await goOffline(page!)
// Reveal the link and click it. Both the prefetch and the navigation
// fetch will fail since we're offline.
const toggle = await browser.elementByCss(
'input[data-link-accordion="/destination"]'
)
await toggle.click()
const link = await browser.elementByCss('a[href="/destination"]')
await link.click()
// The optimistic update should still surface the offline state even
// though the navigation is stuck in a pending transition with no
// cached data at all.
await retry(async () => {
expect(await browser.elementById('offline-status').text()).toBe('offline')
})
expect(await browser.hasElementByCssSelector('#destination-content')).toBe(
false
)
expect(await browser.elementById('home').text()).toContain('Home')
// Restore connectivity. The retry loop should detect this and
// complete the navigation.
// Restore connectivity. Navigation should complete.
await goOnline(page!)
await retry(async () => {
expect(await browser.elementById('destination-content').text()).toBe(
'Destination page content'
expect(await browser.elementById('destination-dynamic').text()).toBe(
'Dynamic data loaded'
)
})
expect(await browser.elementById('offline-status').text()).toBe('online')
})
it('updates offline indicator immediately on disconnect', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
expect(await browser.elementById('offline-status').text()).toBe('online')
// Disconnect without performing any navigation. The offline event
// should flip useOffline() to true immediately.
await goOffline(page!)
await retry(async () => {
expect(await browser.elementById('offline-status').text()).toBe('offline')
})
// Reconnect. The online event triggers a connectivity check, and
// useOffline() should flip back to false.
await goOnline(page!)
await retry(async () => {
expect(await browser.elementById('offline-status').text()).toBe('online')
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment