Repository navigation
refactor(ui)!: let Form completely own the form-state request lifecycle - #19343
Conversation
Moves submission and its state (modified, disabled, submitted, processing, background processing, successful submit count, focus restoration) from Form into a useFormSubmission hook. Behavior is unchanged.
Gives submission cleanup a single place to run. No behavior change.
Form now makes its own getFormState requests, after field changes and after every submission request. Consumers shape the request through the new `formStateRequest` prop instead of calling getFormState from `onChange`. The `onChange` and `onSuccess` return values are no longer merged.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Merge Risk:
|
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖
Largest pathsThese visualization shows top 20 largest paths in the bundle.Meta file: packages/next/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js
Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js
DetailsNext to the size is how much the size has increased or decreased compared with the base branch of this PR.
|
The Form now derives every form-state arg it can from the document, operation and form state, and a document's main form handles locking, stale-data detection and preview URLs itself. Consumers pass only the args the Form can't know. `onChange` runs once the server state for a change is applied, which replaces `onResponse`.
onChange waited for the merged state to commit, but a nested form's transition render can stay pending while its server components load, so Lexical blocks never wrote their values back to the editor and the document never became modified.
|
|
||
| await Promise.all(validationPromises) | ||
| const submittedRef = useRef(false) | ||
| const submissionActivityRef = useRef<SubmissionActivity>({ running: 0, started: 0 }) |
| </InlineBlockContainer> | ||
| )} | ||
| </Form> | ||
| <OperationProvider operation="update"> |
There was a problem hiding this comment.
Just wrapping with the OperationProvider here
| EditButton={EditButton} | ||
| errorCount={errorCount} | ||
| formSchema={clientBlock?.fields ?? []} | ||
| <OperationProvider operation="update"> |
There was a problem hiding this comment.
Just wrapping with the OperationProvider here
|
|
||
| const { i18n, t } = useTranslation<object, string>() | ||
|
|
||
| const onChange = useCallback( |
There was a problem hiding this comment.
The onChange callback no longer needs to refresh form state, it's now completely owned by the form.
| : false | ||
| } | ||
|
|
||
| export const reduceFormStateToBlockData = (formState: FormState, currentData?: Data): Data => { |
There was a problem hiding this comment.
This utility has been moved to the ui package
|
|
||
| const prevFormState = useRef(formState) | ||
|
|
||
| const validateForm = useCallback(async () => { |
There was a problem hiding this comment.
This is now owned by the useFormState hook
| [collectionSlug, docConfig, getUploadHandler], | ||
| ) | ||
|
|
||
| const reset = useCallback( |
There was a problem hiding this comment.
This is now owned by the useFormState hook
| * Called after an edit refresh or local submit validation applies server form state, including invalid state. | ||
| * Side effects only: the return value is ignored. | ||
| */ | ||
| onChange?: ((args: { formState: FormState; submitted: boolean }) => Promise<void> | void)[] |
There was a problem hiding this comment.
The onChange no longer accepts any return value, it can only perform side effects
| name: 'password', | ||
| label: t('authentication:newPassword'), | ||
| required: true, | ||
| <OperationProvider operation="create"> |
There was a problem hiding this comment.
Just wrapping with the OperationProvider here.
| } | ||
| }, [fields, getFormState, isOpen, localeCode, widget.slug, widgetData]) | ||
|
|
||
| const onChange = useCallback( |
There was a problem hiding this comment.
The onChange callback is no longer needed here, refreshing form state is now completely owned by the form
|
|
||
| const collectionConfig = getEntityConfig({ collectionSlug: userSlug }) | ||
|
|
||
| const onChange: FormProps['onChange'][0] = React.useCallback( |
There was a problem hiding this comment.
The onChange callback is no longer needed here, refreshing form state is now completely owned by the form
| ], | ||
| ) | ||
|
|
||
| const onChange: FormProps['onChange'][0] = useCallback( |
There was a problem hiding this comment.
The onChange callback is no longer needed here, refreshing form state is now completely owned by the form
| if (id || globalSlug) { | ||
| const docPreferences = await getDocPreferences() | ||
|
|
||
| const { livePreviewURL, previewURL, state } = await getFormState({ |
There was a problem hiding this comment.
The useFormState hook's onSave now handles refreshing form state automatically
| const classes = [className, baseClass].filter(Boolean).join(' ') | ||
|
|
||
| const executeOnChange = useEffectEvent(() => { | ||
| queueTask(async () => { |
There was a problem hiding this comment.
Form state refreshes are now queued by the useFormState hook
| } | ||
| }) | ||
| for (const onChangeFn of onChange) { | ||
| Promise.resolve(onChangeFn({ formState: changedFormState, submitted: isSubmitted })).catch( |
There was a problem hiding this comment.
The form's onChange callback is now fire-and-forget, its return value is ignored and is only used to perform side effects
Requires #19425. Prerequisite for #19343. Uses `getDataFromFormState` for regular and inline Lexical blocks, replacing the separate reducer introduced in #17957. Lexical now follows the same form-state rules as the rest of the admin panel, including keeping keys with `undefined` values. ## Notable changes ### Empty arrays when unflattening Lexical and the rest of the admin panel previously handled empty arrays differently. Lexical could omit the field, while regular form data could contain its row count (`0`). This normalizes form-state behavior across Lexical and the rest of the admin panel so empty arrays come through as `[]` in both. Explicit empty arrays are now preserved during unflattening when `overwrite: false` (the default), so stale child fields can't bring deleted rows back. `overwrite: true` lets child fields populate the array: ```ts unflatten({ items: [], 'items.0.title': 'Stale' }) // { items: [] } unflatten({ items: [], 'items.0.title': 'Stale' }, { overwrite: true }) // { items: [{ title: 'Stale' }] } ``` ### disableFormData `disableFormData` no longer controls how rows are serialized and instead does what its name implies by keeping a field's value out of form submissions. `getDataFromFormState` now builds array and blocks data without needing `disableFormData` to hide the row count: ```ts getDataFromFormState( { items: { // disableFormData: true, // No longer needed to omit "value: 1" rows: [{ id: 'row-1' }], value: 1, }, 'items.0.id': { value: 'row-1' }, 'items.0.title': { value: 'Hello' }, }, true, ) // { items: [{ id: 'row-1', title: 'Hello' }] } ```
| vi.mock('../../providers/ServerFunctions/index.js', () => ({ | ||
| useServerFunctions: () => ({ getFormState: mocks.getFormState }), | ||
| })) | ||
| vi.mock('../../providers/Translation/index.js', () => ({ |
There was a problem hiding this comment.
Let's use vitest component testing for this, similar to https://github.com/payloadcms/payload/blob/main/packages/ui/src/hooks/useControllableState.spec.tsx
There was a problem hiding this comment.
I'd actually just prefer removing the unit tests in favor of e2e. Done here: 9e26447
|
🚀 This is included in version v4.0.0-beta.8 |
…19554) Release notes now show each breaking PR's `## Breaking Changes` section. They used to show the first paragraph of the commit body, which is usually the PR summary. `AGENTS.md` now asks breaking PRs to include that section. Release notes entry for #19343: ```diff * **ui:** let Form completely own the form-state request lifecycle (#19343) - Requires #19307 and #19384. + The return value of `onChange` and `onSuccess` is now ignored. They now + run only after the new server form state has been applied. Use them + strictly to perform side effects: + + ```diff + -<Form onChange={[onChange]}> + +<Form schemaPath={schemaPath}> + ``` ``` ## Changes - **Breaking change notes** - The releaser reads the text under the commit body's `## Breaking...` heading. It stops at the next H1/H2 heading or a `---` rule. - It also stops at the changed-file list that changelogen appends to each body (from `git log --name-status`). - A heading inside a code fence does not end the section. - Without the heading, the releaser uses the first paragraph and logs a warning with the commit hash. - **Agent guidance** - `AGENTS.md` asks breaking PRs to add a `## Breaking Changes` section. The section states who is affected and what to do. 🤖 Written with AI
) Requires #19343. Prerequisite for #17455. Fixes #18348. Three kinds of requests talk to the server while you edit a document: - Form-state refresh — you typed, so the server recalculates things like conditional field visibility, row labels, computed values, and new server components - Autosave — debounced background draft saves - Explicit save — you clicked Save or Publish (or cmd + s) Before this PR, these ran on separate tracks and could overlap, so responses could land out of order and a save could start before an earlier server update had merged in. This PR puts all three into one track, so that it can effectively manage traffic across all three types of requests. So now: - Only one request runs at a time - Only one request can be pending while the running request executes - The pending slot is ranked: explicit save > autosave > form-state refresh. If a more important request arrives, whatever was pending gets thrown away ## Breaking Changes The `useQueue` hook existed prior to this PR, but it's now instantiated once for all request types within the form. Custom components that call `queueTask` directly need to pass the task as an option. Task errors are no longer caught and logged by the queue; they reject the returned promise, so handle them at the call site: ```diff const { queueTask } = useQueue() - queueTask(async () => { - await fetch('/api/posts') - }) + queueTask({ + task: async () => { + await fetch('/api/posts') + }, + }).catch((err) => { + console.error(err) + }) ``` The `queueTask` method now accepts a `priority` and returns either a `completed` result or a `superseded` status: ```ts const { queueTask } = useQueue() const loadPosts = async () => { const result = await queueTask({ priority: 0, // Lower numbers take precedence task: async () => { const response = await fetch('/api/posts') return response.json() }, }) if (result.status === 'completed') { return result.value } } ``` This hook is also now marked as internal. ## Background For context, #13416 moved autosave execution through the same submit flow as regular submits, so that server hook changes are reflected in form state. But form-state refreshes still ran through a separate queue, allowing responses to merge out of order or saves to start before an earlier form-state response had merged.
Follow up to #19343, #19203, and #19649. Rejects stale form responses using form revisions instead of per-field `isModified` tracking. Autosave and form-state responses could overwrite newer edits or validation state when the user continued editing during a request. With a fast autosave interval on a throttled network, inputs could freeze to a partial value while typing quickly. ## Root Cause 1. A request starts with revision A. 2. The user continues editing, producing revision B while the request is in flight. 3. The response for revision A returns after those edits. 4. The shared queue orders requests, but ordering alone does not prevent that response from applying stale state. The per-field `isModified` flag only protects the most recently edited field. ## Fix Tracks the form revision for each request and rejects response-driven updates invalidated by newer edits, form replacement, or unmounting. Server-computed values are accepted while the response is current. Completed explicit saves still retain their metadata and newly created document identity when newer edits prevent accepting their field values. Huge win: this removes the per-field `isModified` flag introduced in #13460. Staleness is handled consistently across fields and form requests. ## References Resolves: - Closes #17676 - Closes #17517 - Closes #18638 - Closes #18425 - Closes #19368 - Closes #15226 - Closes #19797 - Closes #19842 Fixed by earlier PRs in this stack: - #18348 — fixed by #19203. Preserves edits made while a queued autosave is in flight. - #12368 — fixed by #19649. Preserves block types and content after server-side reordering. Stack: 1. #19307 — extracts form submission into `useFormSubmission`. 2. #19384 — extracts form state into `useFormState`. 3. #19425 — renames shared form-state data utilities. 4. #19423 — consolidates Lexical form-state reduction. 5. #19343 — moves the form-state request lifecycle into `Form`. 6. #19203 — puts form-state refreshes, autosaves, and explicit saves on one queue. 7. #19649 — reconciles array and block rows after server-side reordering. 8. #19736 — preserves Lexical link drawers and nested media pickers when autosave returns updated link fields. 9. #17455 — rejects stale responses and removes per-field `isModified` tracking. Previous work related to these issues: - #13416 — moves autosave into the shared form submission flow so server hook changes are reflected in the UI. - #13438 — protects local edits made while autosave is pending. - #13460 — introduces the per-field `isModified` flag that this PR replaces. - #10268 — adds support for accepting server-computed field values after manual saves. - #12956 — generates slugs on demand; depended on #13416 to reflect computed values. ### For the reviewer Most changed lines are in `test/`. Start with the sequencing and submission lifecycle in: - `packages/ui/src/forms/Form/useFormState.ts` - `packages/ui/src/forms/Form/useFormSubmission.tsx` - `packages/ui/src/hooks/useQueue.ts` - `packages/ui/src/forms/Form/index.tsx` Also review autosave recovery in `packages/ui/src/elements/Autosave/index.tsx`. <!-- e2e-pr-media:start --> ### Before https://github.com/user-attachments/assets/9a1ed7c2-7784-4d20-ae98-8d6063a5c6cd ### After https://github.com/user-attachments/assets/1621e1ee-55df-4e29-87b8-7b9fe68e307f <!-- e2e-pr-media:end -->
Requires #19307 and #19384.
Prerequisite for #19203 and #17455.
Moves all form-state request handling into the
Formcomponent via the newuseFormStatehook. It now orchestrates the entire form state lifecycle viauseFormState, instead of splitting that responbility with its caller:Previously, callers had to fetch and return server state themselves via the
onChangecallback:But the
onChangecallback should not be responsible for returning form state mutations. This is an anti-pattern. It should only be used to perform side-effects, when applicable. Expecting it to tie into thegetFormStateserver function is far too much overhead to have to configure at each callsite.Now,
Formentirely handles requests and cancellation from just the schema path:For historical context, it was initial designed this way so that the
Formcomponent wasn't so heavily tied to internal Payload patterns. The original hope was thatFormcould be used as an agnostic form library, e.g. implemented outside the admin panel. That led to far too abstract APIs that introduced a level of complexity that doesn't scale.Breaking Changes
The return value of
onChangeandonSuccessis now ignored. They now run only after the new server form state has been applied. Use them strictly to perform side effects: