Skip to content

refactor(ui)!: let Form completely own the form-state request lifecycle - #19343

Merged
jacobsfletch merged 36 commits into
mainfrom
refactor/form-owned-form-state
Nov 10, 2026
Merged

jacobsfletch merged 36 commits into
mainfrom
refactor/form-owned-form-state

Conversation

@jacobsfletch

@jacobsfletch jacobsfletch commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Requires #19307 and #19384.

Prerequisite for #19203 and #17455.

Moves all form-state request handling into the Form component via the new useFormState hook. It now orchestrates the entire form state lifecycle via useFormState, instead of splitting that responbility with its caller:

Previously, callers had to fetch and return server state themselves via the onChange callback:

const { getFormState } = useServerFunctions()
const abortControllerRef = useRef<AbortController>(null)

const onChange = useCallback(async ({ formState }) => {
  abortControllerRef.current?.abort()
  const controller = new AbortController()
  abortControllerRef.current = controller

  const { state } = await getFormState({
    // ...request context, permissions, preferences
    formState,
    schemaPath,
    signal: controller.signal,
  })

  return state ?? formState
}, [/* ...dependencies */])

<Form onChange={[onChange]} />

But the onChange callback 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 the getFormState server function is far too much overhead to have to configure at each callsite.

Now, Form entirely handles requests and cancellation from just the schema path:

<Form schemaPath={schemaPath} />

For historical context, it was initial designed this way so that the Form component wasn't so heavily tied to internal Payload patterns. The original hope was that Form could 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 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:

-const onChange = async ({ formState, submitted }) => {
-  const { state } = await getFormState({
-    collectionSlug,
-    docPermissions,
-    docPreferences: await getDocPreferences(),
-    formState,
-    operation: 'update',
-    schemaPath,
-    signal: controller.signal,
-    skipValidation: !submitted,
-  })
-
-  return state
-}

-<Form onChange={[onChange]}>
+<Form schemaPath={schemaPath}>

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.
@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The PR moves form-state refresh, validation, and post-save updates into shared form hooks. It updates UI and Lexical form integrations, adds a shared reducer for converting form state to data, and documents the revised Form behavior.

Changes: Shared Form lifecycle

