Files
payloadcms/packages/richtext-slate/src/field/elements/upload/Element/index.tsx
Jacob Fletcher c96fa613bc 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>
2024-11-11 13:59:05 -05:00

226 lines
6.8 KiB
TypeScript

'use client'
import type { ClientCollectionConfig } from 'payload'
import { getTranslation } from '@payloadcms/translations'
import {
Button,
DrawerToggler,
File,
useConfig,
useDocumentDrawer,
useDrawerSlug,
useListDrawer,
usePayloadAPI,
useTranslation,
} from '@payloadcms/ui'
import React, { useCallback, useReducer, useState } from 'react'
import { Transforms } from 'slate'
import { ReactEditor, useFocused, useSelected, useSlateStatic } from 'slate-react'
import type { UploadElementType } from '../types.js'
import { useElement } from '../../../providers/ElementProvider.js'
import { EnabledRelationshipsCondition } from '../../EnabledRelationshipsCondition.js'
import { uploadFieldsSchemaPath, uploadName } from '../shared.js'
import './index.scss'
import { UploadDrawer } from './UploadDrawer/index.js'
const baseClass = 'rich-text-upload'
const initialParams = {
depth: 0,
}
const UploadElementComponent: React.FC<{ enabledCollectionSlugs?: string[] }> = ({
enabledCollectionSlugs,
}) => {
const {
attributes,
children,
element: { relationTo, value },
element,
fieldProps,
schemaPath,
} = useElement<UploadElementType>()
const {
config: {
collections,
routes: { api },
serverURL,
},
} = useConfig()
const { i18n, t } = useTranslation()
const [cacheBust, dispatchCacheBust] = useReducer((state) => state + 1, 0)
const [relatedCollection, setRelatedCollection] = useState<ClientCollectionConfig>(() =>
collections.find((coll) => coll.slug === relationTo),
)
const drawerSlug = useDrawerSlug('upload-drawer')
const [ListDrawer, ListDrawerToggler, { closeDrawer: closeListDrawer }] = useListDrawer({
collectionSlugs: enabledCollectionSlugs,
selectedCollection: relatedCollection.slug,
})
const [DocumentDrawer, DocumentDrawerToggler, { closeDrawer }] = useDocumentDrawer({
id: value?.id,
collectionSlug: relatedCollection.slug,
})
const editor = useSlateStatic()
const selected = useSelected()
const focused = useFocused()
// Get the referenced document
const [{ data }, { setParams }] = usePayloadAPI(
`${serverURL}${api}/${relatedCollection.slug}/${value?.id}`,
{ initialParams },
)
const thumbnailSRC = data?.thumbnailURL || data?.url
const removeUpload = useCallback(() => {
const elementPath = ReactEditor.findPath(editor, element)
Transforms.removeNodes(editor, { at: elementPath })
}, [editor, element])
const updateUpload = useCallback(
(json) => {
const { doc } = json
const newNode = {
fields: doc,
}
const elementPath = ReactEditor.findPath(editor, element)
Transforms.setNodes(editor, newNode, { at: elementPath })
setParams({
...initialParams,
cacheBust, // do this to get the usePayloadAPI to re-fetch the data even though the URL string hasn't changed
})
dispatchCacheBust()
closeDrawer()
},
[editor, element, setParams, cacheBust, closeDrawer],
)
const swapUpload = React.useCallback(
({ collectionSlug, docID }) => {
const newNode = {
type: uploadName,
children: [{ text: ' ' }],
relationTo: collectionSlug,
value: { id: docID },
}
const elementPath = ReactEditor.findPath(editor, element)
setRelatedCollection(collections.find((coll) => coll.slug === collectionSlug))
Transforms.setNodes(editor, newNode, { at: elementPath })
dispatchCacheBust()
closeListDrawer()
},
[closeListDrawer, editor, element, collections],
)
const relatedFieldSchemaPath = `${uploadFieldsSchemaPath}.${relatedCollection.slug}`
const customFieldsMap = fieldProps.componentMap[relatedFieldSchemaPath]
return (
<div
className={[baseClass, selected && focused && `${baseClass}--selected`]
.filter(Boolean)
.join(' ')}
contentEditable={false}
{...attributes}
>
<div className={`${baseClass}__card`}>
<div className={`${baseClass}__topRow`}>
{/* TODO: migrate to use Thumbnail component */}
<div className={`${baseClass}__thumbnail`}>
{thumbnailSRC ? <img alt={data?.filename} src={thumbnailSRC} /> : <File />}
</div>
<div className={`${baseClass}__topRowRightPanel`}>
<div className={`${baseClass}__collectionLabel`}>
{getTranslation(relatedCollection.labels.singular, i18n)}
</div>
<div className={`${baseClass}__actions`}>
{Boolean(customFieldsMap) && (
<DrawerToggler
className={`${baseClass}__upload-drawer-toggler`}
disabled={fieldProps?.field?.admin?.readOnly}
slug={drawerSlug}
>
<Button
buttonStyle="icon-label"
el="div"
icon="edit"
onClick={(e) => {
e.preventDefault()
}}
round
tooltip={t('fields:editRelationship')}
/>
</DrawerToggler>
)}
<ListDrawerToggler
className={`${baseClass}__list-drawer-toggler`}
disabled={fieldProps?.field?.admin?.readOnly}
>
<Button
buttonStyle="icon-label"
disabled={fieldProps?.field?.admin?.readOnly}
el="div"
icon="swap"
onClick={() => {
// do nothing
}}
round
tooltip={t('fields:swapUpload')}
/>
</ListDrawerToggler>
<Button
buttonStyle="icon-label"
className={`${baseClass}__removeButton`}
disabled={fieldProps?.field?.admin?.readOnly}
icon="x"
onClick={(e) => {
e.preventDefault()
removeUpload()
}}
round
tooltip={t('fields:removeUpload')}
/>
</div>
</div>
</div>
<div className={`${baseClass}__bottomRow`}>
<DocumentDrawerToggler className={`${baseClass}__doc-drawer-toggler`}>
<strong>{data?.filename}</strong>
</DocumentDrawerToggler>
</div>
</div>
{children}
{value?.id && <DocumentDrawer onSave={updateUpload} />}
<ListDrawer onSelect={swapUpload} />
<UploadDrawer {...{ drawerSlug, element, fieldProps, relatedCollection, schemaPath }} />
</div>
)
}
export const UploadElement = (props: any): React.ReactNode => {
return (
<EnabledRelationshipsCondition {...props} uploads>
<UploadElementComponent {...props} />
</EnabledRelationshipsCondition>
)
}