Unverified Commit f08fcd4b authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[form] pages dir support (#68333)

This PR adds support for using Form with pages dir. The functionality is
a bit limited:
- in pages dir, Form doesn't prefetch, because there's no notion of an
instant loading state that we could prefetch
- No support for server actions
- pending indicators from `useFormStatus` do not work while navigating
to the target page (planning to address this in
https://github.com/vercel/next.js/pull/70681)


But other than those things, Form should work. Both of these patterns
are supported:
- `<Form action="/foo/bar">`
- `<Form action={clientAction}>` (if using a react version with
`useActionState`)
parent b7875464
'use client' 'use client'
import { useEffect, type HTMLProps, type FormEvent } from 'react' import { useEffect, type HTMLProps, type FormEvent, useContext } from 'react'
import { useRouter } from './components/navigation'
import { addBasePath } from './add-base-path' import { addBasePath } from './add-base-path'
import { useIntersection } from './use-intersection' import { useIntersection } from './use-intersection'
import { useMergedRef } from './use-merged-ref' import { useMergedRef } from './use-merged-ref'
import type { AppRouterInstance } from '../shared/lib/app-router-context.shared-runtime' import {
AppRouterContext,
type AppRouterInstance,
} from '../shared/lib/app-router-context.shared-runtime'
import { PrefetchKind } from './components/router-reducer/router-reducer-types' import { PrefetchKind } from './components/router-reducer/router-reducer-types'
import { RouterContext } from '../shared/lib/router-context.shared-runtime'
import type { NextRouter } from './router'
const DISALLOWED_FORM_PROPS = ['method', 'encType', 'target'] as const const DISALLOWED_FORM_PROPS = ['method', 'encType', 'target'] as const
...@@ -30,6 +34,8 @@ type InternalFormProps = { ...@@ -30,6 +34,8 @@ type InternalFormProps = {
* - `null` (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data. * - `null` (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - `false`: This will not prefetch any data. * - `false`: This will not prefetch any data.
* *
* In pages dir, prefetching is not supported, and passing this prop will emit a warning.
*
* @defaultValue `null` * @defaultValue `null`
*/ */
prefetch?: false | null prefetch?: false | null
...@@ -57,21 +63,63 @@ export type FormProps<RouteInferType = any> = InternalFormProps ...@@ -57,21 +63,63 @@ export type FormProps<RouteInferType = any> = InternalFormProps
export default function Form({ export default function Form({
replace, replace,
scroll, scroll,
prefetch: prefetchProp = null, prefetch: prefetchProp,
ref: externalRef, ref: externalRef,
...props ...props
}: FormProps) { }: FormProps) {
const router = useAppOrPagesRouter()
const actionProp = props.action const actionProp = props.action
const isNavigatingForm = typeof actionProp === 'string' const isNavigatingForm = typeof actionProp === 'string'
// Validate `action`
if (process.env.NODE_ENV === 'development') {
if (isNavigatingForm) {
checkActionUrl(actionProp, 'action')
}
}
// Validate `prefetch`
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
if (!(prefetchProp === false || prefetchProp === null)) { if (
!(
prefetchProp === undefined ||
prefetchProp === false ||
prefetchProp === null
)
) {
console.error('The `prefetch` prop of <Form> must be `false` or `null`') console.error('The `prefetch` prop of <Form> must be `false` or `null`')
} }
if (prefetchProp !== undefined) {
if (!isAppRouter(router)) {
console.error(
'Passing `prefetch` to a <Form> has no effect in the pages directory.'
)
} else if (!isNavigatingForm) {
console.error(
'Passing `prefetch` to a <Form> whose `action` is a function has no effect.'
)
}
}
} }
const prefetch = const prefetch =
prefetchProp === false || prefetchProp === null ? prefetchProp : null prefetchProp === false || prefetchProp === null ? prefetchProp : null
// Validate `scroll` and `replace`
if (process.env.NODE_ENV === 'development') {
if (!isNavigatingForm && (replace !== undefined || scroll !== undefined)) {
console.error(
'Passing `replace` or `scroll` to a <Form> whose `action` is a function has no effect.\n' +
'See the relevant docs to learn how to control this behavior for navigations triggered from actions:\n' +
' `redirect()` - https://nextjs.org/docs/app/api-reference/functions/redirect#parameters\n' +
' `router.replace()` - https://nextjs.org/docs/app/api-reference/functions/use-router#userouter\n'
)
}
}
// Clean up any unsupported form props (and warn if present)
for (const key of DISALLOWED_FORM_PROPS) { for (const key of DISALLOWED_FORM_PROPS) {
if (key in props) { if (key in props) {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
...@@ -87,11 +135,16 @@ export default function Form({ ...@@ -87,11 +135,16 @@ export default function Form({
} }
} }
const router = useRouter() const isPrefetchEnabled =
// there is no notion of instant loading states in pages dir, so prefetching is pointless
isAppRouter(router) &&
// if we don't have an action path, we can't preload anything anyway.
isNavigatingForm &&
prefetch === null
const [setIntersectionRef, isVisible] = useIntersection({ const [setIntersectionRef, isVisible] = useIntersection({
rootMargin: '200px', rootMargin: '200px',
disabled: !isNavigatingForm, // if we don't have an action path, we can't preload anything anyway. disabled: !isPrefetchEnabled,
}) })
const ownRef = useMergedRef<HTMLFormElement>( const ownRef = useMergedRef<HTMLFormElement>(
...@@ -100,12 +153,6 @@ export default function Form({ ...@@ -100,12 +153,6 @@ export default function Form({
) )
useEffect(() => { useEffect(() => {
if (!isNavigatingForm) {
return
}
const isPrefetchEnabled = prefetch === null
if (!isVisible || !isPrefetchEnabled) { if (!isVisible || !isPrefetchEnabled) {
return return
} }
...@@ -116,30 +163,12 @@ export default function Form({ ...@@ -116,30 +163,12 @@ export default function Form({
} catch (err) { } catch (err) {
console.error(err) console.error(err)
} }
}, [isNavigatingForm, isVisible, actionProp, prefetch, router]) }, [isPrefetchEnabled, isVisible, actionProp, prefetch, router])
if (!isNavigatingForm) { if (!isNavigatingForm) {
if (process.env.NODE_ENV === 'development') {
if (replace !== undefined || scroll !== undefined) {
console.error(
'Passing `replace` or `scroll` to a <Form> whose `action` is a function has no effect.\n' +
'See the relevant docs to learn how to control this behavior for navigations triggered from actions:\n' +
' `redirect()` - https://nextjs.org/docs/app/api-reference/functions/redirect#parameters\n' +
' `router.replace()` - https://nextjs.org/docs/app/api-reference/functions/use-router#userouter\n'
)
}
if (prefetchProp !== undefined) {
console.error(
'Passing `prefetch` to a <Form> whose `action` is a function has no effect.'
)
}
}
return <form {...props} ref={ownRef} /> return <form {...props} ref={ownRef} />
} }
if (process.env.NODE_ENV === 'development') {
checkActionUrl(actionProp, 'action')
}
const actionHref = addBasePath(actionProp) const actionHref = addBasePath(actionProp)
return ( return (
...@@ -173,7 +202,7 @@ function onFormSubmit( ...@@ -173,7 +202,7 @@ function onFormSubmit(
onSubmit: FormProps['onSubmit'] onSubmit: FormProps['onSubmit']
replace: FormProps['replace'] replace: FormProps['replace']
scroll: FormProps['scroll'] scroll: FormProps['scroll']
router: AppRouterInstance router: SomeRouter
} }
) { ) {
if (typeof onSubmit === 'function') { if (typeof onSubmit === 'function') {
...@@ -273,7 +302,37 @@ function onFormSubmit( ...@@ -273,7 +302,37 @@ function onFormSubmit(
event.preventDefault() event.preventDefault()
const method = replace ? 'replace' : 'push' const method = replace ? 'replace' : 'push'
router[method](targetUrl.href, { scroll }) const targetHref = targetUrl.href
if (isAppRouter(router)) {
router[method](targetHref, { scroll })
} else {
// TODO(form): Make this use a transition so that pending states work
//
// Unlike the app router, pages router doesn't use startTransition,
// and can't easily be wrapped in one because of implementation details
// (e.g. it doesn't use any react state)
// But it's important to have this wrapped in a transition because
// pending states from e.g. `useFormStatus` rely on that.
// So this needs some follow up work.
router[method](targetHref, undefined, { scroll })
}
}
type SomeRouter = AppRouterInstance | NextRouter
function isAppRouter(router: SomeRouter): router is AppRouterInstance {
return !('asPath' in router)
}
function useAppOrPagesRouter(): SomeRouter {
const pagesRouter = useContext(RouterContext)
const appRouter = useContext(AppRouterContext)
if (pagesRouter) {
return pagesRouter
} else {
// We're in the app directory if there is no pages router.
return appRouter!
}
} }
function checkActionUrl(action: string, source: 'action' | 'formAction') { function checkActionUrl(action: string, source: 'action' | 'formAction') {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { BrowserInterface } from '../../../../lib/next-webdriver' import { BrowserInterface } from '../../../../lib/next-webdriver'
describe('app dir - form', () => { const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
describe.each(['app', 'pages'])('%s dir - form', (type) => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
it('should soft-navigate on submit and show the prefetched loading state', async () => { const isAppDir = type === 'app'
const session = await next.browser('/forms/basic') const pathPrefix = isAppDir ? '' : '/pages-dir'
const navigationTracker = await trackMpaNavs(session)
const searchInput = await session.elementByCss('input[name="query"]') it(
await searchInput.fill('my search') 'should soft-navigate on submit' +
(isAppDir ? ' and show the prefetched loading state' : ''),
async () => {
const session = await next.browser(pathPrefix + '/forms/basic')
const navigationTracker = await trackMpaNavs(session)
const submitButton = await session.elementByCss('[type="submit"]') const searchInput = await session.elementByCss('input[name="query"]')
await submitButton.click() await searchInput.fill('my search')
// we should have prefetched a loading state, so it should be displayed const submitButton = await session.elementByCss('[type="submit"]')
await session.waitForElementByCss('#loading') await submitButton.click()
const result = await session.waitForElementByCss('#search-results').text() if (isAppDir) {
expect(result).toMatch(/query: "my search"/) // we should have prefetched a loading state, so it should be displayed
await session.waitForElementByCss('#loading')
}
expect(await navigationTracker.didMpaNavigate()).toBe(false) const result = await session.waitForElementByCss('#search-results').text()
}) expect(result).toMatch(/query: "my search"/)
expect(await navigationTracker.didMpaNavigate()).toBe(false)
}
)
it('should soft-navigate to the formAction url of the submitter', async () => { it('should soft-navigate to the formAction url of the submitter', async () => {
const session = await next.browser('/forms/button-formaction') const session = await next.browser(pathPrefix + '/forms/button-formaction')
const navigationTracker = await trackMpaNavs(session) const navigationTracker = await trackMpaNavs(session)
const searchInput = await session.elementByCss('input[name="query"]') const searchInput = await session.elementByCss('input[name="query"]')
...@@ -45,22 +56,27 @@ describe('app dir - form', () => { ...@@ -45,22 +56,27 @@ describe('app dir - form', () => {
expect(await navigationTracker.didMpaNavigate()).toBe(false) expect(await navigationTracker.didMpaNavigate()).toBe(false)
}) })
describe('functions passed to action', () => { // `<form action={someFunction}>` is only supported in React 19.x
;(isReact18 ? describe.skip : describe)('functions passed to action', () => {
it.each([ it.each([
{ {
name: 'client action', name: 'client action',
path: '/forms/with-function/action-client', path: '/forms/with-function/action-client',
}, },
{ ...(isAppDir
name: 'server action', ? [
path: '/forms/with-function/action-server', {
}, name: 'server action',
{ path: '/forms/with-function/action-server',
name: 'server action (closure)', },
path: '/forms/with-function/action-server-closure', {
}, name: 'server action (closure)',
path: '/forms/with-function/action-server-closure',
},
]
: []),
])('runs $name', async ({ path }) => { ])('runs $name', async ({ path }) => {
const session = await next.browser(path) const session = await next.browser(pathPrefix + path)
const navigationTracker = await trackMpaNavs(session) // actions should not MPA-navigate either. const navigationTracker = await trackMpaNavs(session) // actions should not MPA-navigate either.
const searchInput = await session.elementByCss('input[name="query"]') const searchInput = await session.elementByCss('input[name="query"]')
...@@ -78,51 +94,61 @@ describe('app dir - form', () => { ...@@ -78,51 +94,61 @@ describe('app dir - form', () => {
}) })
}) })
describe('functions passed to formAction', () => { // `<button formAction={someFunction}>` is only supported in React 19.x
it.each([ ;(isReact18 ? describe.skip : describe)(
{ 'functions passed to formAction',
name: 'client action', () => {
path: '/forms/with-function/button-formaction-client', it.each([
}, {
{ // TODO(lubieowoce): figure out why the client navigation is failing in pages dir
name: 'server action', // (see "pages-dir/forms/with-function/button-formaction-client/index.tsx" for more)
path: '/forms/with-function/button-formaction-server', name: 'client action',
}, path: '/forms/with-function/button-formaction-client',
{ },
name: 'server action (closure)', ...(isAppDir
path: '/forms/with-function/button-formaction-server-closure', ? [
}, {
])( name: 'server action',
"runs $name from submitter and doesn't warn about unsupported attributes", path: '/forms/with-function/button-formaction-server',
async ({ path }) => { },
const session = await next.browser(path) {
const navigationTracker = await trackMpaNavs(session) // actions should not MPA-navigate either. name: 'server action (closure)',
path: '/forms/with-function/button-formaction-server-closure',
const searchInput = await session.elementByCss('input[name="query"]') },
await searchInput.fill('will not be a search') ]
: []),
const submitButton = await session.elementByCss('[type="submit"]') ])(
await submitButton.click() "runs $name from submitter and doesn't warn about unsupported attributes",
async ({ path }) => {
const result = await session const session = await next.browser(pathPrefix + path)
.waitForElementByCss('#redirected-results') const navigationTracker = await trackMpaNavs(session) // actions should not MPA-navigate either.
.text()
expect(result).toMatch(/query: "will not be a search"/) const searchInput = await session.elementByCss('input[name="query"]')
await searchInput.fill('will not be a search')
expect(await navigationTracker.didMpaNavigate()).toBe(false)
const submitButton = await session.elementByCss('[type="submit"]')
if (isNextDev) { await submitButton.click()
const logs = (await session.log()).map((item) => item.message)
const result = await session
expect(logs).not.toContainEqual( .waitForElementByCss('#redirected-results')
expect.stringMatching( .text()
/<Form>'s `.+?` was set to an unsupported value/ expect(result).toMatch(/query: "will not be a search"/)
expect(await navigationTracker.didMpaNavigate()).toBe(false)
if (isNextDev) {
const logs = (await session.log()).map((item) => item.message)
expect(logs).not.toContainEqual(
expect.stringMatching(
/<Form>'s `.+?` was set to an unsupported value/
)
) )
) }
} }
} )
) }
}) )
describe('unsupported attributes on submitter', () => { describe('unsupported attributes on submitter', () => {
it.each([ it.each([
...@@ -133,7 +159,8 @@ describe('app dir - form', () => { ...@@ -133,7 +159,8 @@ describe('app dir - form', () => {
'should warn if submitter sets "$name" to an unsupported value and fall back to default submit behavior', 'should warn if submitter sets "$name" to an unsupported value and fall back to default submit behavior',
async ({ name: attributeName, baseName: attributeBaseName }) => { async ({ name: attributeName, baseName: attributeBaseName }) => {
const session = await next.browser( const session = await next.browser(
`/forms/button-formaction-unsupported?attribute=${attributeName}` pathPrefix +
`/forms/button-formaction-unsupported?attribute=${attributeName}`
) )
const submitButton = await session.elementByCss('[type="submit"]') const submitButton = await session.elementByCss('[type="submit"]')
...@@ -173,7 +200,7 @@ describe('app dir - form', () => { ...@@ -173,7 +200,7 @@ describe('app dir - form', () => {
}) })
it('does not push a new history entry if `replace` is passed', async () => { it('does not push a new history entry if `replace` is passed', async () => {
const session = await next.browser(`/forms/with-replace`) const session = await next.browser(pathPrefix + `/forms/with-replace`)
const navigationTracker = await trackMpaNavs(session) const navigationTracker = await trackMpaNavs(session)
// apparently this is usually not 1...? // apparently this is usually not 1...?
...@@ -189,7 +216,9 @@ describe('app dir - form', () => { ...@@ -189,7 +216,9 @@ describe('app dir - form', () => {
}) })
it('does not navigate if preventDefault is called in onSubmit', async () => { it('does not navigate if preventDefault is called in onSubmit', async () => {
const session = await next.browser(`/forms/with-onsubmit-preventdefault`) const session = await next.browser(
pathPrefix + `/forms/with-onsubmit-preventdefault`
)
const submitButton = await session.elementByCss('[type="submit"]') const submitButton = await session.elementByCss('[type="submit"]')
await submitButton.click() await submitButton.click()
...@@ -198,12 +227,12 @@ describe('app dir - form', () => { ...@@ -198,12 +227,12 @@ describe('app dir - form', () => {
await session.waitForElementByCss('#redirected-results') await session.waitForElementByCss('#redirected-results')
expect(new URL(await session.url()).pathname).toEqual( expect(new URL(await session.url()).pathname).toEqual(
'/redirected-from-action' pathPrefix + '/redirected-from-action'
) )
}) })
it('url-encodes file inputs, but warns about them', async () => { it('url-encodes file inputs, but warns about them', async () => {
const session = await next.browser(`/forms/with-file-input`) const session = await next.browser(pathPrefix + `/forms/with-file-input`)
const fileInputSelector = 'input[type="file"]' const fileInputSelector = 'input[type="file"]'
// Fake a file to upload // Fake a file to upload
......
import * as React from 'react'
import Form from 'next/form'
export default function Home() {
return (
<Form action="/pages-dir/search" id="search-form">
<input name="query" />
<button type="submit">Submit</button>
</Form>
)
}
'use client'
import * as React from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'
export default function Home() {
const searchParams = useRouter().query
const attribute = searchParams.attribute as string | undefined
return (
<div
onSubmit={(e) => {
// should fire if the form let the event bubble up
if (e.defaultPrevented) {
console.log('incorrect: default submit behavior was prevented')
} else {
console.log('correct: default submit behavior was not prevented')
e.preventDefault() // this submission will do something stupid, we don't want it to actually go through.
}
}}
>
<Form action="/pages-dir/search" id="search-form">
<input name="query" />
<button
type="submit"
formAction="/pages-dir/search"
formEncType={
attribute === 'formEncType' ? 'multipart/form-data' : undefined
}
formMethod={attribute === 'formMethod' ? 'post' : undefined}
formTarget={attribute === 'formTarget' ? 'bloop' : undefined}
>
Submit
</button>
</Form>
</div>
)
}
import * as React from 'react'
import Form from 'next/form'
export default function Home() {
return (
<Form action="/pages-dir/" id="search-form">
<input name="query" />
<button type="submit" formAction="/pages-dir/search">
Submit
</button>
</Form>
)
}
import * as React from 'react'
import Form from 'next/form'
export default function Home() {
return (
<Form action="/pages-dir/search" id="search-form">
<input name="query" type="text" />
<input name="file" type="file" />
<button type="submit">Submit</button>
</Form>
)
}
'use client'
import * as React from 'react'
import { useActionState, useState } from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'
export default function Page() {
const destination = '/pages-dir/redirected-from-action'
const router = useRouter()
const [, dispatch] = useActionState(() => {
const to = destination + '?' + new URLSearchParams({ query })
router.push(to)
}, undefined)
const [query, setQuery] = useState('')
return (
<Form action={dispatch} id="search-form">
<input
name="query"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button type="submit">Submit (client action)</button>
</Form>
)
}
'use client'
import * as React from 'react'
import { type ComponentProps, useActionState, useState } from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'
export default function Page() {
const destination = '/pages-dir/redirected-from-action'
const [query, setQuery] = useState('')
return (
<Form action="/pages-dir/search" id="search-form">
<input
name="query"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<NavigateButton to={destination + '?' + new URLSearchParams({ query })}>
Submit (client action)
</NavigateButton>
</Form>
)
}
function NavigateButton({
to,
...props
}: { to: string } & ComponentProps<'button'>) {
const router = useRouter()
const [, dispatch] = useActionState(() => {
router.push(to)
}, undefined)
return <button type="submit" formAction={dispatch} {...props} />
}
'use client'
import * as React from 'react'
import Form from 'next/form'
import { useRouter } from 'next/router'
export default function Home() {
const router = useRouter()
return (
<Form
action="/pages-dir/search"
id="search-form"
onSubmit={(e) => {
e.preventDefault()
// `preventDefault()` should stop <Form> from running its navigation logic.
// if it doesn't (which'd be a bug), <Form> would call a `router.push` after this,
// and the last push wins, so this would be ignored.
router.push('/pages-dir/redirected-from-action')
}}
>
<input name="query" />
<button type="submit">Submit</button>
</Form>
)
}
import * as React from 'react'
import Form from 'next/form'
export default function Home() {
return (
<Form action="/pages-dir/search" replace id="search-form">
<input name="query" />
<button type="submit">Submit</button>
</Form>
)
}
import * as React from 'react'
export async function getServerSideProps({ req }) {
return {
props: {
searchParams: Object.fromEntries(
new URL(req.url, 'http://n').searchParams.entries()
),
},
}
}
export default function RedirectedPage({ searchParams }) {
const query = searchParams.query as string
return <div id="redirected-results">query: {JSON.stringify(query)}</div>
}
import * as React from 'react'
export async function getServerSideProps({ req }) {
await sleep(1000)
return {
props: {
searchParams: Object.fromEntries(
new URL(req.url, 'http://n').searchParams.entries()
),
},
}
}
export default function SearchPage({ searchParams }) {
const query = searchParams.query as string
return <div id="search-results">query: {JSON.stringify(query)}</div>
}
function sleep(ms: number) {
return new Promise<void>((res) => setTimeout(res, ms))
}
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