Layer / File(s) Summary
Form contract and context
packages/ui/src/forms/Form/types.ts, packages/ui/src/forms/Form/initContextState.ts, packages/ui/src/forms/Form/index.tsx, packages/ui/src/providers/DocumentInfo/*, packages/ui/src/providers/DocumentInfo/useGetDocPermissions.tsx, packages/ui/src/utilities/buildFormState.ts
Form callbacks no longer return replacement form state. Form context tracks submission state, and Form connects state refresh and submission hooks. DocumentInfo exposes stale status, and permission retrieval returns the permissions it loads.
Form state and submission lifecycle
packages/ui/src/forms/Form/useFormState.ts, packages/ui/src/forms/Form/useFormSubmission.tsx
The hooks handle refresh, reset, validation, submission tracking, and post-save refresh. Local submissions can request server validation. Successful saves refresh form state before onSuccess; refresh failures are reported separately.
UI form integrations
packages/ui/src/elements/BulkUpload/*, packages/ui/src/elements/EditMany/DrawerContent.tsx, packages/ui/src/elements/FieldSelect/index.tsx, packages/ui/src/fields/Join/index.tsx, packages/ui/src/views/CreateFirstUser/index.client.tsx, packages/ui/src/views/Dashboard/Default/ModularDashboard/WidgetConfigDrawer.tsx, packages/ui/src/views/Edit/index.tsx
Bulk edit, registration, widget, and document edit forms remove local form-state refresh callbacks. Edit-many field selection updates selection directly, and the edit view uses shared stale state.
Data reduction and Lexical forms
packages/ui/src/utilities/reduceFormStateToData.ts, packages/ui/src/exports/shared/index.ts, packages/richtext-lexical/src/features/blocks/client/*, packages/richtext-lexical/src/utilities/fieldsDrawer/DrawerContent.tsx, test/lexical/collections/Lexical/*, test/lexical/payload-types.ts
The shared reducer converts row-based form state to data and is used by Lexical forms and cached-state comparison. Lexical tests cover server-required and conditionally displayed fields, and array and null conversion cases.
Migration guidance
docs/migration-guide/v4.mdx
The guide describes which forms make server form-state requests, callback and validation behavior, and post-save refresh behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Form
  participant useFormSubmission
  participant useFormState
  participant getFormState
  participant SaveAction
  Form->>useFormSubmission: submit form
  useFormSubmission->>useFormState: validate fields and data
  useFormState->>getFormState: request server validation when required
  getFormState-->>useFormState: return validated form state
  useFormState-->>useFormSubmission: return validated fields and data
  useFormSubmission->>SaveAction: save validated data
  SaveAction-->>useFormSubmission: return save result
  useFormSubmission->>useFormState: refresh after successful save
  useFormState->>getFormState: request refreshed form state
  getFormState-->>useFormState: return refreshed form state
  useFormSubmission->>Form: invoke onSuccess
Loading

Possibly related issues

  • payloadcms/payload#19385 — The PR moves form-state requests and cancellation into Form, overlapping with the issue’s abort and validation interaction.
  • payloadcms/payload#18907 — The PR changes child Form request handling and update timing, but save-snapshot coordination remains a separate requirement.
  • payloadcms/payload#18425 — The PR changes form-state request and cancellation handling, overlapping with the stale-response lifecycle described in the issue.
  • payloadcms/payload#19368 — The PR changes form request handling and post-save refresh, but the value-merge requirement remains distinct.

Suggested reviewers: alessiogr, jarrodmflesch, r1tsuu

Merge Risk: Moderate · previous review 28b47

Editing during validation or a post-save refresh can interrupt the request, potentially failing a local submission or leaving saved server values unapplied. Resolve that lifecycle conflict before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Title check Passed The title clearly describes the move of form-state request handling into Form.
Description check Passed The description explains the form-state lifecycle change and its callback API changes.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 3 functions across 28 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches

Generate docstrings

  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖

Meta File Out File Size (raw) Note
packages/next/meta_index.json esbuild/index.js 279.40 KB ✅ No change
packages/payload/meta_index.json esbuild/index.js 1.98 MB ✅ No change
packages/payload/meta_shared.json esbuild/exports/shared.js 547.32 KB ✅ No change
packages/richtext-lexical/meta_client.json esbuild/exports/client_optimized/index.js 302.50 KB ✅ -598 B (-0.2%)
packages/ui/meta_client.json esbuild/exports/client_optimized/index.js 1.39 MB ⚠️ +3.02 KB (+0.2%)
packages/ui/meta_shared.json esbuild/exports/shared_optimized/index.js 19.46 KB ✅ No change
Largest paths These visualization shows top 20 largest paths in the bundle.

Meta file: packages/next/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████████████▋ }}}$ 98.7%, 272.71 KB
dist/adapters/router.js ${{\color{Goldenrod}{ }}}$ 0.4%, 1.00 KB
dist/adapters/server.js ${{\color{Goldenrod}{ }}}$ 0.2%, 533 B
dist/adapters/layout.js ${{\color{Goldenrod}{ }}}$ 0.2%, 529 B
dist/adapters/views.js ${{\color{Goldenrod}{ }}}$ 0.2%, 469 B
dist/adapters/UnmountWhenHidden ${{\color{Goldenrod}{ }}}$ 0.2%, 449 B
dist/utilities/initAdminContext.js ${{\color{Goldenrod}{ }}}$ 0.1%, 366 B
dist/utilities/selectiveCache.js ${{\color{Goldenrod}{ }}}$ 0.1%, 263 B
dist/esbuildEntry.js ${{\color{Goldenrod}{ }}}$ 0.0%, 0 B

Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████▊ }}}$ 67.3%, 1.33 MB
dist/collections/operations ${{\color{Goldenrod}{ ▉ }}}$ 3.5%, 68.26 KB
dist/fields/hooks ${{\color{Goldenrod}{ ▋ }}}$ 2.5%, 48.41 KB
dist/uploads/fileVersioning ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 22.32 KB
dist/globals/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 19.12 KB
dist/auth/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 18.06 KB
dist/utilities/configToJSONSchema.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 16.17 KB
dist/queues/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 14.33 KB
dist/fields/config ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 13.78 KB
dist/utilities/telemetry ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 12.73 KB
dist/uploads/generateFileData.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 12.31 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 12.21 KB
dist/uploads/transformers ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 12.18 KB
dist/uploads/transformState ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 10.81 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 10.33 KB
dist/cli/commands ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 9.93 KB
dist/config/orderable ${{\color{Goldenrod}{ }}}$ 0.4%, 8.78 KB
dist/uploads/fetchAPI-multipart ${{\color{Goldenrod}{ }}}$ 0.4%, 8.39 KB
dist/config/sanitize.js ${{\color{Goldenrod}{ }}}$ 0.4%, 8.28 KB
dist/database/migrations ${{\color{Goldenrod}{ }}}$ 0.4%, 8.16 KB
(other) ${{\color{Goldenrod}{ ████████▏ }}}$ 32.7%, 644.58 KB

Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js

Path Size
../../node_modules ${{\color{Goldenrod}{ █████████████████████▉ }}}$ 87.7%, 475.32 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 10.30 KB
dist/fields/config ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 5.83 KB
dist/utilities/traverseFields.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 4.34 KB
dist/utilities/deepCopyObject.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.52 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.46 KB
dist/config/orderable ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 3.13 KB
dist/fields/baseFields ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 2.79 KB
dist/config/client.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 2.62 KB
dist/utilities/getDateOnlyComparison.js ${{\color{Goldenrod}{ }}}$ 0.4%, 2.41 KB
dist/auth/cookies.js ${{\color{Goldenrod}{ }}}$ 0.3%, 1.55 KB
dist/utilities/flattenTopLevelFields.js ${{\color{Goldenrod}{ }}}$ 0.3%, 1.42 KB
dist/utilities/getVersionsConfig.js ${{\color{Goldenrod}{ }}}$ 0.2%, 1.04 KB
dist/globals/config ${{\color{Goldenrod}{ }}}$ 0.2%, 957 B
dist/utilities/unflatten.js ${{\color{Goldenrod}{ }}}$ 0.2%, 938 B
dist/uploads/generatePayloadFileURL.js ${{\color{Goldenrod}{ }}}$ 0.2%, 864 B
dist/auth/extractJWT.js ${{\color{Goldenrod}{ }}}$ 0.1%, 807 B
dist/utilities/flattenAllFields.js ${{\color{Goldenrod}{ }}}$ 0.1%, 798 B
dist/errors/ValidationError.js ${{\color{Goldenrod}{ }}}$ 0.1%, 772 B
dist/utilities/sanitizeUserDataForEmail.js ${{\color{Goldenrod}{ }}}$ 0.1%, 713 B
(other) ${{\color{Goldenrod}{ ███ }}}$ 12.3%, 66.93 KB

Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/features/blocks ${{\color{Goldenrod}{ ███▌ }}}$ 14.2%, 42.45 KB
dist/lexical/plugins ${{\color{Goldenrod}{ ███ }}}$ 12.4%, 37.19 KB
dist/lexical/ui ${{\color{Goldenrod}{ ██▊ }}}$ 11.2%, 33.66 KB
dist/features/table ${{\color{Goldenrod}{ ██▎ }}}$ 9.3%, 27.80 KB
dist/features/toolbars ${{\color{Goldenrod}{ █▊ }}}$ 7.4%, 22.25 KB
dist/features/link ${{\color{Goldenrod}{ █▌ }}}$ 6.2%, 18.61 KB
dist/features/upload ${{\color{Goldenrod}{ █▏ }}}$ 4.7%, 14.03 KB
dist/features/textState ${{\color{Goldenrod}{ ▉ }}}$ 3.7%, 11.08 KB
dist/lexical/utils ${{\color{Goldenrod}{ ▊ }}}$ 3.3%, 10.01 KB
dist/features/relationship ${{\color{Goldenrod}{ ▊ }}}$ 3.1%, 9.32 KB
dist/features/converters ${{\color{Goldenrod}{ ▋ }}}$ 2.8%, 8.44 KB
dist/utilities/fieldsDrawer ${{\color{Goldenrod}{ ▋ }}}$ 2.8%, 8.31 KB
dist/features/debug ${{\color{Goldenrod}{ ▋ }}}$ 2.5%, 7.40 KB
dist/lexical/config ${{\color{Goldenrod}{ ▍ }}}$ 1.7%, 5.14 KB
dist/features/indent ${{\color{Goldenrod}{ ▎ }}}$ 1.4%, 4.16 KB
dist/features/lists ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 3.67 KB
dist/lexical/LexicalEditor.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.33 KB
dist/features/horizontalRule ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.29 KB
dist/features/format ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.28 KB
dist/field/Field.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 3.06 KB
(other) ${{\color{Goldenrod}{ █████████████████████▍ }}}$ 85.8%, 256.85 KB

Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ███████▏ }}}$ 28.7%, 394.56 KB
dist/elements/Hierarchy ${{\color{Goldenrod}{ ▉ }}}$ 3.6%, 49.27 KB
dist/views/Version ${{\color{Goldenrod}{ ▌ }}}$ 2.2%, 30.52 KB
dist/elements/BulkUpload ${{\color{Goldenrod}{ ▌ }}}$ 2.2%, 29.90 KB
dist/elements/Table ${{\color{Goldenrod}{ ▌ }}}$ 2.1%, 29.56 KB
dist/forms/Form ${{\color{Goldenrod}{ ▍ }}}$ 1.7%, 24.03 KB
dist/views/Dashboard ${{\color{Goldenrod}{ ▍ }}}$ 1.7%, 23.77 KB
dist/views/HierarchyList ${{\color{Goldenrod}{ ▍ }}}$ 1.6%, 21.50 KB
dist/views/Edit ${{\color{Goldenrod}{ ▍ }}}$ 1.5%, 20.36 KB
dist/elements/WhereBuilder ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 18.54 KB
dist/providers/Auth ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 17.40 KB
dist/fields/Relationship ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 17.10 KB
dist/fields/Blocks ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 16.73 KB
dist/fields/Upload ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 15.41 KB
dist/elements/Popup ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 14.51 KB
dist/widgets/Activity ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 14.12 KB
dist/views/List ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.71 KB
dist/elements/ReactSelect ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.28 KB
dist/elements/PublishButton ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 12.16 KB
dist/elements/QueryPresets ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 12.09 KB
(other) ${{\color{Goldenrod}{ █████████████████▊ }}}$ 71.3%, 981.28 KB

Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js

Path Size
dist/graphics/Logo ${{\color{Goldenrod}{ ███████▍ }}}$ 29.9%, 5.61 KB
../../node_modules ${{\color{Goldenrod}{ ███▌ }}}$ 14.1%, 2.65 KB
dist/graphics/Icon ${{\color{Goldenrod}{ ██ }}}$ 8.1%, 1.51 KB
dist/utilities/formatDocTitle ${{\color{Goldenrod}{ █▊ }}}$ 7.0%, 1.32 KB
dist/providers/TableColumns ${{\color{Goldenrod}{ █▏ }}}$ 4.6%, 866 B
dist/utilities/getGlobalData.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 762 B
dist/utilities/api.js ${{\color{Goldenrod}{ █ }}}$ 4.0%, 756 B
dist/utilities/groupNavItems.js ${{\color{Goldenrod}{ █ }}}$ 4.0%, 745 B
dist/utilities/traverseForLocalizedFields.js ${{\color{Goldenrod}{ ▊ }}}$ 3.0%, 570 B
dist/elements/Translation ${{\color{Goldenrod}{ ▋ }}}$ 2.6%, 493 B
dist/forms/Form ${{\color{Goldenrod}{ ▋ }}}$ 2.5%, 474 B
dist/utilities/handleTakeOver.js ${{\color{Goldenrod}{ ▌ }}}$ 2.3%, 440 B
dist/elements/withMergedProps ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 339 B
dist/utilities/getNavGroups.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 338 B
dist/utilities/getVisibleEntities.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 329 B
dist/elements/WithServerSideProps ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 233 B
dist/layouts/Root ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 230 B
dist/utilities/handleGoBack.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 180 B
dist/fields/mergeFieldStyles.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 158 B
dist/utilities/handleBackToDashboard.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
(other) ${{\color{Goldenrod}{ █████████████████▌ }}}$ 70.1%, 13.16 KB
Details

Next to the size is how much the size has increased or decreased compared with the base branch of this PR.

  • ‼️: Size increased by 20% or more. Special attention should be given to this.
  • ⚠️: Size increased in acceptable range (lower than 20%).
  • ✅: No change or even downsized.
  • 🗑️: The out file is deleted: not found in base branch.
  • 🆕: The out file is newly found: will be added to base branch.

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 })

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be replaced when #19203 lands.

</InlineBlockContainer>
)}
</Form>
<OperationProvider operation="update">

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wrapping with the OperationProvider here

EditButton={EditButton}
errorCount={errorCount}
formSchema={clientBlock?.fields ?? []}
<OperationProvider operation="update">

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wrapping with the OperationProvider here


const { i18n, t } = useTranslation<object, string>()

const onChange = useCallback(

@jacobsfletch jacobsfletch Nov 5, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This utility has been moved to the ui package

Comment thread packages/ui/src/forms/Form/index.tsx Outdated

const prevFormState = useRef(formState)

const validateForm = useCallback(async () => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now owned by the useFormState hook

Comment thread packages/ui/src/forms/Form/index.tsx Outdated
[collectionSlug, docConfig, getUploadHandler],
)

const reset = useCallback(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now owned by the useFormState hook

Comment thread packages/ui/src/forms/Form/types.ts Outdated
* 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)[]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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">

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wrapping with the OperationProvider here.

}
}, [fields, getFormState, isOpen, localeCode, widget.slug, widgetData])

const onChange = useCallback(

@jacobsfletch jacobsfletch Nov 5, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

@jacobsfletch jacobsfletch Nov 5, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The onChange callback is no longer needed here, refreshing form state is now completely owned by the form

],
)

const onChange: FormProps['onChange'][0] = useCallback(

@jacobsfletch jacobsfletch Nov 5, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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({

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The useFormState hook's onSave now handles refreshing form state automatically

const classes = [className, baseClass].filter(Boolean).join(' ')

const executeOnChange = useEffectEvent(() => {
queueTask(async () => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Form state refreshes are now queued by the useFormState hook

Comment thread packages/ui/src/forms/Form/index.tsx Outdated
}
})
for (const onChangeFn of onChange) {
Promise.resolve(onChangeFn({ formState: changedFormState, submitted: isSubmitted })).catch(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The form's onChange callback is now fire-and-forget, its return value is ignored and is only used to perform side effects

Base automatically changed from codex/consolidate-form-state-reducer to main November 7, 2026 01:17
jacobsfletch added a commit that referenced this pull request Nov 7, 2026
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', () => ({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd actually just prefer removing the unit tests in favor of e2e. Done here: 9e26447

@jacobsfletch
jacobsfletch merged commit 09b6b84 into main Nov 10, 2026
574 of 576 checks passed
@jacobsfletch
jacobsfletch deleted the refactor/form-owned-form-state branch November 10, 2026 14:08
@github-actions

Copy link
Copy Markdown
Contributor

🚀 This is included in version v4.0.0-beta.8

denolfe added a commit that referenced this pull request Nov 12, 2026
…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
jacobsfletch added a commit that referenced this pull request Nov 16, 2026
)

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.
jacobsfletch added a commit that referenced this pull request Nov 23, 2026
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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants