Unverified Commit ccd76c96 authored by Jude Gao's avatar Jude Gao Committed by GitHub

feat: useLinkStatus (#77300)

# `useLinkStatus` Hook

The `useLinkStatus` hook is primarily useful when:

- Links have `prefetch={false}` set
- Navigation occurs before prefetching has completed
- When React decides to [skip the loading
state](https://react.dev/reference/react/useTransition#preventing-unwanted-loading-indicators)
and https://github.com/vercel/next.js/issues/69625

It provides loading state feedback during these navigation transitions,
preventing pages from appearing "frozen" while new content loads.

## Usage

`useLinkStatus` can be called from any descendant component of `Link`
and it returns `{ pending: true }` before history has updated. After the
URL updates, it returns `{ pending: false }`.

```jsx
// When prefetching is disabled
<Link href="/dashboard/reports" prefetch={false}>
  Reports <LoadingIndicator />
</Link>

function LoadingIndicator() {
  const { pending } = useLinkStatus();
  return pending ? <Spinner /> : null;
}
```

## Notes

- If the link has been prefetched, pending change will be skipped and
remain `{ pending: false }`.
- If `useLinkStatus` is not under any `Link`, it will always return `{
pending: false }`.
- `useLinkStatus` currently does not support Pages Router, so it will
always return `{ pending: false }` in Pages Router.
- When you click multiple links in a short period, only the last link's
pending state is shown

---------
Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent 8f68d038
......@@ -16,7 +16,10 @@ import {
hasUnsupportedSubmitterAttributes,
type FormProps,
} from '../form-shared'
import { mountLinkInstance, unmountLinkInstance } from '../components/links'
import {
mountFormInstance,
unmountPrefetchableInstance,
} from '../components/links'
export type { FormProps }
......@@ -96,10 +99,10 @@ export default function Form({
const observeFormVisibilityOnMount = useCallback(
(element: HTMLFormElement) => {
if (isPrefetchEnabled && router !== null) {
mountLinkInstance(element, actionProp, router, PrefetchKind.AUTO)
mountFormInstance(element, actionProp, router, PrefetchKind.AUTO)
}
return () => {
unmountLinkInstance(element)
unmountPrefetchableInstance(element)
}
},
[isPrefetchEnabled, actionProp, router]
......
'use client'
import type { NextRouter } from '../../shared/lib/router/router'
import React from 'react'
import React, { createContext, useContext, useOptimistic, useRef } from 'react'
import type { UrlObject } from 'url'
import { formatUrl } from '../../shared/lib/router/utils/format-url'
import { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { PrefetchKind } from '../components/router-reducer/router-reducer-types'
import { useMergedRef } from '../use-merged-ref'
import { isAbsoluteUrl } from '../../shared/lib/utils'
import { addBasePath } from '../add-base-path'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import type { PENDING_LINK_STATUS } from '../components/links'
import {
IDLE_LINK_STATUS,
mountLinkInstance,
onNavigationIntent,
unmountLinkInstance,
unmountLinkForCurrentNavigation,
unmountPrefetchableInstance,
type LinkInstance,
} from '../components/links'
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { dispatchNavigateAction } from '../components/app-router-instance'
type Url = string | UrlObject
type RequiredKeys<T> = {
......@@ -228,11 +230,10 @@ function isModifiedEvent(event: React.MouseEvent): boolean {
function linkClicked(
e: React.MouseEvent,
router: NextRouter | AppRouterInstance,
href: string,
as: string,
linkInstanceRef: React.RefObject<LinkInstance | null>,
replace?: boolean,
shallow?: boolean,
scroll?: boolean,
onNavigate?: OnNavigateEventHandler
): void {
......@@ -278,20 +279,12 @@ function linkClicked(
}
}
// If the router is an NextRouter instance it will have `beforePopState`
// TODO: This should access the router methods directly, rather than
// go through the public interface.
const routerScroll = scroll ?? true
if ('beforePopState' in router) {
router[replace ? 'replace' : 'push'](href, as, {
shallow,
scroll: routerScroll,
})
} else {
router[replace ? 'replace' : 'push'](as || href, {
scroll: routerScroll,
})
}
dispatchNavigateAction(
as || href,
replace ? 'replace' : 'push',
scroll ?? true,
linkInstanceRef.current
)
}
React.startTransition(navigate)
......@@ -321,8 +314,12 @@ export default function LinkComponent(
ref: React.Ref<HTMLAnchorElement>
}
) {
const [linkStatus, setOptimisticLinkStatus] = useOptimistic(IDLE_LINK_STATUS)
let children: React.ReactNode
const linkInstanceRef = useRef<LinkInstance | null>(null)
const {
href: hrefProp,
as: asProp,
......@@ -557,14 +554,26 @@ export default function LinkComponent(
// a revalidation or refresh.
const observeLinkVisibilityOnMount = React.useCallback(
(element: HTMLAnchorElement | SVGAElement) => {
if (prefetchEnabled && router !== null) {
mountLinkInstance(element, href, router, appPrefetchKind)
if (router !== null) {
linkInstanceRef.current = mountLinkInstance(
element,
href,
router,
appPrefetchKind,
prefetchEnabled,
setOptimisticLinkStatus
)
}
return () => {
unmountLinkInstance(element)
if (linkInstanceRef.current) {
unmountLinkForCurrentNavigation(linkInstanceRef.current)
linkInstanceRef.current = null
}
unmountPrefetchableInstance(element)
}
},
[prefetchEnabled, href, router, appPrefetchKind]
[prefetchEnabled, href, router, appPrefetchKind, setOptimisticLinkStatus]
)
const mergedRef = useMergedRef(observeLinkVisibilityOnMount, childRef)
......@@ -606,7 +615,7 @@ export default function LinkComponent(
return
}
linkClicked(e, router, href, as, replace, shallow, scroll, onNavigate)
linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate)
},
onMouseEnter(e) {
if (!legacyBehavior && typeof onMouseEnterProp === 'function') {
......@@ -671,6 +680,8 @@ export default function LinkComponent(
childProps.href = addBasePath(as)
}
let link: React.ReactNode
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
console.error(
......@@ -680,12 +691,26 @@ export default function LinkComponent(
'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'
)
}
return React.cloneElement(child, childProps)
link = React.cloneElement(child, childProps)
} else {
link = (
<a {...restProps} {...childProps}>
{children}
</a>
)
}
return (
<a {...restProps} {...childProps}>
{children}
</a>
<LinkStatusContext.Provider value={linkStatus}>
{link}
</LinkStatusContext.Provider>
)
}
const LinkStatusContext = createContext<
typeof PENDING_LINK_STATUS | typeof IDLE_LINK_STATUS
>(IDLE_LINK_STATUS)
export const useLinkStatus = () => {
return useContext(LinkStatusContext)
}
......@@ -24,6 +24,7 @@ import type {
NavigateOptions,
PrefetchOptions,
} from '../../shared/lib/app-router-context.shared-runtime'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
export type DispatchStatePromise = React.Dispatch<ReducerState>
......@@ -235,10 +236,11 @@ function getAppRouterActionQueue(): AppRouterActionQueue {
return globalActionQueue
}
function dispatchNavigateAction(
export function dispatchNavigateAction(
href: string,
navigateType: NavigateAction['navigateType'],
shouldScroll: boolean
shouldScroll: boolean,
linkInstanceRef: LinkInstance | null
): void {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
......@@ -246,6 +248,9 @@ function dispatchNavigateAction(
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
setLinkForCurrentNavigation(linkInstanceRef)
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
......@@ -298,12 +303,12 @@ export const publicAppRouterInstance: AppRouterInstance = {
},
replace: (href: string, options?: NavigateOptions) => {
startTransition(() => {
dispatchNavigateAction(href, 'replace', options?.scroll ?? true)
dispatchNavigateAction(href, 'replace', options?.scroll ?? true, null)
})
},
push: (href: string, options?: NavigateOptions) => {
startTransition(() => {
dispatchNavigateAction(href, 'push', options?.scroll ?? true)
dispatchNavigateAction(href, 'push', options?.scroll ?? true, null)
})
},
refresh: () => {
......
......@@ -12,13 +12,17 @@ import {
cancelPrefetchTask,
bumpPrefetchTask,
} from './segment-cache'
import { startTransition } from 'react'
type LinkElement = HTMLAnchorElement | SVGAElement | HTMLFormElement
type LinkElement = HTMLAnchorElement | SVGAElement
type LinkInstance = {
type Element = LinkElement | HTMLFormElement
// Properties that are shared between Link and Form instances. We use the same
// shape for both to prevent a polymorphic de-opt in the VM.
type LinkOrFormInstanceShared = {
router: AppRouterInstance
kind: PrefetchKind.AUTO | PrefetchKind.FULL
prefetchHref: string
isVisible: boolean
wasHoveredOrTouched: boolean
......@@ -33,16 +37,68 @@ type LinkInstance = {
cacheVersion: number
}
export type FormInstance = LinkOrFormInstanceShared & {
prefetchHref: string
setOptimisticLinkStatus: null
}
type PrefetchableLinkInstance = LinkOrFormInstanceShared & {
prefetchHref: string
setOptimisticLinkStatus: (status: { pending: boolean }) => void
}
type NonPrefetchableLinkInstance = LinkOrFormInstanceShared & {
prefetchHref: null
setOptimisticLinkStatus: (status: { pending: boolean }) => void
}
type PrefetchableInstance = PrefetchableLinkInstance | FormInstance
export type LinkInstance =
| PrefetchableLinkInstance
| NonPrefetchableLinkInstance
// Tracks the most recently navigated link instance. When null, indicates
// the current navigation was not initiated by a link click.
let linkForMostRecentNavigation: LinkInstance | null = null
// Status object indicating link is pending
export const PENDING_LINK_STATUS = { pending: true }
// Status object indicating link is idle
export const IDLE_LINK_STATUS = { pending: false }
// Updates the loading state when navigating between links
// - Resets the previous link's loading state
// - Sets the new link's loading state
// - Updates tracking of current navigation
export function setLinkForCurrentNavigation(link: LinkInstance | null) {
startTransition(() => {
linkForMostRecentNavigation?.setOptimisticLinkStatus(IDLE_LINK_STATUS)
link?.setOptimisticLinkStatus(PENDING_LINK_STATUS)
linkForMostRecentNavigation = link
})
}
// Unmounts the current link instance from navigation tracking
export function unmountLinkForCurrentNavigation(link: LinkInstance) {
if (linkForMostRecentNavigation === link) {
linkForMostRecentNavigation = null
}
}
// Use a WeakMap to associate a Link instance with its DOM element. This is
// used by the IntersectionObserver to track the link's visibility.
const links: WeakMap<LinkElement, LinkInstance> | Map<Element, LinkInstance> =
const prefetchable:
| WeakMap<Element, PrefetchableInstance>
| Map<Element, PrefetchableInstance> =
typeof WeakMap === 'function' ? new WeakMap() : new Map()
// A Set of the currently visible links. We re-prefetch visible links after a
// cache invalidation, or when the current URL changes. It's a separate data
// structure from the WeakMap above because only the visible links need to
// be enumerated.
const visibleLinks: Set<LinkInstance> = new Set()
const prefetchableAndVisible: Set<PrefetchableInstance> = new Set()
// A single IntersectionObserver instance shared by all <Link> components.
const observer: IntersectionObserver | null =
......@@ -52,20 +108,24 @@ const observer: IntersectionObserver | null =
})
: null
export function mountLinkInstance(
element: LinkElement,
href: string,
router: AppRouterInstance,
kind: PrefetchKind.AUTO | PrefetchKind.FULL
) {
let prefetchUrl: URL | null = null
function observeVisibility(element: Element, instance: PrefetchableInstance) {
const existingInstance = prefetchable.get(element)
if (existingInstance !== undefined) {
// This shouldn't happen because each <Link> component should have its own
// anchor tag instance, but it's defensive coding to avoid a memory leak in
// case there's a logical error somewhere else.
unmountPrefetchableInstance(element)
}
// Only track prefetchable links that have a valid prefetch URL
prefetchable.set(element, instance)
if (observer !== null) {
observer.observe(element)
}
}
function coercePrefetchableUrl(href: string): URL | null {
try {
prefetchUrl = createPrefetchURL(href)
if (prefetchUrl === null) {
// We only track the link if it's prefetchable. For example, this excludes
// links to external URLs.
return
}
return createPrefetchURL(href)
} catch {
// createPrefetchURL sometimes throws an error if an invalid URL is
// provided, though I'm not sure if it's actually necessary.
......@@ -77,36 +137,84 @@ export function mountLinkInstance(
reportErrorFn(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
return
return null
}
}
const instance: LinkInstance = {
prefetchHref: prefetchUrl.href,
export function mountLinkInstance(
element: LinkElement,
href: string,
router: AppRouterInstance,
kind: PrefetchKind.AUTO | PrefetchKind.FULL,
prefetchEnabled: boolean,
setOptimisticLinkStatus: (status: { pending: boolean }) => void
): LinkInstance {
if (prefetchEnabled) {
const prefetchURL = coercePrefetchableUrl(href)
if (prefetchURL !== null) {
const instance: PrefetchableLinkInstance = {
router,
kind,
isVisible: false,
wasHoveredOrTouched: false,
prefetchTask: null,
cacheVersion: -1,
prefetchHref: prefetchURL.href,
setOptimisticLinkStatus,
}
// We only observe the link's visibility if it's prefetchable. For
// example, this excludes links to external URLs.
observeVisibility(element, instance)
return instance
}
}
// If the link is not prefetchable, we still create an instance so we can
// track its optimistic state (i.e. useLinkStatus).
const instance: NonPrefetchableLinkInstance = {
router,
kind,
isVisible: false,
wasHoveredOrTouched: false,
prefetchTask: null,
cacheVersion: -1,
prefetchHref: null,
setOptimisticLinkStatus,
}
const existingInstance = links.get(element)
if (existingInstance !== undefined) {
// This shouldn't happen because each <Link> component should have its own
// anchor tag instance, but it's defensive coding to avoid a memory leak in
// case there's a logical error somewhere else.
unmountLinkInstance(element)
return instance
}
export function mountFormInstance(
element: HTMLFormElement,
href: string,
router: AppRouterInstance,
kind: PrefetchKind.AUTO | PrefetchKind.FULL
): void {
const prefetchURL = coercePrefetchableUrl(href)
if (prefetchURL === null) {
// This href is not prefetchable, so we don't track it.
// TODO: We currently observe/unobserve a form every time its href changes.
// For Links, this isn't a big deal because the href doesn't usually change,
// but for forms it's extremely common. We should optimize this.
return
}
links.set(element, instance)
if (observer !== null) {
observer.observe(element)
const instance: FormInstance = {
router,
kind,
isVisible: false,
wasHoveredOrTouched: false,
prefetchTask: null,
cacheVersion: -1,
prefetchHref: prefetchURL.href,
setOptimisticLinkStatus: null,
}
observeVisibility(element, instance)
}
export function unmountLinkInstance(element: LinkElement) {
const instance = links.get(element)
export function unmountPrefetchableInstance(element: Element) {
const instance = prefetchable.get(element)
if (instance !== undefined) {
links.delete(element)
visibleLinks.delete(instance)
prefetchable.delete(element)
prefetchableAndVisible.delete(instance)
const prefetchTask = instance.prefetchTask
if (prefetchTask !== null) {
cancelPrefetchTask(prefetchTask)
......@@ -127,10 +235,7 @@ function handleIntersect(entries: Array<IntersectionObserverEntry>) {
}
}
export function onLinkVisibilityChanged(
element: LinkElement,
isVisible: boolean
) {
export function onLinkVisibilityChanged(element: Element, isVisible: boolean) {
if (process.env.NODE_ENV !== 'production') {
// Prefetching on viewport is disabled in development for performance
// reasons, because it requires compiling the target page.
......@@ -138,22 +243,22 @@ export function onLinkVisibilityChanged(
return
}
const instance = links.get(element)
const instance = prefetchable.get(element)
if (instance === undefined) {
return
}
instance.isVisible = isVisible
if (isVisible) {
visibleLinks.add(instance)
prefetchableAndVisible.add(instance)
} else {
visibleLinks.delete(instance)
prefetchableAndVisible.delete(instance)
}
rescheduleLinkPrefetch(instance)
}
export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
const instance = links.get(element)
const instance = prefetchable.get(element)
if (instance === undefined) {
return
}
......@@ -164,7 +269,7 @@ export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
}
}
function rescheduleLinkPrefetch(instance: LinkInstance) {
function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
const existingPrefetchTask = instance.prefetchTask
if (!instance.isVisible) {
......@@ -230,7 +335,7 @@ export function pingVisibleLinks(
// may affect the result of a prefetch task. It's also called after a
// cache invalidation.
const currentCacheVersion = getCurrentCacheVersion()
for (const instance of visibleLinks) {
for (const instance of prefetchableAndVisible) {
const task = instance.prefetchTask
if (
task !== null &&
......@@ -261,7 +366,7 @@ export function pingVisibleLinks(
}
}
function prefetchWithOldCacheImplementation(instance: LinkInstance) {
function prefetchWithOldCacheImplementation(instance: PrefetchableInstance) {
// This is the path used when the Segment Cache is not enabled.
if (typeof window === 'undefined') {
return
......
......@@ -5,7 +5,7 @@ import type {
PrefetchOptions as RouterPrefetchOptions,
} from '../shared/lib/router/router'
import React from 'react'
import React, { createContext, useContext } from 'react'
import type { UrlObject } from 'url'
import { resolveHref } from './resolve-href'
import { isLocalURL } from '../shared/lib/router/utils/is-local-url'
......@@ -686,4 +686,17 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
}
)
const LinkStatusContext = createContext<{
pending: boolean
}>({
// We do not support link status in the Pages Router, so we always return false
pending: false,
})
export const useLinkStatus = () => {
// This behaviour is like React's useFormStatus. When the component is not under
// a <form> tag, it will get the default value, instead of throwing an error.
return useContext(LinkStatusContext)
}
export default Link
'use client'
import { useSearchParams } from 'next/navigation'
export default function DebugMode() {
const searchParams = useSearchParams()
const debug = searchParams.get('debug')
if (debug === '1') {
return (
<div data-testid="debug-mode">
<h2>Debug Mode Enabled</h2>
</div>
)
}
return null
}
import React, { Suspense } from 'react'
import NavBar from './nav-bar'
import DebugMode from './debug-mode'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<NavBar />
{children}
<Suspense>
<DebugMode />
</Suspense>
</body>
</html>
)
}
export const dynamic = 'force-dynamic'
'use client'
import React from 'react'
import Link from 'next/link'
import { useLinkStatus } from 'next/link'
import { navigateByServerAction } from './server-action'
import { useRouter } from 'next/navigation'
export default function NavBar() {
const postIds = Array.from({ length: 5 }, (_, i) => i + 1)
const router = useRouter()
return (
<nav data-testid="navbar">
<ul style={{ display: 'flex', listStyle: 'none', gap: '10px' }}>
<li>
<Link
prefetch={false}
href="/"
id="home-link"
data-testid="home-link"
>
Home <LoadingIndicator id="home" />
</Link>
<button
id="server-action-home-btn"
data-testid="server-action-home-btn"
onClick={() => navigateByServerAction(`/`)}
>
Navigate by server action to home
</button>
</li>
{postIds.map((id) => (
<li key={id}>
<Link
prefetch={false}
href={`/post/${id}`}
id={`post-${id}-link`}
data-testid={`post-${id}-link`}
>
Post {id} <LoadingIndicator id={`post-${id}`} />
</Link>
<button
id={`server-action-${id}-btn`}
data-testid={`server-action-${id}-btn`}
onClick={() => navigateByServerAction(`/post/${id}`)}
>
Navigate by server action to {id}
</button>
<button
id={`router-push-${id}-btn`}
data-testid={`router-push-${id}-btn`}
onClick={() => router.push(`/post/${id}`)}
>
Navigate by Router.push to {id}
</button>
</li>
))}
<button
id="enable-debug-btn"
data-testid="enable-debug-btn"
onClick={() => {
const urlSearchParams = new URLSearchParams(window.location.search)
urlSearchParams.set('debug', '1')
window.history.pushState(null, '', `?${urlSearchParams.toString()}`)
}}
>
Enable Debug Mode
</button>
<button
id="disable-debug-btn"
data-testid="disable-debug-btn"
onClick={() => {
const urlSearchParams = new URLSearchParams(window.location.search)
urlSearchParams.delete('debug')
window.history.pushState(null, '', `?${urlSearchParams.toString()}`)
}}
>
Disable Debug Mode
</button>
<LinkThatChangesHref />
</ul>
</nav>
)
}
const LoadingIndicator = ({ id }: { id: string }) => {
const { pending } = useLinkStatus()
if (pending) {
return (
<div id={`${id}-loading`} data-testid={`${id}-loading`}>
(Loading)
</div>
)
}
return null
}
const LinkThatChangesHref = () => {
const [postId, setPostId] = React.useState(6)
return (
<div>
<Link href={`/post/${postId}`} data-testid="changing-link">
Link to post {postId} <LoadingIndicator id={`post-${postId}`} />
</Link>
<button
onClick={() => setPostId(postId + 1)}
data-testid="increment-link-btn"
>
Change link target
</button>
</div>
)
}
import React from 'react'
export default function HomePage() {
return (
<div data-testid="home-page">
<h1>Home Page</h1>
</div>
)
}
// This component delays rendering to simulate a slow page load
async function PostContent({ id }: { id: string }) {
await new Promise((resolve) => setTimeout(resolve, 3000))
return (
<div>
<h1>Post {id}</h1>
<p>This is post {id}</p>
<p>Posted on: {Date.now()}</p>
</div>
)
}
export default async function PostPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return (
<div data-testid={`post-${id}-page`}>
<PostContent id={id} />
</div>
)
}
'use server'
import { redirect } from 'next/navigation'
export async function navigateByServerAction(url: string) {
redirect(url)
}
import { nextTestSetup } from 'e2e-utils'
import { waitFor } from 'next-test-utils'
describe('useLinkStatus', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should show pending state for the last link clicked when clicking multiple links in a row', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Quickly click post 2 link
await browser.elementById('post-2-link').click()
// The pending state should be shown for post 2 link
expect(await browser.elementById('post-2-loading').text()).toBe('(Loading)')
// Post 1 should not show loading
const post1Loading = await browser.elementsByCss('#post-1-loading')
expect(post1Loading.length).toBe(0)
// Wait for navigation to complete and verify we end up on post 2
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-2-page"]')
})
it('should remove pending state after shallow routing', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Verify pending state is shown
expect(await browser.elementById('post-1-loading').text()).toBe('(Loading)')
// Trigger shallow routing by clicking debug mode button
await browser.elementById('enable-debug-btn').click()
// Pending state should be gone
const post1LoadingElements = await browser.elementsByCss('#post-1-loading')
expect(post1LoadingElements.length).toBe(0)
})
it('should remove pending state after browser back navigation', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Wait for navigation to complete
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-1-page"]')
// Click post 2 link
await browser.elementById('post-2-link').click()
// Verify pending state is shown
expect(await browser.elementById('post-2-loading').text()).toBe('(Loading)')
// Go back using browser back button
await browser.back()
// Wait for navigation and verify we're back on home
// We should be on home because page 2 has not been fully loaded yet when we navigated back
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="home-link"]')
// Pending state should be gone
const post2LoadingElements = await browser.elementsByCss('#post-2-loading')
expect(post2LoadingElements.length).toBe(0)
})
it('should show pending state when navigating to the same path', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Wait for navigation to complete
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-1-page"]')
// Click post 1 link again
await browser.elementById('post-1-link').click()
// Verify pending state is shown even though it's the same path
expect(await browser.elementById('post-1-loading').text()).toBe('(Loading)')
// Wait for navigation to complete and verify we're still on post 1
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-1-page"]')
})
it('should remove pending state when navigation starts by router.push', async () => {
const browser = await next.browser('/')
// Click post 1 link
await browser.elementById('post-1-link').click()
// Verify pending state is shown
expect(await browser.elementById('post-1-loading').text()).toBe('(Loading)')
// Click router push button for post 2
await browser.elementById('router-push-2-btn').click()
// Pending state for post 1 should be gone
const post1Loading = await browser.elementsByCss('#post-1-loading')
expect(post1Loading.length).toBe(0)
// Wait for navigation to complete and verify we end up on post 2
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-2-page"]')
})
it('should remove pending state when server action triggers a redirect', async () => {
const browser = await next.browser('/post/1')
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="post-1-page"]')
// Click post 2 link
await browser.elementById('post-2-link').click()
// Verify pending state is shown
expect(await browser.elementById('post-2-loading').text()).toBe('(Loading)')
// Click server action button for home
await browser.elementById('server-action-home-btn').click()
await waitFor(1000) // buffer for server action to return a redirect
// Pending state for post 2 should be gone
const post2Loading = await browser.elementsByCss('#post-2-loading')
expect(post2Loading.length).toBe(0)
// Wait for navigation to complete and verify we end up on home
await browser.waitForIdleNetwork()
await browser.waitForElementByCss('[data-testid="home-link"]')
})
})
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