feat!: beta-next (#7620)

This PR makes three major changes to the codebase:

1. [Component Paths](#component-paths)
Instead of importing custom components into your config directly, they
are now defined as file paths and rendered only when needed. That way
the Payload config will be significantly more lightweight, and ensures
that the Payload config is 100% server-only and Node-safe. Related
discussion: https://github.com/payloadcms/payload/discussions/6938

2. [Client Config](#client-config)
Deprecates the component map by merging its logic into the client
config. The main goal of this change is for performance and
simplification. There was no need to deeply iterate over the Payload
config twice, once for the component map, and another for the client
config. Instead, we can do everything in the client config one time.
This has also dramatically simplified the client side prop drilling
through the UI library. Now, all components can share the same client
config which matches the exact shape of their Payload config (with the
exception of non-serializable props and mapped custom components).

3. [Custom client component are no longer
server-rendered](#custom-client-components-are-no-longer-server-rendered)
Previously, custom components would be server-rendered, no matter if
they are server or client components. Now, only server components are
rendered on the server. Client components are automatically detected,
and simply get passed through as `MappedComponent` to be rendered fully
client-side.

## Component Paths

Instead of importing custom components into your config directly, they
are now defined as file paths and rendered only when needed. That way
the Payload config will be significantly more lightweight, and ensures
that the Payload config is 100% server-only and Node-safe. Related
discussion: https://github.com/payloadcms/payload/discussions/6938

In order to reference any custom components in the Payload config, you
now have to specify a string path to the component instead of importing
it.

Old:

```ts
import { MyComponent2} from './MyComponent2.js'

admin: {
  components: {
    Label: MyComponent2
  },
},
```

New:

```ts
admin: {
  components: {
    Label: '/collections/Posts/MyComponent2.js#MyComponent2', // <= has to be a relative path based on a baseDir configured in the Payload config - NOT relative based on the importing file
  },
},
```

### Local API within Next.js routes

Previously, if you used the Payload Local API within Next.js pages, all
the client-side modules are being added to the bundle for that specific
page, even if you only need server-side functionality.

This `/test` route, which uses the Payload local API, was previously 460
kb. It is now down to 91 kb and does not bundle the Payload client-side
admin panel anymore.

All tests done
[here](https://github.com/payloadcms/payload-3.0-demo/tree/feat/path-test)
with beta.67/PR, db-mongodb and default richtext-lexical:

**dev /admin before:**
![CleanShot 2024-07-29 at 22 49
12@2x](https://github.com/user-attachments/assets/4428e766-b368-4bcf-8c18-d0187ab64f3e)

**dev /admin after:**
![CleanShot 2024-07-29 at 22 50
49@2x](https://github.com/user-attachments/assets/f494c848-7247-4b02-a650-a3fab4000de6)

---

**dev /test before:**
![CleanShot 2024-07-29 at 22 56
18@2x](https://github.com/user-attachments/assets/1a7e9500-b859-4761-bf63-abbcdac6f8d6)

**dev /test after:**
![CleanShot 2024-07-29 at 22 47
45@2x](https://github.com/user-attachments/assets/f89aa76d-f2d5-4572-9753-2267f034a45a)

---

**build before:**
![CleanShot 2024-07-29 at 22 57
14@2x](https://github.com/user-attachments/assets/5f8f7281-2a4a-40a5-a788-c30ddcdd51b5)

**build after::**
![CleanShot 2024-07-29 at 22 56
39@2x](https://github.com/user-attachments/assets/ea8772fd-512f-4db0-9a81-4b014715a1b7)

### Usage of the Payload Local API / config outside of Next.js

This will make it a lot easier to use the Payload config / local API in
other, server-side contexts. Previously, you might encounter errors due
to client files (like .scss files) not being allowed to be imported.

## Client Config

Deprecates the component map by merging its logic into the client
config. The main goal of this change is for performance and
simplification. There was no need to deeply iterate over the Payload
config twice, once for the component map, and another for the client
config. Instead, we can do everything in the client config one time.
This has also dramatically simplified the client side prop drilling
through the UI library. Now, all components can share the same client
config which matches the exact shape of their Payload config (with the
exception of non-serializable props and mapped custom components).

This is breaking change. The `useComponentMap` hook no longer exists,
and most component props have changed (for the better):

```ts
const { componentMap } = useComponentMap() // old
const { config } = useConfig() // new
```

The `useConfig` hook has also changed in shape, `config` is now a
property _within_ the context obj:

```ts
const config = useConfig() // old
const { config } = useConfig() // new
```

## Custom Client Components are no longer server rendered

Previously, custom components would be server-rendered, no matter if
they are server or client components. Now, only server components are
rendered on the server. Client components are automatically detected,
and simply get passed through as `MappedComponent` to be rendered fully
client-side.

The benefit of this change:

Custom client components can now receive props. Previously, the only way
for them to receive dynamic props from a parent client component was to
use hooks, e.g. `useFieldProps()`. Now, we do have the option of passing
in props to the custom components directly, if they are client
components. This will be simpler than having to look for the correct
hook.

This makes rendering them on the client a little bit more complex, as
you now have to check if that component is a server component (=>
already has been rendered) or a client component (=> not rendered yet,
has to be rendered here). However, this added complexity has been
alleviated through the easy-to-use `<RenderMappedComponent />` helper.

This helper now also handles rendering arrays of custom components (e.g.
beforeList, beforeLogin ...), which actually makes rendering custom
components easier in some cases.

## Misc improvements

This PR includes misc, breaking changes. For example, we previously
allowed unions between components and config object for the same
property. E.g. for the custom view property, you were allowed to pass in
a custom component or an object with other properties, alongside a
custom component.

Those union types are now gone. You can now either pass an object, or a
component. The previous `{ View: MyViewComponent}` is now `{ View: {
Component: MyViewComponent} }` or `{ View: { Default: { Component:
MyViewComponent} } }`.

This dramatically simplifies the way we read & process those properties,
especially in buildComponentMap. We can now simply check for the
existence of one specific property, which always has to be a component,
instead of running cursed runtime checks on a shared union property
which could contain a component, but could also contain functions or
objects.

![CleanShot 2024-07-29 at 23 07
07@2x](https://github.com/user-attachments/assets/1e75aa4c-7a4c-419f-9070-216bb7b9a5e5)

![CleanShot 2024-07-29 at 23 09
40@2x](https://github.com/user-attachments/assets/b4c96450-6b7e-496c-a4f7-59126bfd0991)

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository.

---------

Co-authored-by: PatrikKozak <patrik@payloadcms.com>
Co-authored-by: Paul <paul@payloadcms.com>
Co-authored-by: Paul Popus <paul@nouance.io>
Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
Co-authored-by: James <james@trbl.design>
This commit is contained in:
Alessio Gravili
2024-08-13 12:54:33 -04:00
committed by GitHub
parent 9cb84c48b9
commit 90b7b20699
874 changed files with 12208 additions and 9403 deletions

View File

@@ -16,6 +16,12 @@
"import": "./src/index.tsx",
"types": "./src/index.tsx",
"default": "./src/index.tsx"
},
"./generateComponentMap": "./src/generateComponentMap.tsx",
"./client": {
"import": "./src/exports/client/index.ts",
"types": "./src/exports/client/index.ts",
"default": "./src/exports/client/index.ts"
}
},
"main": "./src/index.tsx",
@@ -62,6 +68,16 @@
"import": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./generateComponentMap": {
"import": "./dist/generateComponentMap.js",
"types": "./dist/generateComponentMap.d.ts",
"default": "./dist/generateComponentMap.js"
},
"./client": {
"import": "./dist/exports/client/index.js",
"types": "./dist/exports/client/index.d.ts",
"default": "./dist/exports/client/index.js"
}
},
"main": "./dist/index.js",

View File

@@ -14,7 +14,7 @@ type RecurseRichTextArgs = {
currentDepth: number
depth: number
draft: boolean
field: RichTextField<any[], AdapterArguments, AdapterArguments>
field: RichTextField<any[], any, any>
overrideAccess: boolean
populationPromises: Promise<void>[]
req: PayloadRequest

View File

@@ -0,0 +1,65 @@
'use client'
export { RichTextCell } from '../../cell/index.js'
export { ElementButton } from '../../field/elements/Button.js'
export { BlockquoteElementButton } from '../../field/elements/blockquote/Button.js'
export { BlockquoteElement } from '../../field/elements/blockquote/Element.js'
export { H1ElementButton } from '../../field/elements/h1/Button.js'
export { Heading1Element } from '../../field/elements/h1/Heading1.js'
export { H2ElementButton } from '../../field/elements/h2/Button.js'
export { Heading2Element } from '../../field/elements/h2/Heading2.js'
export { H3ElementButton } from '../../field/elements/h3/Button.js'
export { Heading3Element } from '../../field/elements/h3/Heading3.js'
export { H4ElementButton } from '../../field/elements/h4/Button.js'
export { Heading4Element } from '../../field/elements/h4/Heading4.js'
export { H5ElementButton } from '../../field/elements/h5/Button.js'
export { Heading5Element } from '../../field/elements/h5/Heading5.js'
export { H6ElementButton } from '../../field/elements/h6/Button.js'
export { Heading6Element } from '../../field/elements/h6/Heading6.js'
export { IndentButton } from '../../field/elements/indent/Button.js'
export { IndentElement } from '../../field/elements/indent/Element.js'
export { ListItemElement } from '../../field/elements/li/ListItem.js'
export { LinkButton } from '../../field/elements/link/Button/index.js'
export { LinkElement } from '../../field/elements/link/Element/index.js'
export { WithLinks } from '../../field/elements/link/WithLinks.js'
export { OLElementButton } from '../../field/elements/ol/Button.js'
export { OrderedListElement } from '../../field/elements/ol/OrderedList.js'
export { RelationshipButton } from '../../field/elements/relationship/Button/index.js'
export { RelationshipElement } from '../../field/elements/relationship/Element/index.js'
export { WithRelationship } from '../../field/elements/relationship/plugin.js'
export { TextAlignElementButton } from '../../field/elements/textAlign/Button.js'
export { toggleElement } from '../../field/elements/toggle.js'
export { ULElementButton } from '../../field/elements/ul/Button.js'
export { UnorderedListElement } from '../../field/elements/ul/UnorderedList.js'
export { UploadElementButton } from '../../field/elements/upload/Button/index.js'
export { UploadElement } from '../../field/elements/upload/Element/index.js'
export { WithUpload } from '../../field/elements/upload/plugin.js'
export { RichTextField } from '../../field/index.js'
export { LeafButton } from '../../field/leaves/Button.js'
export { BoldLeaf } from '../../field/leaves/bold/Bold/index.js'
export { BoldLeafButton } from '../../field/leaves/bold/LeafButton.js'
export { CodeLeaf } from '../../field/leaves/code/Code/index.js'
export { CodeLeafButton } from '../../field/leaves/code/LeafButton.js'
export { ItalicLeaf } from '../../field/leaves/italic/Italic/index.js'
export { ItalicLeafButton } from '../../field/leaves/italic/LeafButton.js'
export { StrikethroughLeafButton } from '../../field/leaves/strikethrough/LeafButton.js'
export { StrikethroughLeaf } from '../../field/leaves/strikethrough/Strikethrough/index.js'
export { UnderlineLeafButton } from '../../field/leaves/underline/LeafButton.js'
export { UnderlineLeaf } from '../../field/leaves/underline/Underline/index.js'
export { useLeaf } from '../../field/providers/LeafProvider.js'

View File

@@ -1,6 +1,6 @@
'use client'
import type { FormFieldBase, PayloadRequest, RichTextFieldValidation } from 'payload'
import type { PayloadRequest } from 'payload'
import type { BaseEditor, BaseOperation } from 'slate'
import type { HistoryEditor } from 'slate-history'
import type { ReactEditor } from 'slate-react'
@@ -10,6 +10,7 @@ import {
FieldDescription,
FieldError,
FieldLabel,
RenderComponent,
useEditDepth,
useField,
useFieldProps,
@@ -22,8 +23,8 @@ import { Node, Element as SlateElement, Text, Transforms, createEditor } from 's
import { withHistory } from 'slate-history'
import { Editable, Slate, withReact } from 'slate-react'
import type { ElementNode, RichTextPlugin, TextNode } from '../types.js'
import type { EnabledFeatures } from './types.js'
import type { ElementNode, TextNode } from '../types.js'
import type { LoadedSlateFieldProps } from './types.js'
import { defaultRichTextValue } from '../data/defaultValue.js'
import { richTextValidate } from '../data/validation.js'
@@ -48,40 +49,34 @@ declare module 'slate' {
}
}
const RichTextField: React.FC<
{
elements: EnabledFeatures['elements']
leaves: EnabledFeatures['leaves']
name: string
placeholder?: string
plugins: RichTextPlugin[]
richTextComponentMap: Map<string, React.ReactNode>
validate?: RichTextFieldValidation
width?: string
} & Omit<FormFieldBase, 'validate'>
> = (props) => {
const RichTextField: React.FC<LoadedSlateFieldProps> = (props) => {
const {
name,
CustomDescription,
CustomError,
CustomLabel,
className,
descriptionProps,
elements,
errorProps,
label,
field: {
name,
_path: pathFromProps,
admin: {
className,
components: { Description, Error, Label },
placeholder,
readOnly: readOnlyFromAdmin,
style,
width,
},
label,
required,
},
labelProps,
leaves,
path: pathFromProps,
placeholder,
plugins,
readOnly: readOnlyFromProps,
required,
style,
readOnly: readOnlyFromTopLevelProps,
validate = richTextValidate,
width,
} = props
const readOnlyFromProps = readOnlyFromTopLevelProps || readOnlyFromAdmin
const { i18n } = useTranslation()
const editorRef = useRef(null)
const toolbarRef = useRef(null)
@@ -184,7 +179,7 @@ const RichTextField: React.FC<
path={path}
schemaPath={schemaPath}
>
{Element}
<RenderComponent mappedComponent={Element} />
</ElementProvider>
)
@@ -217,7 +212,7 @@ const RichTextField: React.FC<
result={result}
schemaPath={schemaPath}
>
{Leaf}
<RenderComponent mappedComponent={Leaf} />
</LeafProvider>
)
}
@@ -321,14 +316,9 @@ const RichTextField: React.FC<
width,
}}
>
<FieldLabel
CustomLabel={CustomLabel}
label={label}
required={required}
{...(labelProps || {})}
/>
<FieldLabel Label={Label} label={label} required={required} {...(labelProps || {})} />
<div className={`${baseClass}__wrap`}>
<FieldError CustomError={CustomError} path={path} {...(errorProps || {})} />
<FieldError CustomError={Error} path={path} {...(errorProps || {})} />
<Slate
editor={editor}
key={JSON.stringify({ initialValue, path })} // makes sure slate is completely re-rendered when initialValue changes, bypassing the slate-internal value memoization. That way, external changes to the form will update the editor
@@ -356,7 +346,7 @@ const RichTextField: React.FC<
path={path}
schemaPath={schemaPath}
>
{Button}
<RenderComponent mappedComponent={Button} />
</ElementButtonProvider>
)
}
@@ -374,7 +364,7 @@ const RichTextField: React.FC<
path={path}
schemaPath={schemaPath}
>
{Button}
<RenderComponent mappedComponent={Button} />
</LeafButtonProvider>
)
}
@@ -459,11 +449,7 @@ const RichTextField: React.FC<
</div>
</div>
</Slate>
{CustomDescription !== undefined ? (
CustomDescription
) : (
<FieldDescription {...(descriptionProps || {})} />
)}
<FieldDescription Description={Description} {...(descriptionProps || {})} />
</div>
</div>
)

View File

@@ -1,7 +1,9 @@
import type { MappedComponent } from 'payload'
import type { EnabledFeatures } from './types.js'
export const createFeatureMap = (
richTextComponentMap: Map<string, React.ReactNode>,
richTextComponentMap: Map<string, MappedComponent>,
): EnabledFeatures => {
const features: EnabledFeatures = {
elements: {},

View File

@@ -32,7 +32,9 @@ const filterRichTextCollections: FilteredCollectionsT = (collections, options) =
export const EnabledRelationshipsCondition: React.FC<any> = (props) => {
const { children, uploads = false, ...rest } = props
const { collections } = useConfig()
const {
config: { collections },
} = useConfig()
const { user } = useAuth()
const { visibleEntities } = useEntityVisibility()

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { BlockquoteIcon } from '../../icons/Blockquote/index.js'
import { ElementButton } from '../Button.js'
export const BlockquoteElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<BlockquoteIcon />
</ElementButton>
)

View File

@@ -5,7 +5,7 @@ import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import './index.scss'
export const Blockquote = () => {
export const BlockquoteElement = () => {
const { attributes, children } = useElement()
return (

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { BlockquoteIcon } from '../../icons/Blockquote/index.js'
import { ElementButton } from '../Button.js'
import { Blockquote } from './Blockquote.js'
const name = 'blockquote'
export const blockquote: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<BlockquoteIcon />
</ElementButton>
),
Element: Blockquote,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#BlockquoteElementButton',
},
Element: '@payloadcms/richtext-slate/client#BlockquoteElement',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H1Icon } from '../../icons/headings/H1/index.js'
import { ElementButton } from '../Button.js'
export const H1ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H1Icon />
</ElementButton>
)

View File

@@ -4,7 +4,7 @@ import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
export const Heading1 = () => {
export const Heading1Element = () => {
const { attributes, children } = useElement()
return <h1 {...attributes}>{children}</h1>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H1Icon } from '../../icons/headings/H1/index.js'
import { ElementButton } from '../Button.js'
import { Heading1 } from './Heading1.js'
const name = 'h1'
export const h1: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H1Icon />
</ElementButton>
),
Element: Heading1,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H1ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading1Element',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H2Icon } from '../../icons/headings/H2/index.js'
import { ElementButton } from '../Button.js'
export const H2ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H2Icon />
</ElementButton>
)

View File

@@ -4,7 +4,7 @@ import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
export const Heading2 = () => {
export const Heading2Element = () => {
const { attributes, children } = useElement()
return <h2 {...attributes}>{children}</h2>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H2Icon } from '../../icons/headings/H2/index.js'
import { ElementButton } from '../Button.js'
import { Heading2 } from './Heading2.js'
const name = 'h2'
export const h2: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H2Icon />
</ElementButton>
),
Element: Heading2,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H2ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading2Element',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H3Icon } from '../../icons/headings/H3/index.js'
import { ElementButton } from '../Button.js'
export const H3ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H3Icon />
</ElementButton>
)

View File

@@ -3,8 +3,9 @@
import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import { Heading2Element } from '../h2/Heading2.js'
export const Heading3 = () => {
export const Heading3Element = () => {
const { attributes, children } = useElement()
return <h3 {...attributes}>{children}</h3>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H3Icon } from '../../icons/headings/H3/index.js'
import { ElementButton } from '../Button.js'
import { Heading3 } from './Heading3.js'
const name = 'h3'
export const h3: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H3Icon />
</ElementButton>
),
Element: Heading3,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H3ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading3Element',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H4Icon } from '../../icons/headings/H4/index.js'
import { ElementButton } from '../Button.js'
export const H4ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H4Icon />
</ElementButton>
)

View File

@@ -3,8 +3,9 @@
import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import { Heading2Element } from '../h2/Heading2.js'
export const Heading4 = () => {
export const Heading4Element = () => {
const { attributes, children } = useElement()
return <h4 {...attributes}>{children}</h4>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H4Icon } from '../../icons/headings/H4/index.js'
import { ElementButton } from '../Button.js'
import { Heading4 } from './Heading4.js'
const name = 'h4'
export const h4: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H4Icon />
</ElementButton>
),
Element: Heading4,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H4ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading4Element',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H5Icon } from '../../icons/headings/H5/index.js'
import { ElementButton } from '../Button.js'
export const H5ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H5Icon />
</ElementButton>
)

View File

@@ -3,8 +3,9 @@
import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import { Heading2Element } from '../h2/Heading2.js'
export const Heading5 = () => {
export const Heading5Element = () => {
const { attributes, children } = useElement()
return <h5 {...attributes}>{children}</h5>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H5Icon } from '../../icons/headings/H5/index.js'
import { ElementButton } from '../Button.js'
import { Heading5 } from './Heading5.js'
const name = 'h5'
export const h5: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H5Icon />
</ElementButton>
),
Element: Heading5,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H5ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading5Element',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { H6Icon } from '../../icons/headings/H6/index.js'
import { ElementButton } from '../Button.js'
export const H6ElementButton = ({ format }: { format: string }) => (
<ElementButton format={format}>
<H6Icon />
</ElementButton>
)

View File

@@ -3,8 +3,9 @@
import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import { Heading2Element } from '../h2/Heading2.js'
export const Heading6 = () => {
export const Heading6Element = () => {
const { attributes, children } = useElement()
return <h6 {...attributes}>{children}</h6>

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { H6Icon } from '../../icons/headings/H6/index.js'
import { ElementButton } from '../Button.js'
import { Heading6 } from './Heading6.js'
const name = 'h6'
export const h6: RichTextCustomElement = {
name,
Button: () => (
<ElementButton format={name}>
<H6Icon />
</ElementButton>
),
Element: Heading6,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#H6ElementButton',
},
Element: '@payloadcms/richtext-slate/client#Heading6Element',
}

View File

@@ -1,11 +1,9 @@
import type { RichTextCustomElement } from '../../../types.js'
import { IndentButton } from './Button.js'
import { IndentElement } from './Element.js'
import { indentType } from './shared.js'
export const indent: RichTextCustomElement = {
name: indentType,
Button: IndentButton,
Element: IndentElement,
Button: '@payloadcms/richtext-slate/client#IndentButton',
Element: '@payloadcms/richtext-slate/client#IndentElement',
}

View File

@@ -1,8 +1,6 @@
import type { RichTextCustomElement } from '../../../types.js'
import { ListItemElement } from './ListItem.js'
export const li: RichTextCustomElement = {
name: 'li',
Element: ListItemElement,
Element: '@payloadcms/richtext-slate/client#ListItemElement',
}

View File

@@ -61,15 +61,17 @@ export const LinkButton: React.FC = () => {
const { t } = useTranslation()
const editor = useSlate()
const config = useConfig()
const { config } = useConfig()
const { closeModal, openModal } = useModal()
const drawerSlug = useDrawerSlug('rich-text-link')
const { schemaPath } = useFieldProps()
const { richTextComponentMap } = fieldProps
const {
field: { richTextComponentMap },
} = fieldProps
const fieldMap = richTextComponentMap.get(linkFieldsSchemaPath)
const fields = richTextComponentMap.get(linkFieldsSchemaPath)
return (
<Fragment>
@@ -82,10 +84,12 @@ export const LinkButton: React.FC = () => {
} else {
openModal(drawerSlug)
const isCollapsed = editor.selection && Range.isCollapsed(editor.selection)
if (!isCollapsed) {
const data = {
text: editor.selection ? Editor.string(editor, editor.selection) : '',
}
const state = await getFormState({
apiRoute: config.routes.api,
body: {
@@ -95,6 +99,7 @@ export const LinkButton: React.FC = () => {
},
serverURL: config.serverURL,
})
setInitialState(state)
}
}
@@ -105,7 +110,7 @@ export const LinkButton: React.FC = () => {
</ElementButton>
<LinkDrawer
drawerSlug={drawerSlug}
fieldMap={Array.isArray(fieldMap) ? fieldMap : []}
fields={Array.isArray(fields) ? fields : []}
handleClose={() => {
closeModal(drawerSlug)
}}

View File

@@ -63,11 +63,13 @@ export const LinkElement = () => {
const fieldMapPath = `${schemaPath}.${linkFieldsSchemaPath}`
const { richTextComponentMap } = fieldProps
const fieldMap = richTextComponentMap.get(linkFieldsSchemaPath)
const {
field: { richTextComponentMap },
} = fieldProps
const fields = richTextComponentMap.get(linkFieldsSchemaPath)
const editor = useSlate()
const config = useConfig()
const { config } = useConfig()
const { user } = useAuth()
const { code: locale } = useLocale()
const { i18n, t } = useTranslation()
@@ -120,7 +122,7 @@ export const LinkElement = () => {
{renderModal && (
<LinkDrawer
drawerSlug={drawerSlug}
fieldMap={Array.isArray(fieldMap) ? fieldMap : []}
fields={Array.isArray(fields) ? fields : []}
handleClose={() => {
toggleModal(drawerSlug)
setRenderModal(false)

View File

@@ -26,7 +26,7 @@ const baseClass = 'rich-text-link-edit-modal'
export const LinkDrawer: React.FC<Props> = ({
drawerSlug,
fieldMap,
fields,
handleModalSubmit,
initialState,
}) => {
@@ -34,7 +34,7 @@ export const LinkDrawer: React.FC<Props> = ({
const { schemaPath } = useFieldProps()
const fieldMapPath = `${schemaPath}.${linkFieldsSchemaPath}`
const { id } = useDocumentInfo()
const config = useConfig()
const { config } = useConfig()
const onChange: FormProps['onChange'][0] = useCallback(
async ({ formState: prevFormState }) => {
@@ -62,7 +62,7 @@ export const LinkDrawer: React.FC<Props> = ({
onChange={[onChange]}
onSubmit={handleModalSubmit}
>
<RenderFields fieldMap={fieldMap} forceRender path="" readOnly={false} schemaPath="" />
<RenderFields fields={fields} forceRender path="" readOnly={false} schemaPath="" />
<LinkSubmit />
</Form>
</Drawer>

View File

@@ -1,9 +1,9 @@
import type { FieldMap, FormState } from 'payload'
import type { ClientField, FormState } from 'payload'
export type Props = {
drawerSlug: string
fieldMap: FieldMap
handleClose: () => void
handleModalSubmit: (fields: FormState, data: Record<string, unknown>) => void
initialState?: FormState
readonly drawerSlug: string
readonly fields: ClientField[]
readonly handleClose: () => void
readonly handleModalSubmit: (fields: FormState, data: Record<string, unknown>) => void
readonly initialState?: FormState
}

View File

@@ -1,12 +1,8 @@
import type { RichTextCustomElement } from '../../../types.js'
import { LinkButton } from './Button/index.js'
import { LinkElement } from './Element/index.js'
import { WithLinks } from './WithLinks.js'
export const link: RichTextCustomElement = {
name: 'link',
Button: LinkButton,
Element: LinkElement,
plugins: [WithLinks],
Button: '@payloadcms/richtext-slate/client#LinkButton',
Element: '@payloadcms/richtext-slate/client#LinkElement',
plugins: ['@payloadcms/richtext-slate/client#WithLinks'],
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { OLIcon } from '../../icons/OrderedList/index.js'
import { ListButton } from '../ListButton.js'
export const OLElementButton = ({ format }: { format: string }) => (
<ListButton format={format}>
<OLIcon />
</ListButton>
)

View File

@@ -5,7 +5,7 @@ import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import './index.scss'
export const OrderedList: React.FC = () => {
export const OrderedListElement: React.FC = () => {
const { attributes, children } = useElement()
return (

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { OLIcon } from '../../icons/OrderedList/index.js'
import { ListButton } from '../ListButton.js'
import { OrderedList } from './OrderedList.js'
const name = 'ol'
export const ol: RichTextCustomElement = {
name,
Button: () => (
<ListButton format={name}>
<OLIcon />
</ListButton>
),
Element: OrderedList,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#OLElementButton',
},
Element: '@payloadcms/richtext-slate/client#OrderedListElement',
}

View File

@@ -31,7 +31,7 @@ type Props = {
enabledCollectionSlugs: string[]
path: string
}
const RelationshipButton: React.FC<Props> = ({ enabledCollectionSlugs }) => {
const RelationshipButtonComponent: React.FC<Props> = ({ enabledCollectionSlugs }) => {
const { t } = useTranslation()
const editor = useSlate()
const [selectedCollectionSlug, setSelectedCollectionSlug] = useState(
@@ -81,10 +81,10 @@ const RelationshipButton: React.FC<Props> = ({ enabledCollectionSlugs }) => {
)
}
export const Button = (props: Props): React.ReactNode => {
export const RelationshipButton = (props: Props): React.ReactNode => {
return (
<EnabledRelationshipsCondition {...props}>
<RelationshipButton {...props} />
<RelationshipButtonComponent {...props} />
</EnabledRelationshipsCondition>
)
}

View File

@@ -1,6 +1,6 @@
'use client'
import type { FormFieldBase } from 'payload'
import type { FormFieldBase, MappedComponent } from 'payload'
import { getTranslation } from '@payloadcms/translations'
import {
@@ -29,10 +29,10 @@ const initialParams = {
type Props = {
name: string
richTextComponentMap: Map<string, React.ReactNode>
richTextComponentMap: Map<string, MappedComponent>
} & FormFieldBase
const RelationshipElement: React.FC<Props> = () => {
const RelationshipElementComponent: React.FC<Props> = () => {
const {
attributes,
children,
@@ -42,9 +42,11 @@ const RelationshipElement: React.FC<Props> = () => {
} = useElement<RelationshipElementType>()
const {
collections,
routes: { api },
serverURL,
config: {
collections,
routes: { api },
serverURL,
},
} = useConfig()
const [enabledCollectionSlugs] = useState(() =>
collections
@@ -158,11 +160,11 @@ const RelationshipElement: React.FC<Props> = () => {
<div className={`${baseClass}__actions`}>
<ListDrawerToggler
className={`${baseClass}__list-drawer-toggler`}
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
>
<Button
buttonStyle="icon-label"
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
el="div"
icon="swap"
onClick={() => {
@@ -175,7 +177,7 @@ const RelationshipElement: React.FC<Props> = () => {
<Button
buttonStyle="icon-label"
className={`${baseClass}__removeButton`}
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
icon="x"
onClick={(e) => {
e.preventDefault()
@@ -192,10 +194,10 @@ const RelationshipElement: React.FC<Props> = () => {
)
}
export const Element = (props: Props): React.ReactNode => {
export const RelationshipElement = (props: Props): React.ReactNode => {
return (
<EnabledRelationshipsCondition {...props}>
<RelationshipElement {...props} />
<RelationshipElementComponent {...props} />
</EnabledRelationshipsCondition>
)
}

View File

@@ -1,13 +1,10 @@
import type { RichTextCustomElement } from '../../../types.js'
import { Button } from './Button/index.js'
import { Element } from './Element/index.js'
import { WithRelationship } from './plugin.js'
import { relationshipName } from './shared.js'
export const relationship: RichTextCustomElement = {
name: relationshipName,
Button,
Element,
plugins: [WithRelationship],
Button: '@payloadcms/richtext-slate/client#RelationshipButton',
Element: '@payloadcms/richtext-slate/client#RelationshipElement',
plugins: ['@payloadcms/richtext-slate/client#WithRelationship'],
}

View File

@@ -0,0 +1,21 @@
'use client'
import React from 'react'
import { AlignCenterIcon } from '../../icons/AlignCenter/index.js'
import { AlignLeftIcon } from '../../icons/AlignLeft/index.js'
import { AlignRightIcon } from '../../icons/AlignRight/index.js'
import { ElementButton } from '../Button.js'
export const TextAlignElementButton = () => (
<React.Fragment>
<ElementButton format="left" type="textAlign">
<AlignLeftIcon />
</ElementButton>
<ElementButton format="center" type="textAlign">
<AlignCenterIcon />
</ElementButton>
<ElementButton format="right" type="textAlign">
<AlignRightIcon />
</ElementButton>
</React.Fragment>
)

View File

@@ -1,28 +1,7 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { AlignCenterIcon } from '../../icons/AlignCenter/index.js'
import { AlignLeftIcon } from '../../icons/AlignLeft/index.js'
import { AlignRightIcon } from '../../icons/AlignRight/index.js'
import { ElementButton } from '../Button.js'
export const textAlign: RichTextCustomElement = {
name: 'alignment',
Button: () => {
return (
<React.Fragment>
<ElementButton format="left" type="textAlign">
<AlignLeftIcon />
</ElementButton>
<ElementButton format="center" type="textAlign">
<AlignCenterIcon />
</ElementButton>
<ElementButton format="right" type="textAlign">
<AlignRightIcon />
</ElementButton>
</React.Fragment>
)
},
Element: () => null,
Button: '@payloadcms/richtext-slate/client#TextAlignElementButton',
Element: '@payloadcms/ui/shared#emptyComponent',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { ULIcon } from '../../icons/UnorderedList/index.js'
import { ListButton } from '../ListButton.js'
export const ULElementButton = ({ format }: { format: string }) => (
<ListButton format={format}>
<ULIcon />
</ListButton>
)

View File

@@ -5,7 +5,7 @@ import React from 'react'
import { useElement } from '../../providers/ElementProvider.js'
import './index.scss'
export const UnorderedList: React.FC = () => {
export const UnorderedListElement: React.FC = () => {
const { attributes, children } = useElement()
return (

View File

@@ -1,19 +1,14 @@
import React from 'react'
import type { RichTextCustomElement } from '../../../types.js'
import { ULIcon } from '../../icons/UnorderedList/index.js'
import { ListButton } from '../ListButton.js'
import { UnorderedList } from './UnorderedList.js'
const name = 'ul'
export const ul: RichTextCustomElement = {
name,
Button: () => (
<ListButton format={name}>
<ULIcon />
</ListButton>
),
Element: UnorderedList,
Button: {
clientProps: {
format: name,
},
path: '@payloadcms/richtext-slate/client#ULElementButton',
},
Element: '@payloadcms/richtext-slate/client#UnorderedListElement',
}

View File

@@ -74,7 +74,7 @@ const UploadButton: React.FC<ButtonProps> = ({ enabledCollectionSlugs }) => {
)
}
export const Button = (props: ButtonProps): React.ReactNode => {
export const UploadElementButton = (props: ButtonProps): React.ReactNode => {
return (
<EnabledRelationshipsCondition {...props} uploads>
<UploadButton {...props} />

View File

@@ -1,7 +1,7 @@
'use client'
import type { FormProps } from '@payloadcms/ui'
import type { ClientCollectionConfig, FormFieldBase } from 'payload'
import type { ClientCollectionConfig } from 'payload'
import { getTranslation } from '@payloadcms/translations'
import {
@@ -22,19 +22,17 @@ import React, { useCallback, useEffect, useState } from 'react'
import { Transforms } from 'slate'
import { ReactEditor, useSlateStatic } from 'slate-react'
import type { LoadedSlateFieldProps } from '../../../../types.js'
import type { UploadElementType } from '../../types.js'
import { uploadFieldsSchemaPath } from '../../shared.js'
export const UploadDrawer: React.FC<{
drawerSlug: string
element: UploadElementType
fieldProps: {
name: string
richTextComponentMap: Map<string, React.ReactNode>
} & FormFieldBase
relatedCollection: ClientCollectionConfig
schemaPath: string
readonly drawerSlug: string
readonly element: UploadElementType
readonly fieldProps: LoadedSlateFieldProps
readonly relatedCollection: ClientCollectionConfig
readonly schemaPath: string
}> = (props) => {
const editor = useSlateStatic()
@@ -46,12 +44,14 @@ export const UploadDrawer: React.FC<{
const { closeModal } = useModal()
const { id, collectionSlug } = useDocumentInfo()
const [initialState, setInitialState] = useState({})
const { richTextComponentMap } = fieldProps
const {
field: { richTextComponentMap },
} = fieldProps
const relatedFieldSchemaPath = `${uploadFieldsSchemaPath}.${relatedCollection.slug}`
const fieldMap = richTextComponentMap.get(relatedFieldSchemaPath)
const fields = richTextComponentMap.get(relatedFieldSchemaPath)
const config = useConfig()
const { config } = useConfig()
const handleUpdateEditData = useCallback(
(_, data) => {
@@ -131,7 +131,7 @@ export const UploadDrawer: React.FC<{
onSubmit={handleUpdateEditData}
>
<RenderFields
fieldMap={Array.isArray(fieldMap) ? fieldMap : []}
fields={Array.isArray(fields) ? fields : []}
path=""
readOnly={false}
schemaPath=""

View File

@@ -1,7 +1,6 @@
'use client'
import type { FormFieldBase } from 'payload'
import type { ClientCollectionConfig } from 'payload'
import type { ClientCollectionConfig, FormFieldBase } from 'payload'
import { getTranslation } from '@payloadcms/translations'
import {
@@ -38,7 +37,7 @@ type Props = {
richTextComponentMap: Map<string, React.ReactNode>
} & FormFieldBase
const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = ({
const UploadElementComponent: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = ({
enabledCollectionSlugs,
}) => {
const {
@@ -51,9 +50,11 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
} = useElement<UploadElementType>()
const {
collections,
routes: { api },
serverURL,
config: {
collections,
routes: { api },
serverURL,
},
} = useConfig()
const { i18n, t } = useTranslation()
const [cacheBust, dispatchCacheBust] = useReducer((state) => state + 1, 0)
@@ -136,7 +137,7 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
)
const relatedFieldSchemaPath = `${uploadFieldsSchemaPath}.${relatedCollection.slug}`
const customFieldsMap = fieldProps.richTextComponentMap.get(relatedFieldSchemaPath)
const customFieldsMap = fieldProps.field.richTextComponentMap.get(relatedFieldSchemaPath)
return (
<div
@@ -160,7 +161,7 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
{Boolean(customFieldsMap) && (
<DrawerToggler
className={`${baseClass}__upload-drawer-toggler`}
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
slug={drawerSlug}
>
<Button
@@ -177,11 +178,11 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
)}
<ListDrawerToggler
className={`${baseClass}__list-drawer-toggler`}
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
>
<Button
buttonStyle="icon-label"
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
el="div"
icon="swap"
onClick={() => {
@@ -194,7 +195,7 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
<Button
buttonStyle="icon-label"
className={`${baseClass}__removeButton`}
disabled={fieldProps?.readOnly}
disabled={fieldProps?.field?.admin?.readOnly}
icon="x"
onClick={(e) => {
e.preventDefault()
@@ -220,10 +221,10 @@ const UploadElement: React.FC<{ enabledCollectionSlugs?: string[] } & Props> = (
)
}
export const Element = (props: Props): React.ReactNode => {
export const UploadElement = (props: Props): React.ReactNode => {
return (
<EnabledRelationshipsCondition {...props} uploads>
<UploadElement {...props} />
<UploadElementComponent {...props} />
</EnabledRelationshipsCondition>
)
}

View File

@@ -1,13 +1,10 @@
import type { RichTextCustomElement } from '../../../types.js'
import { Button } from './Button/index.js'
import { Element } from './Element/index.js'
import { WithUpload } from './plugin.js'
import { uploadName } from './shared.js'
export const upload: RichTextCustomElement = {
name: uploadName,
Button,
Element,
plugins: [WithUpload],
Button: '@payloadcms/richtext-slate/client#UploadElementButton',
Element: '@payloadcms/richtext-slate/client#UploadElement',
plugins: ['@payloadcms/richtext-slate/client#WithUpload'],
}

View File

@@ -1,11 +1,9 @@
'use client'
import type { FormFieldBase } from 'payload'
import { ShimmerEffect, useClientFunctions, useFieldProps } from '@payloadcms/ui'
import { RenderComponent, ShimmerEffect, useClientFunctions, useFieldProps } from '@payloadcms/ui'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import type { RichTextPlugin } from '../types.js'
import type { RichTextPlugin, SlateFieldProps } from '../types.js'
import type { EnabledFeatures } from './types.js'
import { createFeatureMap } from './createFeatureMap.js'
@@ -16,20 +14,17 @@ const RichTextEditor = lazy(() =>
})),
)
export const RichTextField: React.FC<
{
name: string
richTextComponentMap: Map<string, React.ReactNode>
} & FormFieldBase
> = (props) => {
const { richTextComponentMap } = props
export const RichTextField: React.FC<SlateFieldProps> = (props) => {
const {
field: { richTextComponentMap },
} = props
const { schemaPath } = useFieldProps()
const clientFunctions = useClientFunctions()
const [hasLoadedPlugins, setHasLoadedPlugins] = useState(false)
const [features] = useState<EnabledFeatures>(() => {
return createFeatureMap(richTextComponentMap)
return createFeatureMap(richTextComponentMap as any)
})
const [plugins, setPlugins] = useState<RichTextPlugin[]>([])
@@ -56,7 +51,11 @@ export const RichTextField: React.FC<
<React.Fragment>
{Array.isArray(features.plugins) &&
features.plugins.map((Plugin, i) => {
return <React.Fragment key={i}>{Plugin}</React.Fragment>
return (
<React.Fragment key={i}>
<RenderComponent mappedComponent={Plugin} />
</React.Fragment>
)
})}
</React.Fragment>
)

View File

@@ -3,7 +3,7 @@ import React from 'react'
import { useLeaf } from '../../../providers/LeafProvider.js'
export const Bold = () => {
export const BoldLeaf = () => {
const { attributes, children } = useLeaf()
return <strong {...attributes}>{children}</strong>
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { BoldIcon } from '../../icons/Bold/index.js'
import { LeafButton } from '../Button.js'
export const BoldLeafButton = () => (
<LeafButton format="bold">
<BoldIcon />
</LeafButton>
)

View File

@@ -1,17 +1,7 @@
import React from 'react'
import type { RichTextCustomLeaf } from '../../../types.js'
import { BoldIcon } from '../../icons/Bold/index.js'
import { LeafButton } from '../Button.js'
import { Bold } from './Bold/index.js'
export const bold: RichTextCustomLeaf = {
name: 'bold',
Button: () => (
<LeafButton format="bold">
<BoldIcon />
</LeafButton>
),
Leaf: Bold,
Button: '@payloadcms/richtext-slate/client#BoldLeafButton',
Leaf: '@payloadcms/richtext-slate/client#BoldLeaf',
}

View File

@@ -3,7 +3,7 @@ import React from 'react'
import { useLeaf } from '../../../providers/LeafProvider.js'
export const Code = () => {
export const CodeLeaf = () => {
const { attributes, children } = useLeaf()
return <code {...attributes}>{children}</code>
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { CodeIcon } from '../../icons/Code/index.js'
import { LeafButton } from '../Button.js'
export const CodeLeafButton = () => (
<LeafButton format="code">
<CodeIcon />
</LeafButton>
)

View File

@@ -1,17 +1,7 @@
import React from 'react'
import type { RichTextCustomLeaf } from '../../../types.js'
import { CodeIcon } from '../../icons/Code/index.js'
import { LeafButton } from '../Button.js'
import { Code } from './Code/index.js'
export const code: RichTextCustomLeaf = {
name: 'code',
Button: () => (
<LeafButton format="code">
<CodeIcon />
</LeafButton>
),
Leaf: Code,
Button: '@payloadcms/richtext-slate/client#CodeLeafButton',
Leaf: '@payloadcms/richtext-slate/client#CodeLeaf',
}

View File

@@ -3,7 +3,7 @@ import React from 'react'
import { useLeaf } from '../../../providers/LeafProvider.js'
export const Italic = () => {
export const ItalicLeaf = () => {
const { attributes, children } = useLeaf()
return <em {...attributes}>{children}</em>
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { ItalicIcon } from '../../icons/Italic/index.js'
import { LeafButton } from '../Button.js'
export const ItalicLeafButton = () => (
<LeafButton format="italic">
<ItalicIcon />
</LeafButton>
)

View File

@@ -1,17 +1,7 @@
import React from 'react'
import type { RichTextCustomLeaf } from '../../../types.js'
import { ItalicIcon } from '../../icons/Italic/index.js'
import { LeafButton } from '../Button.js'
import { Italic } from './Italic/index.js'
export const italic: RichTextCustomLeaf = {
name: 'italic',
Button: () => (
<LeafButton format="italic">
<ItalicIcon />
</LeafButton>
),
Leaf: Italic,
Button: '@payloadcms/richtext-slate/client#ItalicLeafButton',
Leaf: '@payloadcms/richtext-slate/client#ItalicLeaf',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { StrikethroughIcon } from '../../icons/Strikethrough/index.js'
import { LeafButton } from '../Button.js'
export const StrikethroughLeafButton = () => (
<LeafButton format="strikethrough">
<StrikethroughIcon />
</LeafButton>
)

View File

@@ -3,7 +3,7 @@ import React from 'react'
import { useLeaf } from '../../../providers/LeafProvider.js'
export const Strikethrough = () => {
export const StrikethroughLeaf = () => {
const { attributes, children } = useLeaf()
return <del {...attributes}>{children}</del>
}

View File

@@ -1,17 +1,7 @@
import React from 'react'
import type { RichTextCustomLeaf } from '../../../types.js'
import { StrikethroughIcon } from '../../icons/Strikethrough/index.js'
import { LeafButton } from '../Button.js'
import { Strikethrough } from './Strikethrough/index.js'
export const strikethrough: RichTextCustomLeaf = {
name: 'strikethrough',
Button: () => (
<LeafButton format="strikethrough">
<StrikethroughIcon />
</LeafButton>
),
Leaf: Strikethrough,
Button: '@payloadcms/richtext-slate/client#StrikethroughLeafButton',
Leaf: '@payloadcms/richtext-slate/client#StrikethroughLeaf',
}

View File

@@ -0,0 +1,11 @@
'use client'
import React from 'react'
import { UnderlineIcon } from '../../icons/Underline/index.js'
import { LeafButton } from '../Button.js'
export const UnderlineLeafButton = () => (
<LeafButton format="underline">
<UnderlineIcon />
</LeafButton>
)

View File

@@ -3,7 +3,7 @@ import React from 'react'
import { useLeaf } from '../../../providers/LeafProvider.js'
export const Underline = () => {
export const UnderlineLeaf = () => {
const { attributes, children } = useLeaf()
return <u {...attributes}>{children}</u>
}

View File

@@ -1,17 +1,7 @@
import React from 'react'
import type { RichTextCustomLeaf } from '../../../types.js'
import { UnderlineIcon } from '../../icons/Underline/index.js'
import { LeafButton } from '../Button.js'
import { Underline } from './Underline/index.js'
export const underline: RichTextCustomLeaf = {
name: 'underline',
Button: () => (
<LeafButton format="underline">
<UnderlineIcon />
</LeafButton>
),
Leaf: Underline,
Button: '@payloadcms/richtext-slate/client#UnderlineLeafButton',
Leaf: '@payloadcms/richtext-slate/client#UnderlineLeaf',
}

View File

@@ -1,15 +1,12 @@
'use client'
import type { FormFieldBase } from 'payload'
import React from 'react'
import type { LoadedSlateFieldProps } from '../types.js'
type ElementButtonContextType = {
disabled?: boolean
fieldProps: {
name: string
richTextComponentMap: Map<string, React.ReactNode>
} & FormFieldBase
fieldProps: LoadedSlateFieldProps
path: string
schemaPath: string
}

View File

@@ -1,18 +1,16 @@
'use client'
import type { FormFieldBase } from 'payload'
import type { Element } from 'slate'
import React from 'react'
import type { LoadedSlateFieldProps } from '../types.js'
type ElementContextType<T> = {
attributes: Record<string, unknown>
children: React.ReactNode
editorRef: React.MutableRefObject<HTMLDivElement>
editorRef: React.RefObject<HTMLDivElement>
element: T
fieldProps: {
name: string
richTextComponentMap: Map<string, React.ReactNode>
} & FormFieldBase
fieldProps: LoadedSlateFieldProps
path: string
schemaPath: string
}

View File

@@ -1,13 +1,11 @@
'use client'
import type { FormFieldBase } from 'payload'
import React from 'react'
import type { LoadedSlateFieldProps } from '../types.js'
type LeafButtonContextType = {
fieldProps: {
name: string
} & FormFieldBase
fieldProps: LoadedSlateFieldProps
path: string
schemaPath: string
}

View File

@@ -1,16 +1,14 @@
'use client'
import type { FormFieldBase } from 'payload'
import React from 'react'
import type { LoadedSlateFieldProps } from '../types.js'
type LeafContextType = {
attributes: Record<string, unknown>
children: React.ReactNode
editorRef: React.MutableRefObject<HTMLDivElement>
fieldProps: {
name: string
} & FormFieldBase
editorRef: React.RefObject<HTMLDivElement>
fieldProps: LoadedSlateFieldProps
leaf: string
path: string
schemaPath: string

View File

@@ -1,17 +1,27 @@
import type { MappedComponent } from 'payload'
import type { RichTextPlugin, SlateFieldProps } from '../types.js'
export type EnabledFeatures = {
elements: {
[name: string]: {
Button: React.ReactNode
Element: React.ReactNode
Button: MappedComponent
Element: MappedComponent
name: string
}
}
leaves: {
[name: string]: {
Button: React.ReactNode
Leaf: React.ReactNode
Button: MappedComponent
Leaf: MappedComponent
name: string
}
}
plugins: React.ReactNode[]
plugins: MappedComponent[]
}
export type LoadedSlateFieldProps = {
elements: EnabledFeatures['elements']
leaves: EnabledFeatures['leaves']
plugins: RichTextPlugin[]
} & SlateFieldProps

View File

@@ -1,7 +1,7 @@
import type { Field, RichTextAdapter } from 'payload'
import type { ClientField, Field, MappedComponent, RichTextGenerateComponentMap } from 'payload'
import { mapFields } from '@payloadcms/ui/utilities/buildComponentMap'
import React from 'react'
import { createClientFields } from '@payloadcms/ui/utilities/createClientConfig'
import { deepCopyObjectSimple } from 'payload'
import type { AdapterArguments, RichTextCustomElement, RichTextCustomLeaf } from './types.js'
@@ -11,9 +11,9 @@ import { uploadFieldsSchemaPath } from './field/elements/upload/shared.js'
import { defaultLeaves as leafTypes } from './field/leaves/index.js'
export const getGenerateComponentMap =
(args: AdapterArguments): RichTextAdapter['generateComponentMap'] =>
({ WithServerSideProps, config, i18n, payload }) => {
const componentMap = new Map()
(args: AdapterArguments): RichTextGenerateComponentMap =>
({ createMappedComponent, i18n, importMap, payload }) => {
const componentMap: Map<string, ClientField[] | MappedComponent> = new Map()
;(args?.admin?.leaves || Object.values(leafTypes)).forEach((leaf) => {
let leafObject: RichTextCustomLeaf
@@ -28,12 +28,22 @@ export const getGenerateComponentMap =
const LeafButton = leafObject.Button
const LeafComponent = leafObject.Leaf
componentMap.set(`leaf.button.${leafObject.name}`, <LeafButton />)
componentMap.set(`leaf.component.${leafObject.name}`, <LeafComponent />)
componentMap.set(
`leaf.button.${leafObject.name}`,
createMappedComponent(LeafButton, undefined, undefined, 'slate-LeafButton'),
)
componentMap.set(
`leaf.component.${leafObject.name}`,
createMappedComponent(LeafComponent, undefined, undefined, 'slate-LeafComponent'),
)
if (Array.isArray(leafObject.plugins)) {
leafObject.plugins.forEach((Plugin, i) => {
componentMap.set(`leaf.plugin.${leafObject.name}.${i}`, <Plugin />)
componentMap.set(
`leaf.plugin.${leafObject.name}.${i}`,
createMappedComponent(Plugin, undefined, undefined, 'slate-LeafPlugin'),
)
})
}
}
@@ -51,33 +61,46 @@ export const getGenerateComponentMap =
const ElementButton = element.Button
const ElementComponent = element.Element
if (ElementButton) componentMap.set(`element.button.${element.name}`, <ElementButton />)
componentMap.set(`element.component.${element.name}`, <ElementComponent />)
if (ElementButton)
componentMap.set(
`element.button.${element.name}`,
createMappedComponent(ElementButton, undefined, undefined, 'slate-ElementButton'),
)
componentMap.set(
`element.component.${element.name}`,
createMappedComponent(ElementComponent, undefined, undefined, 'slate-ElementComponent'),
)
if (Array.isArray(element.plugins)) {
element.plugins.forEach((Plugin, i) => {
componentMap.set(`element.plugin.${element.name}.${i}`, <Plugin />)
componentMap.set(
`element.plugin.${element.name}.${i}`,
createMappedComponent(Plugin, undefined, undefined, 'slate-ElementPlugin'),
)
})
}
switch (element.name) {
case 'link': {
const mappedFields = mapFields({
WithServerSideProps,
config,
fieldSchema: args.admin?.link?.fields as Field[],
let clientFields = deepCopyObjectSimple(
args.admin?.link?.fields,
) as unknown as ClientField[]
clientFields = createClientFields({
clientFields,
createMappedComponent,
fields: args.admin?.link?.fields as Field[],
i18n,
importMap,
payload,
readOnly: false,
})
componentMap.set(linkFieldsSchemaPath, mappedFields)
componentMap.set(linkFieldsSchemaPath, clientFields)
break
}
case 'upload': {
const uploadEnabledCollections = config.collections.filter(
const uploadEnabledCollections = payload.config.collections.filter(
({ admin: { enableRichTextRelationship, hidden }, upload }) => {
if (hidden === true) {
return false
@@ -89,16 +112,19 @@ export const getGenerateComponentMap =
uploadEnabledCollections.forEach((collection) => {
if (args?.admin?.upload?.collections[collection.slug]?.fields) {
const mappedFields = mapFields({
WithServerSideProps,
config,
fieldSchema: args?.admin?.upload?.collections[collection.slug]?.fields,
let clientFields = deepCopyObjectSimple(
args?.admin?.upload?.collections[collection.slug]?.fields,
) as unknown as ClientField[]
clientFields = createClientFields({
clientFields,
createMappedComponent,
fields: args?.admin?.upload?.collections[collection.slug]?.fields,
i18n,
importMap,
payload,
readOnly: false,
})
componentMap.set(`${uploadFieldsSchemaPath}.${collection.slug}`, mappedFields)
componentMap.set(`${uploadFieldsSchemaPath}.${collection.slug}`, clientFields)
}
})

View File

@@ -4,12 +4,11 @@ import { sanitizeFields, withNullableJSONSchemaType } from 'payload'
import type { AdapterArguments } from './types.js'
import { RichTextCell } from './cell/index.js'
import { richTextRelationshipPromise } from './data/richTextRelationshipPromise.js'
import { richTextValidate } from './data/validation.js'
import { elements as elementTypes } from './field/elements/index.js'
import { transformExtraFields } from './field/elements/link/utilities.js'
import { RichTextField } from './field/index.js'
import { getGenerateComponentMap } from './generateComponentMap.js'
import { defaultLeaves as leafTypes } from './field/leaves/index.js'
import { getGenerateSchemaMap } from './generateSchemaMap.js'
export function slateEditor(
@@ -46,9 +45,67 @@ export function slateEditor(
}
return {
CellComponent: RichTextCell,
FieldComponent: RichTextField,
generateComponentMap: getGenerateComponentMap(args),
CellComponent: '@payloadcms/richtext-slate/client#RichTextCell',
FieldComponent: '@payloadcms/richtext-slate/client#RichTextField',
generateComponentMap: {
path: '@payloadcms/richtext-slate/generateComponentMap#getGenerateComponentMap',
serverProps: args,
},
generateImportMap: ({ addToImportMap }) => {
addToImportMap('@payloadcms/richtext-slate/client#RichTextCell')
addToImportMap('@payloadcms/richtext-slate/client#RichTextField')
addToImportMap('@payloadcms/richtext-slate/generateComponentMap#getGenerateComponentMap')
Object.values(leafTypes).forEach((leaf) => {
if (leaf.Button) {
addToImportMap(leaf.Button)
}
if (leaf.Leaf) {
addToImportMap(leaf.Leaf)
}
if (Array.isArray(leaf.plugins) && leaf.plugins?.length) {
addToImportMap(leaf.plugins)
}
})
args?.admin?.leaves?.forEach((leaf) => {
if (typeof leaf === 'object') {
if (leaf.Button) {
addToImportMap(leaf.Button)
}
if (leaf.Leaf) {
addToImportMap(leaf.Leaf)
}
if (Array.isArray(leaf.plugins) && leaf.plugins?.length) {
addToImportMap(leaf.plugins)
}
}
})
Object.values(elementTypes).forEach((element) => {
if (element.Button) {
addToImportMap(element.Button)
}
if (element.Element) {
addToImportMap(element.Element)
}
if (Array.isArray(element.plugins) && element.plugins?.length) {
addToImportMap(element.plugins)
}
})
args?.admin?.elements?.forEach((element) => {
if (typeof element === 'object') {
if (element.Button) {
addToImportMap(element.Button)
}
if (element.Element) {
addToImportMap(element.Element)
}
if (Array.isArray(element.plugins) && element.plugins?.length) {
addToImportMap(element.plugins)
}
}
})
},
generateSchemaMap: getGenerateSchemaMap(args),
graphQLPopulationPromises({
context,
@@ -145,20 +202,16 @@ export function slateEditor(
}
}
export { ElementButton } from './field/elements/Button.js'
export { toggleElement } from './field/elements/toggle.js'
export { LeafButton } from './field/leaves/Button.js'
export { useLeaf } from './field/providers/LeafProvider.js'
export type {
AdapterArguments,
ElementNode,
FieldProps,
RichTextCustomElement,
RichTextCustomLeaf,
RichTextElement,
RichTextLeaf,
RichTextPlugin,
RichTextPluginComponent,
SlateFieldProps,
TextNode,
} from './types.js'

View File

@@ -1,4 +1,4 @@
import type { Field, RichTextFieldProps, SanitizedConfig } from 'payload'
import type { Field, PayloadComponent, RichTextFieldProps, SanitizedConfig } from 'payload'
import type { Editor } from 'slate'
export type TextNode = { [x: string]: unknown; text: string }
@@ -9,19 +9,19 @@ export function nodeIsTextNode(node: ElementNode | TextNode): node is TextNode {
return 'text' in node
}
export type RichTextPluginComponent = React.ComponentType
export type RichTextPluginComponent = PayloadComponent
export type RichTextPlugin = (editor: Editor) => Editor
export type RichTextCustomElement = {
Button?: React.ComponentType<any>
Element: React.ComponentType<any>
Button?: PayloadComponent
Element: PayloadComponent
name: string
plugins?: RichTextPluginComponent[]
}
export type RichTextCustomLeaf = {
Button: React.ComponentType<any>
Leaf: React.ComponentType<any>
Button: PayloadComponent
Leaf: PayloadComponent
name: string
plugins?: RichTextPluginComponent[]
}
@@ -70,4 +70,4 @@ export type AdapterArguments = {
}
}
export type FieldProps = RichTextFieldProps<any[], AdapterArguments, AdapterArguments>
export type SlateFieldProps = RichTextFieldProps<any[], AdapterArguments, AdapterArguments>