feat!: on demand rsc (#8364)
Currently, Payload renders all custom components on initial compile of the admin panel. This is problematic for two key reasons: 1. Custom components do not receive contextual data, i.e. fields do not receive their field data, edit views do not receive their document data, etc. 2. Components are unnecessarily rendered before they are used This was initially required to support React Server Components within the Payload Admin Panel for two key reasons: 1. Fields can be dynamically rendered within arrays, blocks, etc. 2. Documents can be recursively rendered within a "drawer" UI, i.e. relationship fields 3. Payload supports server/client component composition In order to achieve this, components need to be rendered on the server and passed as "slots" to the client. Currently, the pattern for this is to render custom server components in the "client config". Then when a view or field is needed to be rendered, we first check the client config for a "pre-rendered" component, otherwise render our client-side fallback component. But for the reasons listed above, this pattern doesn't exactly make custom server components very useful within the Payload Admin Panel, which is where this PR comes in. Now, instead of pre-rendering all components on initial compile, we're able to render custom components _on demand_, only as they are needed. To achieve this, we've established [this pattern](https://github.com/payloadcms/payload/pull/8481) of React Server Functions in the Payload Admin Panel. With Server Functions, we can iterate the Payload Config and return JSX through React's `text/x-component` content-type. This means we're able to pass contextual props to custom components, such as data for fields and views. ## Breaking Changes 1. Add the following to your root layout file, typically located at `(app)/(payload)/layout.tsx`: ```diff /* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ /* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */ + import type { ServerFunctionClient } from 'payload' import config from '@payload-config' import { RootLayout } from '@payloadcms/next/layouts' import { handleServerFunctions } from '@payloadcms/next/utilities' import React from 'react' import { importMap } from './admin/importMap.js' import './custom.scss' type Args = { children: React.ReactNode } + const serverFunctions: ServerFunctionClient = async function (args) { + 'use server' + return handleServerFunctions({ + ...args, + config, + importMap, + }) + } const Layout = ({ children }: Args) => ( <RootLayout config={config} importMap={importMap} + serverFunctions={serverFunctions} > {children} </RootLayout> ) export default Layout ``` 2. If you were previously posting to the `/api/form-state` endpoint, it no longer exists. Instead, you'll need to invoke the `form-state` Server Function, which can be done through the _new_ `getFormState` utility: ```diff - import { getFormState } from '@payloadcms/ui' - const { state } = await getFormState({ - apiRoute: '', - body: { - // ... - }, - serverURL: '' - }) + const { getFormState } = useServerFunctions() + + const { state } = await getFormState({ + // ... + }) ``` ## Breaking Changes ```diff - useFieldProps() - useCellProps() ``` More details coming soon. --------- Co-authored-by: Alessio Gravili <alessio@gravili.de> Co-authored-by: Jarrod Flesch <jarrodmflesch@gmail.com> Co-authored-by: James <james@trbl.design>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
import type { ArrayField, ClientField, FieldPermissions, MappedComponent, Row } from 'payload'
|
||||
import type { ArrayField, ClientField, FieldPermissions, Row } from 'payload'
|
||||
|
||||
import { getTranslation } from '@payloadcms/translations'
|
||||
import React from 'react'
|
||||
@@ -19,15 +19,16 @@ const baseClass = 'array-field'
|
||||
|
||||
type ArrayRowProps = {
|
||||
readonly addRow: (rowIndex: number) => Promise<void> | void
|
||||
readonly CustomRowLabel?: React.ReactNode
|
||||
readonly duplicateRow: (rowIndex: number) => void
|
||||
readonly errorCount: number
|
||||
readonly fields: ClientField[]
|
||||
readonly forceRender?: boolean
|
||||
readonly hasMaxRows?: boolean
|
||||
readonly indexPath: string
|
||||
readonly isSortable?: boolean
|
||||
readonly labels: Partial<ArrayField['labels']>
|
||||
readonly moveRow: (fromIndex: number, toIndex: number) => void
|
||||
readonly parentPath: string
|
||||
readonly path: string
|
||||
readonly permissions: FieldPermissions
|
||||
readonly readOnly?: boolean
|
||||
@@ -35,7 +36,6 @@ type ArrayRowProps = {
|
||||
readonly row: Row
|
||||
readonly rowCount: number
|
||||
readonly rowIndex: number
|
||||
readonly RowLabel?: MappedComponent
|
||||
readonly schemaPath: string
|
||||
readonly setCollapse: (rowID: string, collapsed: boolean) => void
|
||||
} & UseDraggableSortableReturn
|
||||
@@ -43,32 +43,31 @@ type ArrayRowProps = {
|
||||
export const ArrayRow: React.FC<ArrayRowProps> = ({
|
||||
addRow,
|
||||
attributes,
|
||||
CustomRowLabel,
|
||||
duplicateRow,
|
||||
errorCount,
|
||||
fields,
|
||||
forceRender = false,
|
||||
hasMaxRows,
|
||||
indexPath,
|
||||
isDragging,
|
||||
isSortable,
|
||||
labels,
|
||||
listeners,
|
||||
moveRow,
|
||||
path: parentPath,
|
||||
parentPath,
|
||||
path,
|
||||
permissions,
|
||||
readOnly,
|
||||
removeRow,
|
||||
row,
|
||||
rowCount,
|
||||
rowIndex,
|
||||
RowLabel: CustomRowLabel,
|
||||
schemaPath,
|
||||
setCollapse,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
}) => {
|
||||
const path = `${parentPath}.${rowIndex}`
|
||||
const { i18n } = useTranslation()
|
||||
const hasSubmitted = useFormSubmitted()
|
||||
|
||||
@@ -126,11 +125,10 @@ export const ArrayRow: React.FC<ArrayRowProps> = ({
|
||||
header={
|
||||
<div className={`${baseClass}__row-header`}>
|
||||
<RowLabel
|
||||
i18n={i18n}
|
||||
CustomComponent={CustomRowLabel}
|
||||
label={fallbackLabel}
|
||||
path={path}
|
||||
RowLabel={CustomRowLabel}
|
||||
rowLabel={fallbackLabel}
|
||||
rowNumber={rowIndex + 1}
|
||||
rowNumber={rowIndex}
|
||||
/>
|
||||
{fieldHasErrors && <ErrorPill count={errorCount} i18n={i18n} withMessage />}
|
||||
</div>
|
||||
@@ -142,12 +140,12 @@ export const ArrayRow: React.FC<ArrayRowProps> = ({
|
||||
className={`${baseClass}__fields`}
|
||||
fields={fields}
|
||||
forceRender={forceRender}
|
||||
indexPath={indexPath}
|
||||
margins="small"
|
||||
path={path}
|
||||
parentIndexPath=""
|
||||
parentPath={path}
|
||||
parentSchemaPath={schemaPath}
|
||||
permissions={permissions?.fields}
|
||||
readOnly={readOnly}
|
||||
schemaPath={schemaPath}
|
||||
/>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
@@ -13,7 +13,10 @@ import { Button } from '../../elements/Button/index.js'
|
||||
import { DraggableSortableItem } from '../../elements/DraggableSortable/DraggableSortableItem/index.js'
|
||||
import { DraggableSortable } from '../../elements/DraggableSortable/index.js'
|
||||
import { ErrorPill } from '../../elements/ErrorPill/index.js'
|
||||
import { useFieldProps } from '../../forms/FieldPropsProvider/index.js'
|
||||
import { RenderCustomComponent } from '../../elements/RenderCustomComponent/index.js'
|
||||
import { FieldDescription } from '../../fields/FieldDescription/index.js'
|
||||
import { FieldError } from '../../fields/FieldError/index.js'
|
||||
import { FieldLabel } from '../../fields/FieldLabel/index.js'
|
||||
import { useForm, useFormSubmitted } from '../../forms/Form/context.js'
|
||||
import { extractRowsAndCollapsedIDs, toggleAllRows } from '../../forms/Form/rowHelpers.js'
|
||||
import { NullifyLocaleField } from '../../forms/NullifyField/index.js'
|
||||
@@ -24,9 +27,6 @@ import { useDocumentInfo } from '../../providers/DocumentInfo/index.js'
|
||||
import { useLocale } from '../../providers/Locale/index.js'
|
||||
import { useTranslation } from '../../providers/Translation/index.js'
|
||||
import { scrollToID } from '../../utilities/scrollToID.js'
|
||||
import { FieldDescription } from '../FieldDescription/index.js'
|
||||
import { FieldError } from '../FieldError/index.js'
|
||||
import { FieldLabel } from '../FieldLabel/index.js'
|
||||
import { fieldBaseClass } from '../shared/index.js'
|
||||
import { ArrayRow } from './ArrayRow.js'
|
||||
import './index.scss'
|
||||
@@ -35,19 +35,9 @@ const baseClass = 'array-field'
|
||||
|
||||
export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
const {
|
||||
descriptionProps,
|
||||
errorProps,
|
||||
field,
|
||||
field: {
|
||||
name,
|
||||
_path: pathFromProps,
|
||||
admin: {
|
||||
className,
|
||||
components: { RowLabel },
|
||||
description,
|
||||
isSortable = true,
|
||||
readOnly: readOnlyFromAdmin,
|
||||
} = {},
|
||||
admin: { className, description, isSortable = true } = {},
|
||||
fields,
|
||||
label,
|
||||
localized,
|
||||
@@ -56,19 +46,14 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
required,
|
||||
},
|
||||
forceRender = false,
|
||||
labelProps,
|
||||
readOnly: readOnlyFromTopLevelProps,
|
||||
path: pathFromProps,
|
||||
permissions,
|
||||
readOnly,
|
||||
schemaPath: schemaPathFromProps,
|
||||
validate,
|
||||
} = props
|
||||
|
||||
const readOnlyFromProps = readOnlyFromTopLevelProps || readOnlyFromAdmin
|
||||
|
||||
const {
|
||||
indexPath,
|
||||
path: pathFromContext,
|
||||
permissions,
|
||||
readOnly: readOnlyFromContext,
|
||||
} = useFieldProps()
|
||||
const path = pathFromProps ?? name
|
||||
const schemaPath = schemaPathFromProps ?? name
|
||||
|
||||
const minRows = (minRowsProp ?? required) ? 1 : 0
|
||||
|
||||
@@ -96,12 +81,15 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
if ('labels' in p && p?.labels) {
|
||||
return p.labels
|
||||
}
|
||||
|
||||
if ('labels' in p.field && p.field.labels) {
|
||||
return { plural: p.field.labels?.plural, singular: p.field.labels?.singular }
|
||||
}
|
||||
|
||||
if ('label' in p.field && p.field.label) {
|
||||
return { plural: undefined, singular: p.field.label }
|
||||
}
|
||||
|
||||
return { plural: t('general:rows'), singular: t('general:row') }
|
||||
}
|
||||
|
||||
@@ -113,6 +101,7 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
if (!editingDefaultLocale && value === null) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (typeof validate === 'function') {
|
||||
return validate(value, { ...options, maxRows, minRows, required })
|
||||
}
|
||||
@@ -121,38 +110,39 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
)
|
||||
|
||||
const {
|
||||
customComponents: { Description, Error, Label, RowLabels } = {},
|
||||
errorPaths,
|
||||
formInitializing,
|
||||
formProcessing,
|
||||
path,
|
||||
rows = [],
|
||||
schemaPath,
|
||||
rows: rowsData = [],
|
||||
showError,
|
||||
valid,
|
||||
value,
|
||||
} = useField<number>({
|
||||
hasRows: true,
|
||||
path: pathFromContext ?? pathFromProps ?? name,
|
||||
path,
|
||||
validate: memoizedValidate,
|
||||
})
|
||||
|
||||
const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing
|
||||
|
||||
const addRow = useCallback(
|
||||
async (rowIndex: number): Promise<void> => {
|
||||
await addFieldRow({ path, rowIndex, schemaPath })
|
||||
(rowIndex: number) => {
|
||||
addFieldRow({
|
||||
path,
|
||||
rowIndex,
|
||||
schemaPath,
|
||||
})
|
||||
|
||||
setModified(true)
|
||||
|
||||
setTimeout(() => {
|
||||
scrollToID(`${path}-row-${rowIndex + 1}`)
|
||||
scrollToID(`${path}-row-${rowIndex}`)
|
||||
}, 0)
|
||||
},
|
||||
[addFieldRow, path, setModified, schemaPath],
|
||||
[addFieldRow, path, schemaPath, setModified],
|
||||
)
|
||||
|
||||
const duplicateRow = useCallback(
|
||||
(rowIndex: number) => {
|
||||
dispatchFields({ type: 'DUPLICATE_ROW', path, rowIndex })
|
||||
|
||||
setModified(true)
|
||||
|
||||
setTimeout(() => {
|
||||
@@ -182,12 +172,12 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
(collapsed: boolean) => {
|
||||
const { collapsedIDs, updatedRows } = toggleAllRows({
|
||||
collapsed,
|
||||
rows,
|
||||
rows: rowsData,
|
||||
})
|
||||
dispatchFields({ type: 'SET_ALL_ROWS_COLLAPSED', path, updatedRows })
|
||||
setDocFieldPreferences(path, { collapsed: collapsedIDs })
|
||||
dispatchFields({ type: 'SET_ALL_ROWS_COLLAPSED', path, updatedRows })
|
||||
},
|
||||
[dispatchFields, path, rows, setDocFieldPreferences],
|
||||
[dispatchFields, path, rowsData, setDocFieldPreferences],
|
||||
)
|
||||
|
||||
const setCollapse = useCallback(
|
||||
@@ -195,21 +185,22 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
const { collapsedIDs, updatedRows } = extractRowsAndCollapsedIDs({
|
||||
collapsed,
|
||||
rowID,
|
||||
rows,
|
||||
rows: rowsData,
|
||||
})
|
||||
|
||||
dispatchFields({ type: 'SET_ROW_COLLAPSED', path, updatedRows })
|
||||
setDocFieldPreferences(path, { collapsed: collapsedIDs })
|
||||
},
|
||||
[dispatchFields, path, rows, setDocFieldPreferences],
|
||||
[dispatchFields, path, rowsData, setDocFieldPreferences],
|
||||
)
|
||||
|
||||
const hasMaxRows = maxRows && rows.length >= maxRows
|
||||
const hasMaxRows = maxRows && rowsData.length >= maxRows
|
||||
|
||||
const fieldErrorCount = errorPaths.length
|
||||
const fieldHasErrors = submitted && errorPaths.length > 0
|
||||
|
||||
const showRequired = disabled && rows.length === 0
|
||||
const showMinRows = rows.length < minRows || (required && rows.length === 0)
|
||||
const showRequired = readOnly && rowsData.length === 0
|
||||
const showMinRows = rowsData.length < minRows || (required && rowsData.length === 0)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -224,30 +215,33 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
id={`field-${path.replace(/\./g, '__')}`}
|
||||
>
|
||||
{showError && (
|
||||
<FieldError
|
||||
CustomError={field?.admin?.components?.Error}
|
||||
field={field}
|
||||
path={path}
|
||||
{...(errorProps || {})}
|
||||
<RenderCustomComponent
|
||||
CustomComponent={Error}
|
||||
Fallback={<FieldError path={path} showError={showError} />}
|
||||
/>
|
||||
)}
|
||||
<header className={`${baseClass}__header`}>
|
||||
<div className={`${baseClass}__header-wrap`}>
|
||||
<div className={`${baseClass}__header-content`}>
|
||||
<h3 className={`${baseClass}__title`}>
|
||||
<FieldLabel
|
||||
as="span"
|
||||
field={field}
|
||||
Label={field?.admin?.components?.Label}
|
||||
unstyled
|
||||
{...(labelProps || {})}
|
||||
<RenderCustomComponent
|
||||
CustomComponent={Label}
|
||||
Fallback={
|
||||
<FieldLabel
|
||||
as="span"
|
||||
label={label}
|
||||
localized={localized}
|
||||
path={path}
|
||||
required={required}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</h3>
|
||||
{fieldHasErrors && fieldErrorCount > 0 && (
|
||||
<ErrorPill count={fieldErrorCount} i18n={i18n} withMessage />
|
||||
)}
|
||||
</div>
|
||||
{rows.length > 0 && (
|
||||
{rowsData?.length > 0 && (
|
||||
<ul className={`${baseClass}__header-actions`}>
|
||||
<li>
|
||||
<button
|
||||
@@ -270,47 +264,50 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<FieldDescription
|
||||
Description={field?.admin?.components?.Description}
|
||||
description={description}
|
||||
field={field}
|
||||
{...(descriptionProps || {})}
|
||||
<RenderCustomComponent
|
||||
CustomComponent={Description}
|
||||
Fallback={<FieldDescription description={description} path={path} />}
|
||||
/>
|
||||
</header>
|
||||
<NullifyLocaleField fieldValue={value} localized={localized} path={path} />
|
||||
{(rows.length > 0 || (!valid && (showRequired || showMinRows))) && (
|
||||
{(rowsData?.length > 0 || (!valid && (showRequired || showMinRows))) && (
|
||||
<DraggableSortable
|
||||
className={`${baseClass}__draggable-rows`}
|
||||
ids={rows.map((row) => row.id)}
|
||||
ids={rowsData.map((row) => row.id)}
|
||||
onDragEnd={({ moveFromIndex, moveToIndex }) => moveRow(moveFromIndex, moveToIndex)}
|
||||
>
|
||||
{rows.map((row, i) => {
|
||||
{rowsData.map((rowData, i) => {
|
||||
const { id: rowID } = rowData
|
||||
|
||||
const rowPath = `${path}.${i}`
|
||||
|
||||
const rowErrorCount = errorPaths?.filter((errorPath) =>
|
||||
errorPath.startsWith(`${path}.${i}.`),
|
||||
errorPath.startsWith(rowPath + '.'),
|
||||
).length
|
||||
|
||||
return (
|
||||
<DraggableSortableItem disabled={disabled || !isSortable} id={row.id} key={row.id}>
|
||||
<DraggableSortableItem disabled={readOnly || !isSortable} id={rowID} key={rowID}>
|
||||
{(draggableSortableItemProps) => (
|
||||
<ArrayRow
|
||||
{...draggableSortableItemProps}
|
||||
addRow={addRow}
|
||||
CustomRowLabel={RowLabels?.[i]}
|
||||
duplicateRow={duplicateRow}
|
||||
errorCount={rowErrorCount}
|
||||
fields={fields}
|
||||
forceRender={forceRender}
|
||||
hasMaxRows={hasMaxRows}
|
||||
indexPath={indexPath}
|
||||
isSortable={isSortable}
|
||||
labels={labels}
|
||||
moveRow={moveRow}
|
||||
path={path}
|
||||
parentPath={path}
|
||||
path={rowPath}
|
||||
permissions={permissions}
|
||||
readOnly={disabled}
|
||||
readOnly={readOnly}
|
||||
removeRow={removeRow}
|
||||
row={row}
|
||||
rowCount={rows.length}
|
||||
row={rowData}
|
||||
rowCount={rowsData?.length}
|
||||
rowIndex={i}
|
||||
RowLabel={RowLabel}
|
||||
schemaPath={schemaPath}
|
||||
setCollapse={setCollapse}
|
||||
/>
|
||||
@@ -339,7 +336,7 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => {
|
||||
)}
|
||||
</DraggableSortable>
|
||||
)}
|
||||
{!disabled && !hasMaxRows && (
|
||||
{!readOnly && !hasMaxRows && (
|
||||
<Button
|
||||
buttonStyle="icon-label"
|
||||
className={`${baseClass}__add-row`}
|
||||
|
||||
Reference in New Issue
Block a user