Compare commits

...

63 Commits

Author SHA1 Message Date
Elliot DeNolf
763ccdcf00 chore(release): eslint/3.0.0 2024-11-18 20:39:54 -05:00
Elliot DeNolf
76286136ba chore(cpa): update init next to use latest 2024-11-18 20:29:07 -05:00
Elliot DeNolf
6145accb83 chore(templates): bump all templates to 3.0 2024-11-18 20:25:52 -05:00
Elliot DeNolf
6407e577d3 chore(release): v3.0.0 [skip ci] 2024-11-18 20:10:16 -05:00
Elliot DeNolf
7fe207937f ci: update release script for v3 2024-11-18 20:05:55 -05:00
Elliot DeNolf
cc04396a4f chore(cpa): unpin template version tag for release 2024-11-18 20:00:38 -05:00
Dan Ribbens
0d63dc9f9c chore: remove unused transaction in website seed (#9319) 2024-11-18 19:55:27 -05:00
Alessio Gravili
f7fc8a2ea0 perf(richtext-lexical): do not send default lexical editor config to client (#9318)
We can just get the default config from the client, if the server passes
undefined. This wasted bandwidth and unnecessarily increased the html
size
2024-11-18 17:28:55 -07:00
Elliot DeNolf
fade739f77 chore(release): v3.0.0-beta.135 [skip ci] 2024-11-18 19:19:55 -05:00
Said Akhrarov
1a31e63b4d fix(ui): safely accesses field in default filter component (#9276)
### What?
In the WhereBuilder Condition DefaultFilter component, there is a switch
statement that contains components to return based on the built filter
in the admin ui. Having a filter built out then navigating to another
collection list view causes an error to occur due to InternalField being
undefined but the DefaultFilter tries to access the field on it.

### Why?
To fix unexpected `cannot access property field of undefined` errors.

### How?
Adding a conditional chaining operator.

Odd thing here is that the `Text` component where this error originates
from doesn't actually make use of the passed `InternalField`. Might be
worth it to take a closer look at it.

Fixes #9179
2024-11-18 17:52:29 -05:00
Dan Ribbens
a25ddc5448 docs: migration guide more info (#9305) 2024-11-18 17:35:36 -05:00
Elliot DeNolf
ecbafbf181 fix(templates): remove req from seed script 2024-11-18 16:58:16 -05:00
Elliot DeNolf
7314990b0c chore(templates): add .npmrc files 2024-11-18 16:38:36 -05:00
Elliot DeNolf
58eeb6e47c chore(templates): bring back needed lock files 2024-11-18 16:35:56 -05:00
Germán Jabloñski
f1eab5d5d3 chore(richtext-lexical): re-export lexical (#9229)
Co-authored-by: Alessio Gravili <alessio@gravili.de>
2024-11-18 16:27:36 -05:00
James Mikrut
6873b139e2 chore(examples): removes nested docs, redirects, virtual fields, custom server, and hierarchy examples (#9112)
Removes examples that are now duplicative or unnecessary due to new
features in 3.0:

### Custom server

This one can be removed in favor of [Next.js
documentation](https://nextjs.org/docs/pages/building-your-application/configuring/custom-server)

### Hierarchy

The new `join` field can solve for many of the use cases for the
`hierarchy` example. Bi-directional relationships with the `join` field
should be preferred here.

### Nested Docs, Redirects

Our website template showcases how to use the `nested-docs` and
`redirects` plugins in-depth, with real-world examples.

### Virtual Fields

Virtual fields have gotten significantly easier and can now be defined
by specifying `virtual: true`. Not a big need for a full example any
longer.

---------

Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
2024-11-18 16:11:21 -05:00
Sophia Michelle Andren
54379eccf4 feat: new Payload logo (#9240)
Introducing the new Payload logo! 🎉


![Payload_Opengraph](https://github.com/user-attachments/assets/387e0841-9498-43df-bf01-f78adb7cdfcf)
2024-11-18 16:08:59 -05:00
Jarrod Flesch
7989563bc1 chore: updates multi tenant example to use baseListFilter (#9308)
### What?
Implements new `baseListFilter` into the multi-tenant example

---------

Co-authored-by: Patrik Kozak <patrik@payloadcms.com>
2024-11-18 15:59:54 -05:00
Patrik
7babe6bcf5 chore(examples): migrates multi-tenant example to latest beta (#9300) 2024-11-18 15:45:20 -05:00
Nate
bccb7c0ff7 chore: update README.md (#9304)
Fixes url to banner asset.
2024-11-18 15:44:42 -05:00
Elliot DeNolf
333da1bb42 fix(templates): seed from url (#9306)
Update website template seeding to use URLs instead of image assets.
Images are not available when deployed to vercel.
2024-11-18 15:41:20 -05:00
Elliot DeNolf
2b955a4aa3 chore(cpa): remove beta from vercel pg and sqlite 2024-11-18 15:40:18 -05:00
Elliot DeNolf
e796ff2330 chore(templates): add back payload cloud to plugins array 2024-11-18 15:31:45 -05:00
mattddean
0075b99eec fix(graphql): loading of polymorphic hasMany relationships (#9175)
### What?

Bug #9173

### Why?

`collectionSlug` is an array when `isRelatedToManyCollections` is true

### How?

Compare array to array

Fixes #9173

![Screenshot 2024-11-13 at 12 37
52 PM](https://github.com/user-attachments/assets/3eae497d-90d8-474a-afd0-baf69f017459)
2024-11-18 22:25:42 +02:00
Sasha
e40141b559 fix: queues types with strict: true (#9281)
Fixes types for workflows / jobs `input` and `output` when using
`strict: true` or `strictNullChecks: true` by ensuring that all
properties in generates types are requried
2024-11-18 21:49:08 +02:00
Jacob Fletcher
ec95ce8758 fix(next): passes doc through edit view handler (#9302)
The Edit and Live Preview views were duplicately making the same Local
API requests for document data. This is because while the top-level
document view handler makes these requests _before_ rendering the Live
Preview view, it wasn't passing it's data through as props. This has
also led to inconsistencies in the options being passed through the
requests themselves, such as `locale`, `user`, and `overrideAccess:
false`. Everything is now standardized as expected through the existing
`getDocumentData` utility.
2024-11-18 14:27:40 -05:00
Mikkel Wied Frederiksen
54ac8b9cd2 fix(next): passes locale through requests in live preview edit view (#9298)
Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
2024-11-18 13:41:12 -05:00
Alessio Gravili
0a6f530007 fix: nav jumping around if no nav preferences are set (#9301)
If you start a fresh dev server and open payload, the nav will initially
show as closed and then jump to its open state. This is because no
preferences are set, so the server tells the client to initially keep it
closed, despite the default nav state being _open_.
2024-11-18 18:36:56 +00:00
Jarrod Flesch
58ac784425 fix(next): initialize payload with importMap (#9297)
### What?
Custom providers could not be resolved because payload was not
initialized in the Root layout with the importMap passed in from props.

### How?
Pass importMap from props into the getPayload function in the Root
layout.
2024-11-18 11:07:40 -05:00
Jarrod Flesch
5503afdf29 fix: sanitize sub block field permissions correctly (#9296)
Fixes https://github.com/payloadcms/payload/issues/9288

### What?
When a block had a subfield named `blocks`, sanitization would throw an
error.

### Why?
An incorrect check for the key of `"fields"` would then attempt to pass
`data.blocks[key].fields` aka `data.blocks.fields.fields` to the next
call of `areAllPermissionsTrue` which would be undefined. Instead if the
key is `fields` it should pass `data.blocks[key]`.

### How?
Remove the second `.fields` property accessor.
2024-11-18 10:47:57 -05:00
Jacob Fletcher
30947d2173 perf!: removes unnecessary field styles from initial page response (#9286)
Optimizes initial page responses by removing unnecessary inline field
styles that were being sent through the HTML response. The Client Config
contains a large number of duplicates of the string:
`"style\":{\"flex\":\"1 1 auto\"}`, one for every single field within
the entirely of the config. This leads to hundreds or potentially
thousands of instances of this same string, depending on the number of
fields within the config itself. This is regardless of custom field
widths being defined. Instead, we can do this entirely client-side,
preventing this string from ever being transmitted over the network in
the first place.

## Breaking Changes

This only effects those who are importing Payload's field components
into your own Custom Components or front-end application. The `width`
prop no longer exists. It has been consolidated into the existing
`style` prop. To migrate, simply move this prop as follows:

```diff
import { TextInput } from '@payloadcms/ui

export const MyCustomComponent = () => {
  return (
    <TextInput 
-      width="60%"
       style={{
+        width: "60%,
       }}
    />
  )
}
```
2024-11-18 10:03:26 -05:00
Sasha
665b3536d3 fix(db-mongodb): potential errors in sanitizeRelationshipIDs with ref being a non object (#9292)
### What?
Fixes potential errors when passed to `sanitizeRelationships` `ref`
could potentially be a non object (for example `string`) because of
having in the database data in old structure.
```
"Cannot create property 'a' on string 'B'",
``` 

### Why?
Necessary particularly for the migration script, as it migrates
everything including versions that can have outdated data.

### How?
Ensures passed `ref` is an `object`.
2024-11-18 16:10:13 +02:00
Dan Ribbens
488c28c99c fix: getPayload node exits on webpack-hmr websocket failure (#9279)
### What?
When a script attempts to load payload using `getPayload()`, it will end
with: `Error: connect ECONNREFUSED 127.0.0.1:3000` etc...

### Why?

Even though there is a try/catch, it still errors because WebSocket
connection failures happen asynchronously after the ws object is
instantiated.

### How?

Added the error handling function cached.ws.onerror to prevent exit.
2024-11-18 09:03:52 -05:00
Jacob Fletcher
7489c29704 chore: dedupes field description functions and defers rendering static field descriptions to the client (#9277)
Custom field description functions were being duplicately called in both
the Client Config and form state. Static field descriptions were also
being rendered in form state unnecessarily. Now, field description
functions are only executed once within form state, and static
descriptions are deferred to the client for rendering.
2024-11-17 22:37:35 -05:00
Jacob Fletcher
3eb8b5939e chore: extracts dependency checker from root layout (#9272)
Cleans up the Root Layout by extracting the dependency checker and
related code away from component logic.
2024-11-17 21:46:18 -05:00
Alessio Gravili
d4f1add2ab feat(richtext-lexical): mdx support (#9160)
Supports bi-directional import/export between MDX <=> Lexical. JSX will
be mapped to lexical blocks back and forth.

This will allow editing our mdx docs in payload while keeping mdx as the
source of truth

---------

Co-authored-by: Germán Jabloñski <43938777+GermanJablo@users.noreply.github.com>
2024-11-17 15:03:45 -07:00
Elliot DeNolf
324af8a5f9 chore: update all githubusercontent links after branch rename 2024-11-17 16:46:23 -05:00
Elliot DeNolf
c9040b6095 chore(templates): update templates after branch rename 2024-11-17 12:52:18 -05:00
Elliot DeNolf
0107a48374 ci: update dependabot config after branch rename 2024-11-17 12:35:34 -05:00
Elliot DeNolf
a31c29b1ff ci: update workflows after branch rename 2024-11-17 12:13:19 -05:00
Elliot DeNolf
cb6ceaec76 chore(release): v3.0.0-beta.134 [skip ci] 2024-11-17 11:43:43 -05:00
Sasha
ef2475d804 fix(ui): avoid calling getTableState from join field on create (#9256)
### What?
Fixes the issue when visiting the create view with the Join Field and
using postgres adapter
```
invalid input syntax for type integer: "NaN"
```
This happens because we don't have an ID yet and we send to the
database:
`WHERE id = NaN`

### How?
Avoids calling `getTableState` inside of `RelationshipTable` if there's
no ID yet, as it will always lead to the same empty result. While we
_could_ avoid error directly in the database adapter, I don't think we
should do that render request

Fixes https://github.com/payloadcms/payload/issues/9193
2024-11-17 11:32:50 -05:00
Sasha
d21fca9156 feat: support relationship writes using objects instead of IDs (#9253)
### What?
Previously, this code led to a validation error because `movie` is an
object and you needed to use `movie.id` instead.
```ts
const movie = await payload.create({ collection: 'movies', data: {} })
const result = await payload.create({
  collection: 'object-writes',
  data: {
    many: [movie],
    manyPoly: [{ relationTo: 'movies', value: movie }],
    one: movie,
    onePoly: {
      relationTo: 'movies',
      value: movie,
    },
  },
})
```
While it's simple to modify this example, it's more painful when you
have a data with `depth` > 0 and then you want to update that document.

### Why?
Better DX as less checks needed, and TypeScript says that we can pass an
object.

### How?
Sanitizes the field value in the root `beforeValidate` hook
2024-11-17 11:25:32 +02:00
Alessio Gravili
35917c67d7 perf(richtext-lexical)!: significantly reduce lexical rerendering and amount of network requests from blocks (#9255)
The field RSC now provides an initial state for all lexical blocks. This
completely obliterates any flashes and lexical block loading states when
loading or saving a document.

Previously, when a document is loaded or saved, every lexical block was
sending a network request in order to fetch their form state. Now, this
is batched and handled in the lexical server component. All lexical
block form states are sent to the client together with the parent
lexical field, and are thus available immediately.

We also do the same with block collapsed preferences. Thus, there are no
loading states or layout shifts/flashes of blocks anymore.

Additionally, when saving a document while your cursor is inside a
lexical field, the cursor position is preserved. Previously, a document
save would kick your cursor out of the lexical field.

## Look at how nice this is:


https://github.com/user-attachments/assets/21d736d4-8f80-4df0-a782-7509edd993da

**BREAKING:**

This removes the `feature.hooks.load` and `feature.hooks.save`
interfaces from custom lexical features, as they weren't used internally
and added unnecessary, additional overhead.

If you have custom features that use those, you can migrate to using
normal payload hooks that run on the server instead of the client.
2024-11-17 08:31:55 +00:00
Jacob Fletcher
abe4cc87ca docs: updates migration guide (#9251)
Documents more breaking changes within the migration guide, improves
overview, reorganizes everything, adds section headings, table of
contents, and more.
2024-11-16 23:34:14 -05:00
Sasha
8efb926be9 chore: split e2e-admin__e2e__1 test suite (#9254)
Speeds up the longest test suite.
From:
<img width="494" alt="image"
src="https://github.com/user-attachments/assets/76d96ece-696a-4b56-9192-deaa307a0442">
To:
<img width="477" alt="image"
src="https://github.com/user-attachments/assets/a9d46180-a9cc-4ef9-8727-0130b422baf0">
2024-11-17 00:47:38 +02:00
Alessio Gravili
63cc9668df feat(richtext-lexical): allow replacing entire blocks with custom components (#9234)
With this PR, you can now customize the way that `blocks` and
`inlineBlocks` are rendered within Lexical's `BlocksFeature` by passing
your own React components.

This is super helpful when you need to create "previews" or more
accurate UI for your Lexical blocks.

For example, let's say you have a `gallery` block where your admins
select a bunch of images. By default, Lexical would just render a
collapsible with your block's fields in it. But now you can customize
the `admin.components.Block` property on your `block` config by passing
it a custom React component for us to render instead.

So using that, with this `gallery` example, you could make a dynamic
gallery React component that shows the images to your editors - and then
render our built-in `BlockEditButton` to allow your editors to manage
your gallery in a drawer.


Here is an example where the BlockEditButton is added to the default
Block Collapsible/Header:


![image](https://github.com/user-attachments/assets/db8c13f1-2650-4b33-bc11-2582bb937f3d)

---------

Co-authored-by: James <james@trbl.design>
2024-11-16 15:30:18 -07:00
Elliot DeNolf
55d5edda6b ci: update pr action 2024-11-16 17:05:44 -05:00
Elliot DeNolf
da22c6abee ci: dynamic base for lockfile pr 2024-11-16 16:01:14 -05:00
Elliot DeNolf
29c7cc8796 ci: do not run release-commenter on workflow_dispatch 2024-11-16 15:37:34 -05:00
James Mikrut
31b32ef941 feat: deprecates getPayloadHMR in favor of simpler getPayload (#9249)
Deprecates `getPayloadHMR` and simplifies this pattern into a single
`import { getPayload } from 'payload'`.

We will still retain the exported `getPayloadHMR` but it now will throw
a deprecation warning with instructions for how to migrate.
2024-11-16 15:30:05 -05:00
Elliot DeNolf
67ff23a6e2 chore(templates): deprecate vercel-postgres, superceded by with-vercel-postgres 2024-11-16 15:24:10 -05:00
Elliot DeNolf
aacc4745b6 ci: allow workflow_dispatch on post-release 2024-11-16 15:00:17 -05:00
Jacob Fletcher
ed21c1c036 fix!: proper casing for default root views (#9248)
Custom `account` and `dashboard` views now defined as lowercase in the
config. This is to maintain consistency with all other custom views
throughout the config. The underlying reason for this change is that
previously, you could define React Components directly on these
properties. Now, these are strictly _view configuration objects_, and
the property names have been adjusted in order to semantically reflect
that. These two views in particular, however, were never updated
accordingly.

## Breaking Changes

```diff
import { buildConfig } from 'payload'

const config = buildConfig({
  // ...
  admin: {
    components: {
      // ...
      views: {
        // ...
-       Account: ...
-       Dashboard: ...
+       account: ...
+       dashboard: ...
      },
    },
  },
})
```
2024-11-16 14:35:35 -05:00
Elliot DeNolf
447587a01e ci: adjust post-release pr permissions 2024-11-16 14:20:45 -05:00
Jacob Fletcher
c4269d25d3 fix(next): custom default root views (#9247)
Fixes #9246. Custom default root views (account and dashboard) were not
being properly thread to the custom component renderer. Custom account
views were also improperly _stacking_ instead of _replacing_ the default
view.

Tests for this are incoming. To properly test this we need to wrap our
default root views with custom ones, so that out existing `admin` test
suite can continue to work alongside tests specifically for this issue.
2024-11-16 14:05:50 -05:00
Elliot DeNolf
457be31ed2 chore(release): v3.0.0-beta.133 [skip ci] 2024-11-16 13:59:41 -05:00
Elliot DeNolf
bfbee4e604 ci: bump templates post release (#9241)
Automatically create a PR that bumps the lockfiles of the templates post
release.
2024-11-16 13:51:01 -05:00
James Mikrut
9b00b59df0 fix: corrects cases of false positive identification of custom id fields (#9245)
This PR fixes cases where you may have a field called `id` within a
group or a named tab, which would have incorrectly been treated as a
custom ID field for the collection.

However, custom IDs need to be defined at the root level - and now
Payload only respects custom IDs defined at the root level.
2024-11-16 16:29:48 +00:00
Elliot DeNolf
1393d84bca feat(templates): programmatic migration gen (#9238)
Programmatically generate lockfiles and postgres migrations
2024-11-15 21:47:05 -05:00
Elliot DeNolf
ff8e7bb968 chore(release): v3.0.0-beta.132 [skip ci] 2024-11-15 18:13:02 -05:00
James Mikrut
131d1be8fc fix(ui): lexical was incorrectly set to readonly in blocks (#9237)
Fixes a bug introduced in `beta-131` that rendered Lexical fields as
read-only if they were within a block.
2024-11-15 22:47:26 +00:00
Elliot DeNolf
30d66bf601 fix(templates): vercel website migrations (#9235)
Properly generate migrations for with-vercel-website template
2024-11-15 16:44:55 -05:00
731 changed files with 28339 additions and 66007 deletions

View File

@@ -8,7 +8,7 @@ updates:
- /.github/workflows
- /.github/actions/* # Not working until resolved: https://github.com/dependabot/dependabot-core/issues/6345
- /.github/actions/setup
target-branch: beta
target-branch: main
schedule:
interval: monthly
timezone: America/Detroit
@@ -20,7 +20,7 @@ updates:
- package-ecosystem: npm
directory: /
target-branch: beta
target-branch: main
schedule:
interval: weekly
day: sunday
@@ -53,7 +53,7 @@ updates:
# Only bump patch versions for 2.x
- package-ecosystem: npm
directory: /
target-branch: main
target-branch: 2.x
schedule:
interval: weekly
day: sunday

View File

@@ -40,7 +40,7 @@ There are a couple ways run integration tests:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/int-debug.png" />
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/int-debug.png" />
- **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command:
@@ -57,7 +57,7 @@ The easiest way to run E2E tests is to install
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/e2e-debug.png" />
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/e2e-debug.png" />
#### Notes

View File

@@ -9,7 +9,6 @@ on:
push:
branches:
- main
- beta
concurrency:
# <workflow_name>-<branch_name>-<true || commit_sha if branch is protected>
@@ -284,7 +283,7 @@ jobs:
tests-e2e:
runs-on: ubuntu-latest
needs: build
name: ${{ matrix.suite }}
name: e2e-${{ matrix.suite }}
strategy:
fail-fast: false
matrix:
@@ -294,6 +293,7 @@ jobs:
- access-control
- admin__e2e__1
- admin__e2e__2
- admin__e2e__3
- admin-root
- auth
- field-error-states
@@ -414,6 +414,10 @@ jobs:
- template: with-vercel-postgres
database: postgres
# Re-enable once PG conncection is figured out
# - template: with-vercel-website
# database: postgres
name: ${{ matrix.template }}-${{ matrix.database }}
env:
@@ -525,7 +529,7 @@ jobs:
publish-canary:
name: Publish Canary
runs-on: ubuntu-latest
if: ${{ needs.all-green.result == 'success' && github.ref_name == 'beta' }}
if: ${{ needs.all-green.result == 'success' && github.ref_name == 'main' }}
needs:
- all-green
@@ -533,4 +537,4 @@ jobs:
# debug github.ref output
- run: |
echo github.ref: ${{ github.ref }}
echo isBeta: ${{ github.ref == 'refs/heads/beta' }}
echo isV3: ${{ github.ref == 'refs/heads/main' }}

View File

@@ -5,16 +5,26 @@ on:
types:
- published
workflow_dispatch:
inputs:
tag:
description: 'Release tag to process (optional)'
required: false
default: ''
env:
NODE_VERSION: 22.6.0
PNPM_VERSION: 9.7.1
DO_NOT_TRACK: 1 # Disable Turbopack telemetry
NEXT_TELEMETRY_DISABLED: 1 # Disable Next telemetry
jobs:
post_release:
runs-on: ubuntu-latest
if: ${{ github.event_name != 'workflow_dispatch' }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
# Only needed if debugging on a branch other than default
# ref: ${{ github.event.release.target_commitish || github.ref }}
- uses: ./.github/actions/release-commenter
continue-on-error: true
env:
@@ -28,3 +38,70 @@ jobs:
comment-template: |
🚀 This is included in version {release_link}
update_templates:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup
uses: ./.github/actions/setup
with:
node-version: ${{ env.NODE_VERSION }}
pnpm-version: ${{ env.PNPM_VERSION }}
- name: Update template lockfiles and migrations
run: pnpm script:gen-templates
- name: Determine Release Tag
id: determine_tag
run: |
if [ "${{ github.event.inputs.tag }}" != "" ]; then
echo "Using tag from input: ${{ github.event.inputs.tag }}"
echo "release_tag=${{ github.event.inputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "Using tag from release event: ${{ github.event.release.tag_name }}"
echo "release_tag=${{ github.event.release.tag_name }}" >> "$GITHUB_OUTPUT"
fi
- name: Commit and push changes
id: commit
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -ex
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
export BRANCH_NAME=chore/templates-${{ steps.determine_tag.outputs.release_tag }}
git checkout -b $BRANCH_NAME
git add -A
# If no files have changed, exit early with success
git diff --cached --quiet --exit-code && exit 0
git commit -m "chore(templates): bump lockfiles after ${{ steps.determine_tag.outputs.release_tag }}"
git push origin $BRANCH_NAME
echo "committed=true" >> "$GITHUB_OUTPUT"
echo "branch=$BRANCH_NAME" >> "$GITHUB_OUTPUT"
- name: Debug Branches
run: |
echo "Target Commitish: ${{ github.event.release.target_commitish }}"
echo "Branch: ${{ steps.commit.outputs.branch }}"
echo "Ref: ${{ github.ref }}"
- name: Create pull request
uses: peter-evans/create-pull-request@v7
if: steps.commit.outputs.committed == 'true'
with:
token: ${{ secrets.GITHUB_TOKEN }}
labels: 'area: templates'
author: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
commit-message: 'Automated update after release'
branch: ${{ steps.commit.outputs.branch }}
base: ${{ github.event_name != 'workflow_dispatch' && github.event.release.target_commitish || github.ref }}
title: 'chore(templates): bump lockfiles after ${{ steps.determine_tag.outputs.release_tag }}'
body: 'Automated bump of template lockfiles after release ${{ steps.determine_tag.outputs.release_tag }}'

View File

@@ -109,13 +109,13 @@ jobs:
runs-on: ubuntu-latest
if: github.event.action == 'opened'
steps:
- name: Tag with main branch with v2
if: github.event.pull_request.base.ref == 'main'
- name: Tag with 2.x branch with v2
if: github.event.pull_request.base.ref == '2.x'
uses: actions-ecosystem/action-add-labels@v1
with:
labels: v2
- name: Tag with beta branch with v3
if: github.event.pull_request.base.ref == 'beta'
- name: Tag with main branch with v3
if: github.event.pull_request.base.ref == 'main'
uses: actions-ecosystem/action-add-labels@v1
with:
labels: v3

View File

@@ -3,7 +3,7 @@ name: release-canary
on:
workflow_dispatch:
branches:
- beta
- main
env:
NODE_VERSION: 22.6.0

View File

@@ -45,7 +45,7 @@ There are a couple ways to do this:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/int-debug.png" />
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/int-debug.png" />
- **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command:
@@ -62,7 +62,7 @@ The easiest way to run E2E tests is to install
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/e2e-debug.png" />
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/e2e-debug.png" />
#### Notes

View File

@@ -1,4 +1,4 @@
<a href="https://payloadcms.com"><img width="100%" src="https://github.com/payloadcms/payload/blob/beta/packages/payload/src/assets/images/github-banner-nextjs-native.jpg" alt="Payload headless CMS Admin panel built with React" /></a>
<a href="https://payloadcms.com"><img width="100%" src="https://github.com/payloadcms/payload/blob/main/packages/payload/src/assets/images/github-banner-nextjs-native.jpg" alt="Payload headless CMS Admin panel built with React" /></a>
<br />
<br />

View File

@@ -62,13 +62,13 @@ You can also override Payload's built-in [CSS Variables](https://developer.mozil
The following variables are defined and can be overridden:
- [Breakpoints](https://github.com/payloadcms/payload/blob/beta/packages/ui/src/scss/queries.scss)
- [Colors](https://github.com/payloadcms/payload/blob/beta/packages/ui/src/scss/colors.scss)
- [Breakpoints](https://github.com/payloadcms/payload/blob/main/packages/ui/src/scss/queries.scss)
- [Colors](https://github.com/payloadcms/payload/blob/main/packages/ui/src/scss/colors.scss)
- Base color shades (white to black by default)
- Success / warning / error color shades
- Theme-specific colors (background, input background, text color, etc.)
- Elevation colors (used to determine how "bright" something should be when compared to the background)
- [Sizing](https://github.com/payloadcms/payload/blob/beta/packages/ui/src/scss/app.scss)
- [Sizing](https://github.com/payloadcms/payload/blob/main/packages/ui/src/scss/app.scss)
- Horizontal gutter
- Transition speeds
- Font sizes

View File

@@ -121,6 +121,11 @@ All Description Functions receive the following arguments:
| -------------- | ---------------------------------------------------------------- |
| **`t`** | The `t` function used to internationalize the Admin Panel. [More details](../configuration/i18n) |
<Banner type="info">
<strong>Note:</strong>
If you need to subscribe to live updates within your form, use a Description Component instead. [More details](#description).
</Banner>
## Conditional Logic
You can show and hide fields based on what other fields are doing by utilizing conditional logic on a field by field basis. The `condition` property on a field's admin config accepts a function which takes three arguments:

View File

@@ -177,7 +177,7 @@ The following options are available:
<Banner type="success">
<strong>Tip:</strong>
You can easily add _new_ routes to the Admin Panel through [Custom Endpoints](../rest-api/overview#custom-endpoints) and [Custom Views](./views).
You can easily add _new_ routes to the Admin Panel through [Custom Endpoints](../rest-api/overview#custom-endpoints) and [Custom Views](./views).
</Banner>
#### Customizing Root-level Routes
@@ -237,7 +237,7 @@ The following options are available:
## I18n
The Payload Admin Panel is translated in over [30 languages and counting](https://github.com/payloadcms/payload/tree/beta/packages/translations). Languages are automatically detected based on the user's browser and used by the Admin Panel to display all text in that language. If no language was detected, or if the user's language is not yet supported, English will be chosen. Users can easily specify their language by selecting one from their account page. See [I18n](../configuration/i18n) for more information.
The Payload Admin Panel is translated in over [30 languages and counting](https://github.com/payloadcms/payload/tree/main/packages/translations). Languages are automatically detected based on the user's browser and used by the Admin Panel to display all text in that language. If no language was detected, or if the user's language is not yet supported, English will be chosen. Users can easily specify their language by selecting one from their account page. See [I18n](../configuration/i18n) for more information.
## Light and Dark Modes

View File

@@ -350,6 +350,8 @@ export const MyCollectionConfig: SanitizedCollectionConfig = {
}
```
### Default Props
Your Custom Views will be provided with the following props:
| Prop | Description |
@@ -359,6 +361,7 @@ Your Custom Views will be provided with the following props:
| **`importMap`** | The import map object. |
| **`params`** | An object containing the [Dynamic Route Parameters](https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes). |
| **`searchParams`** | An object containing the [Search Parameters](https://developer.mozilla.org/docs/Learn/Common_questions/What_is_a_URL#parameters). |
| **`doc`** | The document being edited. Only available in Document Views. [More details](#document-views). |
<Banner type="success">
<strong>Reminder:</strong>

View File

@@ -6,7 +6,7 @@ desc: Manage and customize internationalization support in your CMS editor exper
keywords: internationalization, i18n, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
The [Admin Panel](../admin/overview) is translated in over [30 languages and counting](https://github.com/payloadcms/payload/tree/beta/packages/translations). With I18n, editors can navigate the interface and read API error messages in their preferred language. This is similar to [Localization](./localization), but instead of managing translations for the data itself, you are managing translations for your application's interface.
The [Admin Panel](../admin/overview) is translated in over [30 languages and counting](https://github.com/payloadcms/payload/tree/main/packages/translations). With I18n, editors can navigate the interface and read API error messages in their preferred language. This is similar to [Localization](./localization), but instead of managing translations for the data itself, you are managing translations for your application's interface.
By default, Payload comes with preinstalled with English, but you can easily load other languages into your own application. Languages are automatically detected based on the request. If no language was detected, or if the user's language is not yet supported by your application, English will be chosen.

View File

@@ -12,18 +12,13 @@ Examples are changing every day, so be sure to check back often to see what new
- [Auth](https://github.com/payloadcms/payload/tree/main/examples/auth)
- [Custom Components](https://github.com/payloadcms/payload/tree/main/examples/custom-components)
- [Custom Server](https://github.com/payloadcms/payload/tree/main/examples/custom-server)
- [Draft Preview](https://github.com/payloadcms/payload/tree/main/examples/draft-preview)
- [Email](https://github.com/payloadcms/payload/tree/main/examples/email)
- [Form Builder](https://github.com/payloadcms/payload/tree/main/examples/form-builder)
- [Hierarchy](https://github.com/payloadcms/payload/tree/main/examples/hierarchy)
- [Live Preview](https://github.com/payloadcms/payload/tree/main/examples/live-preview)
- [Multi-tenant](https://github.com/payloadcms/payload/tree/main/examples/multi-tenant)
- [Nested Docs](https://github.com/payloadcms/payload/tree/main/examples/nested-docs)
- [Redirects](https://github.com/payloadcms/payload/tree/main/examples/redirects)
- [Tailwind / Shadcn-ui](https://github.com/payloadcms/payload/tree/main/examples/tailwind-shadcn-ui)
- [Tests](https://github.com/payloadcms/payload/tree/main/examples/testing)
- [Virtual Fields](https://github.com/payloadcms/payload/tree/main/examples/virtual-fields)
- [White-label Admin UI](https://github.com/payloadcms/payload/tree/main/examples/whitelabel)
When necessary, some examples include a front-end. Examples that require a front-end share this folder structure:

View File

@@ -84,6 +84,51 @@ The Blocks Field inherits all of the default options from the base [Field Admin
| **`initCollapsed`** | Set the initial collapsed state |
| **`isSortable`** | Disable order sorting by setting this value to `false` |
#### Customizing the way your block is rendered in Lexical
If you're using this block within the [Lexical editor](/docs/lexical/overview), you can also customize how the block is rendered in the Lexical editor itself by specifying custom components.
- `admin.components.Label` - pass a custom React component here to customize the way that the label is rendered for this block
- `admin.components.Block` - pass a component here to completely override the way the block is rendered in Lexical with your own component
This is super handy if you'd like to present your editors with a very deliberate and nicely designed block "preview" right in your rich text.
For example, if you have a `gallery` block, you might want to actually render the gallery of images directly in your Lexical block. With the `admin.components.Block` property, you can do exactly that!
<Banner type="success">
<strong>Tip:</strong><br/>
If you customize the way your block is rendered in Lexical, you can import utility components to easily edit / remove your block - so that you don't have to build all of this yourself.
</Banner>
To import these utility components for one of your custom blocks, you can import the following:
```ts
import {
// Edit block buttons (choose the one that corresponds to your usage)
// When clicked, this will open a drawer with your block's fields
// so your editors can edit them
InlineBlockEditButton,
BlockEditButton,
// Buttons that will remove this block from Lexical
// (choose the one that corresponds to your usage)
InlineBlockRemoveButton,
BlockRemoveButton,
// The label that should be rendered for an inline block
InlineBlockLabel,
// The default "container" that is rendered for an inline block
// if you want to re-use it
InlineBlockContainer,
// The default "collapsible" UI that is rendered for a regular block
// if you want to re-use it
BlockCollapsible,
} from '@payloadcms/richtext-lexical/client'
```
## Block Configs
Blocks are defined as separate configs of their own.

View File

@@ -19,8 +19,8 @@ Payload's rich text field is built on an "adapter pattern" which lets you specif
Right now, Payload is officially supporting two rich text editors:
1. [SlateJS](/docs/rich-text/slate) - stable, backwards-compatible with 1.0
2. [Lexical](/docs/lexical/overview) - beta, where things will be moving
1. [SlateJS](/docs/rich-text/slate) - legacy, backwards-compatible with 1.0
2. [Lexical](/docs/lexical/overview) - recommended
<Banner type="success">
<strong>

View File

@@ -68,15 +68,10 @@ Here's a quick example of a React Server Component fetching data using the Local
```tsx
import React from 'react'
import config from '@payload-config'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { getPayload } from 'payload'
const MyServerComponent: React.FC = () => {
// If you're working in Next.js, and you want HMR,
// you should get Payload via the `getPayloadHMR` function.
const payload = await getPayloadHMR({ config })
// If you are writing a standalone script and do not need HMR,
// you can get Payload via import { getPayload } from 'payload' instead.
const payload = await getPayload({ config })
// The `findResult` here will be fully typed as `PaginatedDocs<Page>`,
// where you will have the `docs` that are returned as well as

View File

@@ -24,14 +24,14 @@ Payload requires the following software:
To quickly scaffold a new Payload app in the fastest way possible, you can use [create-payload-app](https://npmjs.com/package/create-payload-app). To do so, run the following command:
```
npx create-payload-app@beta
npx create-payload-app
```
Then just follow the prompts! You'll get set up with a new folder and a functioning Payload app inside. You can then start [configuring your application](../configuration/overview).
## Adding to an existing app
Adding Payload to an existing Next.js app is super straightforward. You can either run the `npx create-payload-app@beta` command inside your Next.js project's folder, or manually install Payload by following the steps below.
Adding Payload to an existing Next.js app is super straightforward. You can either run the `npx create-payload-app` command inside your Next.js project's folder, or manually install Payload by following the steps below.
If you don't have a Next.js app already, but you still want to start a project from a blank Next.js app, you can create a new Next.js app using `npx create-next-app` - and then just follow the steps below to install Payload.
@@ -44,7 +44,7 @@ If you don't have a Next.js app already, but you still want to start a project f
First, you'll want to add the required Payload packages to your project and can do so by running the command below:
```bash
pnpm i payload@beta @payloadcms/next@beta @payloadcms/richtext-lexical@beta sharp graphql
pnpm i payload @payloadcms/next @payloadcms/richtext-lexical sharp graphql
```
<Banner type="warning">
@@ -58,12 +58,12 @@ To install a Database Adapter, you can run **one** of the following commands:
- To install the [MongoDB Adapter](../database/mongodb), run:
```bash
pnpm i @payloadcms/db-mongodb@beta
pnpm i @payloadcms/db-mongodb
```
- To install the [Postgres Adapter](../database/postgres), run:
```bash
pnpm i @payloadcms/db-postgres@beta
pnpm i @payloadcms/db-postgres
```
<Banner type="success">
@@ -73,7 +73,7 @@ To install a Database Adapter, you can run **one** of the following commands:
#### 2. Copy Payload files into your Next.js app folder
Payload installs directly in your Next.js `/app` folder, and you'll need to place some files into that folder for Payload to run. You can copy these files from the [Blank Template](https://github.com/payloadcms/payload/tree/beta/templates/blank/src/app/(payload)) on GitHub. Once you have the required Payload files in place in your `/app` folder, you should have something like this:
Payload installs directly in your Next.js `/app` folder, and you'll need to place some files into that folder for Payload to run. You can copy these files from the [Blank Template](https://github.com/payloadcms/payload/tree/main/templates/blank/src/app/(payload)) on GitHub. Once you have the required Payload files in place in your `/app` folder, you should have something like this:
```plaintext
app/

View File

@@ -3,7 +3,7 @@ title: What is Payload?
label: What is Payload?
order: 10
desc: Payload is a next-gen application framework that can be used as a Content Management System, enterprise tool framework, headless commerce platform, or digital asset management tool.
keywords: documentation, getting started, guide, Content Management System, cms, headless, javascript, node, react, express
keywords: documentation, getting started, guide, Content Management System, cms, headless, javascript, node, react
---
<YouTube
@@ -95,12 +95,6 @@ Payload can integrate with any payment processor like Stripe and its content aut
If you can build your storefront with a single backend, and only offload things like payment processing, the code will be simpler and the editing experience will be significantly streamlined. Manage products, catalogs, page content, media, and more—all in one spot.
Payload's official Ecommerce template gives you everything you need for a storefront out of the box, including a Next.js frontend, product variations, and a full Stripe implementation:
```
npx create-payload-app@latest -t ecommerce
```
### Digital Asset Management
Payload's API-first tagging, sorting, and querying engine lends itself perfectly to all types of content that a CMS might ordinarily store, but these strong fundamentals also make it a formidable Digital Asset Management (DAM) tool as well.

View File

@@ -13,7 +13,7 @@ In Payload the schema is controlled by your collections and globals. All you nee
Install `@payloadcms/graphql` as a dev dependency:
```bash
pnpm add @payloadcms/graphql@beta -D
pnpm add @payloadcms/graphql -D
```
Run the following command to generate the schema:

View File

@@ -32,7 +32,7 @@ Examples:
**Periodic sync or similar scheduled action**
Some applications may need to perform a regularly scheduled operation of some type. Jobs are perfect for this because you can execute their logic using `cron`, scheduled nightly, every twelve hours, or some similar time period.
Some applications may need to perform a regularly scheduled operation of some type. Jobs are perfect for this because you can execute their logic using `cron`, scheduled nightly, every twelve hours, or some similar time period.
Examples:
@@ -49,22 +49,22 @@ Examples:
- You need to create (and then keep in sync) vector embeddings of your documents as they change, but you use an open source model to generate embeddings
- You have a PDF generator that needs to dynamically build and send PDF versions of documents to customers
- You need to use a headless browser to perform some type of logic
- You need to perform a series of actions, each of which depends on a prior action and should be run in as "durable" of a fashion as possible
- You need to perform a series of actions, each of which depends on a prior action and should be run in as "durable" of a fashion as possible
### How it works
There are a few concepts that you should become familiarized with before using Payload's Jobs Queue. We recommend learning what each of these does in order to fully understand how to leverage the power of Payload's Jobs Queue.
1. [Tasks](/docs/beta/jobs-queue/tasks)
1. [Workflows](/docs/beta/jobs-queue/workflows)
1. [Jobs](/docs/beta/jobs-queue/jobs)
1. [Queues](/docs/beta/jobs-queue/queues)
1. [Tasks](/docs/jobs-queue/tasks)
1. [Workflows](/docs/jobs-queue/workflows)
1. [Jobs](/docs/jobs-queue/jobs)
1. [Queues](/docs/jobs-queue/queues)
All of these pieces work together in order to allow you to offload long-running, expensive, or future scheduled work from your main APIs.
All of these pieces work together in order to allow you to offload long-running, expensive, or future scheduled work from your main APIs.
Here's a quick overview:
- A Task is a specific function that performs business logic
- Workflows are groupings of specific tasks which should be run in-order, and can be retried from a specific point of failure
- A Job is an instance of a single task or workflow which will be executed
- A Queue is a way to segment your jobs into different "groups" - for example, some to run nightly, and others to run every 10 minutes
- A Queue is a way to segment your jobs into different "groups" - for example, some to run nightly, and others to run every 10 minutes

View File

@@ -2,7 +2,7 @@
title: Tasks
label: Tasks
order: 20
desc: A Task is a distinct function declaration that can be run within Payload's Jobs Queue.
desc: A Task is a distinct function declaration that can be run within Payload's Jobs Queue.
keywords: jobs queue, application framework, typescript, node, react, nextjs
---
@@ -10,7 +10,7 @@ keywords: jobs queue, application framework, typescript, node, react, nextjs
A <strong>"Task"</strong> is a function definition that performs business logic and whose input and output are both strongly typed.
</Banner>
You can register Tasks on the Payload config, and then create [Jobs](/docs/beta/jobs-queue/jobs) or [Workflows](/docs/beta/jobs-queue/workflows) that use them. Think of Tasks like tidy, isolated "functions that do one specific thing".
You can register Tasks on the Payload config, and then create [Jobs](/docs/jobs-queue/jobs) or [Workflows](/docs/jobs-queue/workflows) that use them. Think of Tasks like tidy, isolated "functions that do one specific thing".
Payload Tasks can be configured to automatically retried if they fail, which makes them valuable for "durable" workflows like AI applications where LLMs can return non-deterministic results, and might need to be retried.

View File

@@ -83,7 +83,7 @@ The Server Feature, just like the Client Feature, allows you to add markdown tra
```ts
import { createServerFeature } from '@payloadcms/richtext-lexical';
import type { ElementTransformer } from '@lexical/markdown'
import type { ElementTransformer } from '@payloadcms/richtext-lexical/lexical/markdown'
import {
$createMyNode,
$isMyNode,
@@ -299,9 +299,9 @@ import type {
EditorConfig,
LexicalNode,
SerializedLexicalNode,
} from 'lexical'
} from '@payloadcms/richtext-lexical/lexical'
import { $applyNodeReplacement, DecoratorNode } from 'lexical'
import { $applyNodeReplacement, DecoratorNode } from '@payloadcms/richtext-lexical/lexical'
// SerializedLexicalNode is the default lexical node.
// By setting your SerializedMyNode type to SerializedLexicalNode,
@@ -448,17 +448,17 @@ Example plugin.tsx:
'use client'
import type {
LexicalCommand,
} from 'lexical'
} from '@payloadcms/richtext-lexical/lexical'
import {
createCommand,
$getSelection,
$isRangeSelection,
COMMAND_PRIORITY_EDITOR
} from 'lexical'
} from '@payloadcms/richtext-lexical/lexical'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext.js'
import { $insertNodeToNearestRoot } from '@lexical/utils'
import { useLexicalComposerContext } from '@payloadcms/richtext-lexical/lexical/react/LexicalComposerContext.js'
import { $insertNodeToNearestRoot } from '@payloadcms/richtext-lexical/lexical/utils'
import { useEffect } from 'react'
import type { PluginComponent } from '@payloadcms/richtext-lexical' // type imports can be imported from @payloadcms/richtext-lexical - even on the client
@@ -589,7 +589,7 @@ import { createClientFeature, toolbarAddDropdownGroupWithItems } from '@payloadc
import { IconComponent } from './icon';
import { $isHorizontalRuleNode } from './nodes/MyNode';
import { INSERT_MYNODE_COMMAND } from './plugin';
import { $isNodeSelection } from 'lexical'
import { $isNodeSelection } from '@payloadcms/richtext-lexical/lexical'
export const MyClientFeature = createClientFeature({
toolbarFixed: {
@@ -711,7 +711,7 @@ The Client Feature, just like the Server Feature, allows you to add markdown tra
```ts
import { createClientFeature } from '@payloadcms/richtext-lexical/client';
import type { ElementTransformer } from '@lexical/markdown'
import type { ElementTransformer } from '@payloadcms/richtext-lexical/lexical/markdown'
import {
$createMyNode,
$isMyNode,
@@ -836,4 +836,4 @@ The reason the client feature does not have the same props available as the serv
## More information
Have a look at the [features we've already built](https://github.com/payloadcms/payload/tree/beta/packages/richtext-lexical/src/features) - understanding how they work will help you understand how to create your own. There is no difference between the features included by default and the ones you create yourself - since those features are all isolated from the "core", you have access to the same APIs, whether the feature is part of Payload or not!
Have a look at the [features we've already built](https://github.com/payloadcms/payload/tree/main/packages/richtext-lexical/src/features) - understanding how they work will help you understand how to create your own. There is no difference between the features included by default and the ones you create yourself - since those features are all isolated from the "core", you have access to the same APIs, whether the feature is part of Payload or not!

View File

@@ -200,7 +200,7 @@ Lexical provides a seamless way to perform conversions between various other for
A headless editor can perform such conversions outside of the main editor instance. Follow this method to initiate a headless editor:
```ts
import { createHeadlessEditor } from '@lexical/headless' // <= make sure this package is installed
import { createHeadlessEditor } from '@payloadcms/richtext-lexical/lexical/headless'
import { getEnabledNodes, sanitizeServerEditorConfig } from '@payloadcms/richtext-lexical'
const yourEditorConfig // <= your editor config here
@@ -237,7 +237,7 @@ If you have access to the sanitized collection config, you can get access to the
```ts
import type { CollectionConfig, RichTextField } from 'payload'
import { createHeadlessEditor } from '@lexical/headless'
import { createHeadlessEditor } from '@payloadcms/richtext-lexical/lexical/headless'
import type { LexicalRichTextAdapter, SanitizedServerEditorConfig } from '@payloadcms/richtext-lexical'
import {
getEnabledNodes,
@@ -292,8 +292,8 @@ export const MyCollection: CollectionConfig = {
Once you have your headless editor instance, you can use it to convert HTML to Lexical:
```ts
import { $generateNodesFromDOM } from '@lexical/html'
import { $getRoot, $getSelection } from 'lexical'
import { $generateNodesFromDOM } from '@payloadcms/richtext-lexical/lexical/html'
import { $getRoot, $getSelection } from '@payloadcms/richtext-lexical/lexical'
import { JSDOM } from 'jsdom'
headlessEditor.update(
@@ -334,8 +334,7 @@ This has been taken from the [lexical serialization & deserialization docs](http
Convert markdown content to the Lexical editor format with the following:
```ts
import { $convertFromMarkdownString } from '@lexical/markdown'
import { sanitizeServerEditorConfig } from '@payloadcms/richtext-lexical'
import { sanitizeServerEditorConfig, $convertFromMarkdownString } from '@payloadcms/richtext-lexical'
const yourSanitizedEditorConfig = sanitizeServerEditorConfig(yourEditorConfig, payloadConfig) // <= your editor config & Payload Config here
const markdown = `# Hello World`
@@ -361,9 +360,9 @@ Export content from the Lexical editor into Markdown format using these steps:
Here's the code for it:
```ts
import { $convertToMarkdownString } from '@lexical/markdown'
import { $convertToMarkdownString } from '@payloadcms/richtext-lexical/lexical/markdown'
import { sanitizeServerEditorConfig } from '@payloadcms/richtext-lexical'
import type { SerializedEditorState } from 'lexical'
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
const yourSanitizedEditorConfig = sanitizeServerEditorConfig(yourEditorConfig, payloadConfig) // <= your editor config & Payload Config here
const yourEditorState: SerializedEditorState // <= your current editor state here
@@ -397,8 +396,8 @@ Export content from the Lexical editor into plain text using these steps:
Here's the code for it:
```ts
import type { SerializedEditorState } from 'lexical'
import { $getRoot } from 'lexical'
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import { $getRoot } from '@payloadcms/richtext-lexical/lexical'
const yourEditorState: SerializedEditorState // <= your current editor state here

View File

@@ -10,12 +10,6 @@ One of Payload's goals is to build the best rich text editor experience that we
Classically, we've used SlateJS to work toward this goal, but building custom elements into Slate has proven to be more difficult than we'd like, and we've been keeping our options open.
<Banner type="warning">
Payload's Lexical rich text editor is currently in beta. It's stable enough to use as you build on
Payload, so if you're up for helping us fine-tune it, you should use it. But if you're looking for
stability, use Slate instead.
</Banner>
Lexical is extremely impressive and trivializes a lot of the hard parts of building new elements into a rich text editor. It has a few distinct advantages over Slate, including the following:
1. A "/" menu, which allows editors to easily add new elements while never leaving their keyboard

View File

@@ -34,11 +34,11 @@ Then, render the `RefreshRouteOnSave` component anywhere in your `page.tsx`. Her
```tsx
import { RefreshRouteOnSave } from './RefreshRouteOnSave.tsx'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { getPayload } from 'payload'
import config from '../payload.config'
export default async function Page() {
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const page = await payload.findByID({
collection: 'pages',

View File

@@ -18,12 +18,9 @@ Payload can be used completely outside of Next.js which is helpful in cases like
Payload provides a convenient way to run standalone scripts, which can be useful for tasks like seeding your database or performing one-off operations.
In standalone scripts, can simply import the Payload Config and use it right away. If you need an initialized copy of Payload, you can then use the `getPayload` function. This can be useful for tasks like seeding your database or performing other one-off operations.
In standalone scripts, you can simply import the Payload Config and use it right away. If you need an initialized copy of Payload, you can then use the `getPayload` function. This can be useful for tasks like seeding your database or performing other one-off operations.
```ts
// We are importing `getPayload` because we don't need HMR
// for a standalone script. For usage of Payload inside Next.js,
// you should always use `import { getPayloadHMR } from '@payloadcms/next/utilities'` instead.
import { getPayload } from 'payload'
import config from '@payload-config'

View File

@@ -43,27 +43,6 @@ const afterChangeHook: CollectionAfterChangeHook = async ({ req: { payload } })
If you want to import Payload in places where you don't have the option to access it from function arguments or `req`, you can import it and initialize it.
There are two places to import Payload:
**Option 1 - using HMR, within Next.js**
```ts
import { getPayloadHMR } from '@payloadcms/next/utilities'
import config from '@payload-config'
const payload = await getPayloadHMR({ config })
```
You should import Payload using the first option (`getPayloadHMR`) if you are using Payload inside of Next.js (like route handlers, server components, and similar.)
This way, in Next.js development mode, Payload will work with Hot Module Replacement (HMR), and as you make changes to your Payload Config, your usage of Payload will always be in sync with your changes. In production, `getPayloadHMR` simply disables all HMR functionality so you don't need to write your code any differently. We handle optimization for you in production mode.
If you are accessing Payload via function arguments or `req.payload`, HMR is automatically supported if you are using it within Next.js.
**Option 2 - outside of Next.js**
If you are using Payload outside of Next.js, for example in standalone scripts or in other frameworks, you can import Payload with no HMR functionality. Instead of using `getPayloadHMR`, you can use `getPayload`.
```ts
import { getPayload } from 'payload'
import config from '@payload-config'
@@ -71,7 +50,11 @@ import config from '@payload-config'
const payload = await getPayload({ config })
```
Both options function in exactly the same way outside of one having HMR support and the other not. For more information about using Payload outside of Next.js, [click here](./outside-nextjs).
If you're working in Next.js' development mode, Payload will work with Hot Module Replacement (HMR), and as you make changes to your Payload Config, your usage of Payload will always be in sync with your changes. In production, `getPayload` simply disables all HMR functionality so you don't need to write your code any differently. We handle optimization for you in production mode.
If you are accessing Payload via function arguments or `req.payload`, HMR is automatically supported if you are using it within Next.js.
For more information about using Payload outside of Next.js, [click here](./outside-nextjs).
## Local options available

View File

@@ -1,15 +1,121 @@
# 🚧 **DRAFT:** 3.0 Migration Guide / Breaking Changes
---
title: 2.0 to 3.0 Migration Guide
label: 2.0 to 3.0 Migration Guide
order: 10
desc: Upgrade guide for Payload 2.x projects migrating to 3.0.
keywords: local api, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react
---
> [!IMPORTANT]
> This document will continue to be updated and cleaned up until the 3.0 release.
# Payload 2.0 to 3.0 Migration Guide
Payload 3.0 completely replatforms the Admin Panel from a React Router single-page application onto the Next.js App Router with full support for React Server Components. This change completely separates Payload "core" from its rendering and HTTP layers, making it truly Node-safe and portable.
## What has changed?
The core logic and principles of Payload remain the same from 2.0 to 3.0, with the majority of changes affecting specifically the HTTP layer and the Admin Panel, which is now built upon Next.js. With this change, your entire application can be served within a single repo. Payload endpoints are now opened directly within your own Next.js application, right alongside your frontend. All Payload APIs remain exactly the same (with a few new features), and the Payload Config is generally the same, with the breaking changes detailed below.
The core logic and principles of Payload remain the same from 2.0 to 3.0, with the majority of changes affecting specifically the HTTP layer and the Admin Panel, which is now built upon Next.js. With this change, your entire application can be served within a single repo, with Payload endpoints are now opened within your own Next.js application, directly alongside your frontend. Payload is still headless, you will still be able to leverage it completely headlessly just as you do now with Sveltekit, etc. All Payload APIs remain exactly the same (with a few new features), and the Payload Config is generally the same, with the breaking changes detailed below.
Payload is still headless, you will still be able to leverage it completely headlessly just as you do now with Sveltekit, etc. In fact, Payload itself is now _truly_ portable because it is fully Node.js compatible and completely separate from the HTTP layer. The entire Payload suite of packages has been modularized to make this possible.
### Table of Contents
## To migrate from Payload 2.0 to 3.0:
All breaking changes are listed below. If you encounter changes that are not explicitly listed here, please consider contributing to this documentation by submitting a PR.
- [Installation](#installation)
- [Breaking Changes](#breaking-changes)
- [Custom Components](#custom-components)
- [Endpoints](#endpoints)
- [React Hooks](#react-hooks)
- [Types](#types)
- [Email Adapters](#email-adapters)
- [Plugins](#plugins)
## Installation
Payload 3.0 requires a set of auto-generated files that you will need to bring into your existing project. The easiest way of acquiring these is by initializing a new project via `create-payload-app`, then replace the provided Payload Config with your own.
```bash
npx create-payload-app
```
For more details, see the [Documentation](https://payloadcms.com/docs/getting-started/installation).
1. **Install new dependencies of payload, next.js and react**:
Refer to the package.json file made in the create-payload-app, including peerDependencies, devDependencies, and dependencies. The core package and plugins require all versions to be synced. Previously, on 2.x it was possible to be running the latest version of payload 2.x with an older version of db-mongodb for example. This is no longer the case.
```bash
pnpm i next react react-dom payload @payloadcms/ui @payloadcms/next
```
Also install the other @payloadcms packages specific to the plugins and adapters you are using. Depending on your project, these may include:
- @payloadcms/db-mongodb
- @payloadcms/db-postgres
- @payloadcms/richtext-slate
- @payloadcms/richtext-lexical
- @payloadcms/plugin-form-builder
- @payloadcms/plugin-nested-docs
- @payloadcms/plugin-redirects
- @payloadcms/plugin-relationship
- @payloadcms/plugin-search
- @payloadcms/plugin-sentry
- @payloadcms/plugin-seo
- @payloadcms/plugin-stripe
- @payloadcms/plugin-cloud-storage - Read [More](#@payloadcms/plugin-cloud-storage).
1. Uninstall deprecated packages:
```bash
pnpm remove express nodemon @payloadcms/bundler-webpack @payloadcms/bundler-vite
```
1. For Payload Cloud users, the plugin has changed.
Uninstall the old package:
```bash
pnpm remove @payloadcms/plugin-cloud
```
Install the new package:
```bash
pnpm i @payloadcms/payload-cloud
```
```diff
// payload.config.ts
- import { payloadCloud } from '@payloadcms/plugin-cloud'
+ import { payloadCloudPlugin } from '@payloadcms/payload-cloud'
buildConfig({
// ...
plugins: [
- payloadCloud()
+ payloadCloudPlugin()
]
})
```
1. **Optional** sharp dependency
If you have upload enabled collections that use `formatOptions`, `imageSizes`, or `resizeOptions`—payload expects to have `sharp` installed. In 2.0 this was a dependency was installed for you. Now it is only installed if needed. If you have any of these options set, you will need to install `sharp` and add it to your payload.config.ts:
```bash
pnpm i sharp
```
```diff
// payload.config.ts
import sharp from 'sharp'
buildConfig({
// ...
+ sharp,
})
```
1. Database Adapter Migrations
If you have existing data and are using the MongoDB or Postgres adapters, you will need to run the database migrations to ensure your database schema is up-to-date. Follow the instructions from the release notes for [postgres](https://github.com/payloadcms/payload/releases/edit/v3.0.0-beta.39) or [mongodb](https://github.com/payloadcms/payload/releases/edit/v3.0.0-beta.131) depending on your chosen adapter.
## Breaking Changes
1. Delete the `admin.bundler` property from your Payload Config. Payload no longer bundles the Admin Panel. Instead, we rely directly on Next.js for bundling.
@@ -39,6 +145,23 @@ Payload is still headless, you will still be able to leverage it completely head
})
```
1. Environment variables prefixed with `PAYLOAD_PUBLIC` will no longer be available on the client. In order to access them on the client, those will now have to be prefixed with `NEXT_PUBLIC` instead.
```diff
'use client'
- const var = process.env.PAYLOAD_PUBLIC_MY_ENV_VAR
+ const var = process.env.NEXT_PUBLIC_MY_ENV_VAR
```
For more details, see the [Documentation](https://payloadcms.com/docs/configuration/environment-vars).
1. The `req` object used to extend the [Express Request](https://expressjs.com/), but now extends the [Web Request](https://developer.mozilla.org/en-US/docs/Web/API/Request). You may need to update your code accordingly to reflect this change. For example:
```diff
- req.headers['content-type']
+ req.headers.get('content-type')
```
1. The `admin.css` and `admin.scss` properties in the Payload Config have been removed.
```diff
@@ -133,6 +256,159 @@ Payload is still headless, you will still be able to leverage it completely head
}
```
1. Fields with `unique: true` now automatically be appended with “- Copy” through the new `admin.beforeDuplicate` field hooks (see previous bullet).
1. The `upload.staticDir` property must now be an absolute path. Before it would attempt to use the location of the Payload Config and merge the relative path set for staticDir.
```diff
// collections/Media.ts
import type { CollectionConfig } from 'payload'
import path from 'path'
+ import { fileURLToPath } from 'url'
+ const filename = fileURLToPath(import.meta.url)
+ const dirname = path.dirname(filename)
export const MediaCollection: CollectionConfig = {
slug: 'media',
upload: {
- staticDir: path.resolve(__dirname, './uploads'),
+ staticDir: path.resolve(dirname, '../uploads'),
},
}
```
1. The `upload.staticURL` property has been removed. If you were using this format URLs when using an external provider, you can leverage the `generateFileURL` functions in order to do the same.
```diff
// collections/Media.ts
import type { CollectionConfig } from 'payload'
export const MediaCollection: CollectionConfig = {
slug: 'media',
upload: {
- staticURL: '',
},
}
```
1. The `admin.favicon` property is now `admin.icons` and the types have changed:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
- favicon: 'path-to-favicon.svg',
+ icons: [{
+ path: 'path-to-favicon.svg',
+ sizes: '32x32'
+ }]
}
})
```
For more details, see the [Documentation](https://payloadcms.com/docs/admin/metadata#icons).
1. The `admin.meta.ogImage` property has been replaced by `admin.meta.openGraph.images`:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
meta: {
- ogImage: '',
+ openGraph: {
+ images: []
+ }
}
}
})
```
For more details, see the [Documentation](https://payloadcms.com/docs/admin/metadata#open-graph).
1. The args of the `admin.livePreview.url` function have changed. It no longer receives `documentInfo` as an arg, and instead, now has `collectionConfig` and `globalConfig`.
```diff
// payload.config.ts
import { buildConfig } from 'payload'
export default buildConfig({
// ...
admin: {
// ...
livePreview: ({
- documentInfo,
+ collectionConfig,
+ globalConfig
}) => ''
}
})
```
1. The `admin.logoutRoute` and `admin.inactivityRoute` properties have been consolidated into a single `admin.routes` property. To migrate, simply move those two keys as follows:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
- logoutRoute: '/custom-logout',
+ inactivityRoute: '/custom-inactivity'
+ routes: {
+ logout: '/custom-logout',
+ inactivity: '/custom-inactivity'
+ }
}
})
```
1. The `custom` property in the Payload Config, i.e. Collections, Globals, and Fields is now **server only** and will **not** appear in the client-side bundle. To add custom properties to the client bundle, use the new `admin.custom` property, which will be available on _both_ the server and the client.
```diff
// payload.config.ts
import { buildConfig } from 'payload'
export default buildConfig({
custom: {
someProperty: 'My Server Prop' // Now server only!
},
admin: {
+ custom: {
+ name: 'My Client Prop' // Available in server AND client
+ }
},
})
```
1. `hooks.afterError` is now an array of functions instead of a single function. The args have also been expanded. Read [More](https://payloadcms.com/docs/hooks/overview#root-hooks).
```diff
// payload.config.ts
import { buildConfig } from 'payload'
export default buildConfig({
hooks: {
- afterError: async ({ error }) => {
+ afterError: [
+ async ({ error, req, res }) => {
+ // ...
+ }
+ ]
}
})
```
## Custom Components
1. All Payload React components have been moved from the `payload` package to `@payloadcms/ui`. If you were previously importing components into your app from the `payload` package, for example to create Custom Components, you will need to change your import paths:
```diff
@@ -141,13 +417,6 @@ Payload is still headless, you will still be able to leverage it completely head
```
*Note: for brevity, not _all_ modules are listed here*
1. The `BlockField` and related types have been renamed to `BlocksField` for semantic accuracy.
```diff
- import type { BlockField, BlockFieldProps } from 'payload'
+ import type { BlocksField, BlocksFieldProps } from 'payload'
```
1. All Custom Components are now defined as _file paths_ instead of direct imports. If you are using Custom Components in your Payload Config, remove the imported module and point to the file's path instead:
```diff
@@ -167,7 +436,7 @@ Payload is still headless, you will still be able to leverage it completely head
})
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/admin/components#component-paths).
For more details, see the [Documentation](https://payloadcms.com/docs/admin/components#component-paths).
1. All Custom Components are now server-rendered by default, and therefore, cannot use state or hooks directly. If youre using Custom Components in your app that requires state or hooks, add the `'use client'` directive at the top of the file.
@@ -187,102 +456,186 @@ Payload is still headless, you will still be able to leverage it completely head
}
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/admin/components#client-components).
For more details, see the [Documentation](https://payloadcms.com/docs/admin/components#client-components).
1. The `custom` property in the Payload Config, i.e. Collections, Globals, and Fields is now **server only** and will **not** appear in the client-side bundle. To add custom properties to the client bundle, use the new `admin.custom` property, which will be available on _both_ the server and the client.
1. The `admin.description` property within Collection, Globals, and Fields no longer accepts a React Component. Instead, you must define it as a Custom Component.
1. For Collections, use the `admin.components.edit.Description` key:
```diff
// payload.config.ts
// collections/Posts.ts
import type { CollectionConfig } from 'payload'
- import { MyCustomDescription } from '../components/MyCustomDescription'
export const PostsCollection: CollectionConfig = {
slug: 'posts',
admin: {
- description: MyCustomDescription,
+ components: {
+ edit: {
+ Description: 'path/to/MyCustomDescription'
+ }
+ }
}
}
```
2. For Globals, use the `admin.components.elements.Description` key:
```diff
// globals/Site.ts
import type { GlobalConfig } from 'payload'
- import { MyCustomDescription } from '../components/MyCustomDescription'
export const SiteGlobal: GlobalConfig = {
slug: 'site',
admin: {
- description: MyCustomDescription,
+ components: {
+ elements: {
+ Description: 'path/to/MyCustomDescription'
+ }
+ }
}
}
```
3. For Fields, use the `admin.components.Description` key:
```diff
// fields/MyField.ts
import type { FieldConfig } from 'payload'
- import { MyCustomDescription } from '../components/MyCustomDescription'
export const MyField: FieldConfig = {
type: 'text',
admin: {
- description: MyCustomDescription,
+ components: {
+ Description: 'path/to/MyCustomDescription'
+ }
}
}
```
1. Array Field row labels and Collapsible Field label now _only_ accepts a React Component, and no longer accepts a plain string or record:
```diff
// file: Collection.tsx
import type { CollectionConfig } from 'payload'
- import { MyCustomRowLabel } from './components/MyCustomRowLabel.tsx'
export const MyCollection: CollectionConfig = {
slug: 'my-collection',
fields: [
{
name: 'my-array',
type: 'array',
admin: {
components: {
- RowLabel: 'My Array Row Label,
+ RowLabel: './components/RowLabel.ts'
}
},
fields: [...]
},
{
name: 'my-collapsible',
type: 'collapsible',
admin: {
components: {
- Label: 'My Collapsible Label',
+ Label: './components/RowLabel.ts'
}
},
fields: [...]
}
]
}
```
1. All default view keys are now camelcase:
For example, for Root Views:
```diff
// file: payload.config.ts
import { buildConfig } from 'payload'
export default buildConfig({
custom: {
someProperty: 'My Server Prop' // Now server only!
},
admin: {
+ custom: {
+ name: 'My Client Prop' // Available in server AND client
+ }
},
})
```
1. The `useTitle` hook has been consolidated into the `useDocumentInfo` hook. Instead, you can get title directly from document info context:
```diff
'use client'
- import { useTitle } from 'payload'
+ import { useDocumentInfo } from '@payloadcms/ui'
export const MyComponent = () => {
- const title = useTitle()
+ const { title } = useDocumentInfo()
// ...
}
```
1. The `Fields` type was renamed to `FormState` for improved semantics. If you were previously importing this type in your own application, simply change the import name:
```diff
- import type { Fields } from 'payload'
+ import type { FormState } from 'payload'
```
1. The `useDocumentInfo` hook no longer returns `collection` or `global`. Instead, various properties of the config are passed, like `collectionSlug` and `globalSlug`. You can use these to access a client-side config, if needed, through the `useConfig` hook (see next bullet).
```diff
'use client'
import { useDocumentInfo } from '@payloadcms/ui'
export const MyComponent = () => {
const {
- collection,
- global,
+ collectionSlug,
+ globalSlug
} = useDocumentInfo()
// ...
}
```
1. The `useConfig` hook now returns a `ClientConfig` and not a `SanitizedConfig`. This is because the config itself is not serializable and so it is not able to be thread through to the client. This means that all non-serializable props have been omitted from the Client Config, such as `db`, `bundler`, etc.
```diff
'use client'
- import { useConfig } from 'payload'
+ import { useConfig } from '@payloadcms/ui'
export const MyComponent = () => {
- const config = useConfig() // used to be a 'SanitizedConfig'
+ const { config } = useConfig() // now is a 'ClientConfig'
// ...
}
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/admin/components#accessing-the-payload-config).
1. The args of the `admin.livePreview.url` function have changed. It no longer receives `documentInfo` as an arg, and instead, now has `collectionConfig` and `globalConfig`.
```diff
// payload.config.ts
import { buildConfig } from 'payload'
export default buildConfig({
// ...
admin: {
// ...
livePreview: ({
- documentInfo,
+ collectionConfig,
+ globalConfig
}) => ''
admin: {
views: {
- Account: ...
+ account: ...
}
})
```
Or Document Views:
```diff
// file: Collection.tsx
import type { CollectionConfig } from 'payload'
export const MyCollection: CollectionConfig = {
slug: 'my-collection',
admin: {
views: {
- Edit: {
- Default: ...
- }
+ edit: {
+ default: ...
+ }
}
}
}
```
1. Custom Views within the config no longer accept React Components directly, instead, you must use their `Component` property:
```diff
// file: Collection.tsx
import type { CollectionConfig } from 'payload'
- import { MyCustomView } from './components/MyCustomView.tsx'
export const MyCollection: CollectionConfig = {
slug: 'my-collection',
admin: {
views: {
- Edit: MyCustomView
+ edit: {
+ Component: './components/MyCustomView.tsx'
+ }
}
}
}
```
This also means that Custom Root Views are no longer defined on the `edit` key. Instead, use the new `views.root` key:
```diff
// file: Collection.tsx
import type { CollectionConfig } from 'payload'
- import { MyCustomRootView } from './components/MyCustomRootView.tsx'
export const MyCollection: CollectionConfig = {
slug: 'my-collection',
admin: {
views: {
- Edit: MyCustomRootView
edit: {
+ root: {
+ Component: './components/MyCustomRootView.tsx'
+ }
}
}
}
}
```
1. The `href` and `isActive` functions on View Tabs no longer includes the `match` or `location` arguments. This is is a property specific to React Router, not Next.js. If you need to do URL matching similar to this, use a custom tab that fires of some hooks, i.e. `usePathname()` and run it through your own utility functions:
```diff
@@ -324,12 +677,12 @@ Payload is still headless, you will still be able to leverage it completely head
admin: {
components: {
- views: {
- edit: {
- Edit: {
- Tab: {
- pillLabel: 'Hello, world!',
- },
- },
+ Edit: {
+ edit: {
+ tab: {
+ Pill: './path/to/CustomPill.tsx',
+ }
@@ -340,106 +693,6 @@ Payload is still headless, you will still be able to leverage it completely head
}
```
1. Unique fields will now automatically be appended with “- Copy” through the new `admin.beforeDuplicate` field hooks (detailed aboved).
1. The `useCollapsible` hook has had slight changes to its property names. `collapsed` is now `isCollapsed` and `withinCollapsible` is now `isWithinCollapsible`.
```diff
'use client'
import { useCollapsible } from '@payloadcms/ui'
export const MyComponent = () => {
- const { collapsed, withinCollapsible } = useCollapsible()
+ const { isCollapsed, isWithinCollapsible } = useCollapsible()
}
```
1. The `admin.favicon` property is now `admin.icons` and the types have changed:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
- favicon: 'path-to-favicon.svg',
+ icons: [{
+ path: 'path-to-favicon.svg',
+ sizes: '32x32'
+ }]
}
})
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/admin/metadata#icons).
1. The `admin.meta.ogImage` property has been replaced by `admin.meta.openGraph.images`:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
meta: {
- ogImage: '',
+ openGraph: {
+ images: []
+ }
}
}
})
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/admin/metadata#open-graph).
1. The `admin.logoutRoute` and `admin.inactivityRoute` properties have been consolidated into a single `admin.routes` property. To migrate, simply move those two keys as follows:
```diff
// payload.config.ts
import { buildConfig } from 'payload'
const config = buildConfig({
// ...
admin: {
- logoutRoute: '/custom-logout',
+ inactivityRoute: '/custom-inactivity'
+ routes: {
+ logout: '/custom-logout',
+ inactivity: '/custom-inactivity'
+ }
}
})
```
1. Environment variables prefixed with `PAYLOAD_PUBLIC` will no longer be available on the client. In order to access them on the client, those will now have to be prefixed with `NEXT_PUBLIC` instead.
```diff
'use client'
- const var = process.env.PAYLOAD_PUBLIC_MY_ENV_VAR
+ const var = process.env.NEXT_PUBLIC_MY_ENV_VAR
```
For more details, see the [Documentation](https://payloadcms.com/docs/beta/configuration/environment-vars).
1. The `useTranslation` hook no longer takes any options, any translations using shorthand accessors will need to use the entire `group:key`
```diff
'use client'
- import { useTranslation } from 'payload'
+ import { useTranslation } from '@payloadcms/ui'
export const MyComponent = () => {
- const { i18n, t } = useTranslation('general')
+ const { i18n, t } = useTranslation()
- return <p>{t('cancel')}</p>
+ return <p>{t('general:cancel')}</p>
}
```
1. `react-i18n` was removed, the `Trans` component from `react-i18n` has been replaced with a Payload-provided solution:
```diff
@@ -467,7 +720,9 @@ Payload is still headless, you will still be able to leverage it completely head
}
```
1. All other endpoint handlers have changed. The args no longer include `res`, and `next`, and the return type now expects a valid HTTP [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) instead of `res.json`, `res.send`, etc.:
## Endpoints
1. All endpoint handlers have changed. The args no longer include `res`, and `next`, and the return type now expects a valid HTTP [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) instead of `res.json`, `res.send`, etc.:
```diff
// collections/Posts.ts
@@ -542,47 +797,102 @@ Payload is still headless, you will still be able to leverage it completely head
}
```
1. The `req` object used to extend the [Express Request](https://expressjs.com/), but now extends the [Web Request](https://developer.mozilla.org/en-US/docs/Web/API/Request). You may need to update your code accordingly to reflect this change. For example:
## React Hooks
1. The `useTitle` hook has been consolidated into the `useDocumentInfo` hook. Instead, you can get title directly from document info context:
```diff
- req.headers['content-type']
+ req.headers.get('content-type')
```
'use client'
- import { useTitle } from 'payload'
+ import { useDocumentInfo } from '@payloadcms/ui'
1. `staticDir` must now be an absolute path. Before it would attempt to use the location of the Payload Config and merge the relative path set for staticDir.
export const MyComponent = () => {
- const title = useTitle()
+ const { title } = useDocumentInfo()
```diff
// collections/Media.ts
import type { CollectionConfig } from 'payload'
import path from 'path'
+ import { fileURLToPath } from 'url'
+ const filename = fileURLToPath(import.meta.url)
+ const dirname = path.dirname(filename)
export const MediaCollection: CollectionConfig = {
slug: 'media',
upload: {
- staticDir: path.resolve(__dirname, './uploads'),
+ staticDir: path.resolve(dirname, '../uploads'),
},
// ...
}
```
1. `staticURL` has been removed. If you were using this format URLs when using an external provider, you can leverage the `generateFileURL` functions in order to do the same.
1. The `useDocumentInfo` hook no longer returns `collection` or `global`. Instead, various properties of the config are passed, like `collectionSlug` and `globalSlug`. You can use these to access a client-side config, if needed, through the `useConfig` hook (see next bullet).
```diff
// collections/Media.ts
import type { CollectionConfig } from 'payload'
'use client'
import { useDocumentInfo } from '@payloadcms/ui'
export const MediaCollection: CollectionConfig = {
slug: 'media',
upload: {
- staticURL: '',
},
export const MyComponent = () => {
const {
- collection,
- global,
+ collectionSlug,
+ globalSlug
} = useDocumentInfo()
// ...
}
```
1. The `useConfig` hook now returns a `ClientConfig` and not a `SanitizedConfig`. This is because the config itself is not serializable and so it is not able to be thread through to the client. This means that all non-serializable props have been omitted from the Client Config, such as `db`, `bundler`, etc.
```diff
'use client'
- import { useConfig } from 'payload'
+ import { useConfig } from '@payloadcms/ui'
export const MyComponent = () => {
- const config = useConfig() // used to be a 'SanitizedConfig'
+ const { config } = useConfig() // now is a 'ClientConfig'
// ...
}
```
For more details, see the [Documentation](https://payloadcms.com/docs/admin/components#accessing-the-payload-config).
1. The `useCollapsible` hook has had slight changes to its property names. `collapsed` is now `isCollapsed` and `withinCollapsible` is now `isWithinCollapsible`.
```diff
'use client'
import { useCollapsible } from '@payloadcms/ui'
export const MyComponent = () => {
- const { collapsed, withinCollapsible } = useCollapsible()
+ const { isCollapsed, isWithinCollapsible } = useCollapsible()
}
```
1. The `useTranslation` hook no longer takes any options, any translations using shorthand accessors will need to use the entire `group:key`
```diff
'use client'
- import { useTranslation } from 'payload'
+ import { useTranslation } from '@payloadcms/ui'
export const MyComponent = () => {
- const { i18n, t } = useTranslation('general')
+ const { i18n, t } = useTranslation()
- return <p>{t('cancel')}</p>
+ return <p>{t('general:cancel')}</p>
}
```
## Types
1. The `Fields` type was renamed to `FormState` for improved semantics. If you were previously importing this type in your own application, simply change the import name:
```diff
- import type { Fields } from 'payload'
+ import type { FormState } from 'payload'
```
1. The `BlockField` and related types have been renamed to `BlocksField` for semantic accuracy.
```diff
- import type { BlockField, BlockFieldProps } from 'payload'
+ import type { BlocksField, BlocksFieldProps } from 'payload'
```
## Email Adapters
Email functionality has been abstracted out into email adapters.
@@ -647,7 +957,7 @@ export default buildConfig({
- Now only available if using custom server and using express or similar
# Plugins
## Plugins
1. *All* plugins have been standardized to use _named exports_ (as opposed to default exports). Most also have a suffix of `Plugin` to make it clear what is being imported.
@@ -669,11 +979,11 @@ export default buildConfig({
- If you have created a custom adapter, the type must now provide a `name` property.
| Service | Package |
| -------------------- | ---------------------------------------------------------------------------- |
| Vercel Blob | https://github.com/payloadcms/payload/tree/beta/packages/storage-vercel-blob |
| AWS S3 | https://github.com/payloadcms/payload/tree/beta/packages/storage-s3 |
| Azure | https://github.com/payloadcms/payload/tree/beta/packages/storage-azure |
| Google Cloud Storage | https://github.com/payloadcms/payload/tree/beta/packages/storage-gcs |
| -------------------- |------------------------------------------------------------------------------|
| Vercel Blob | https://github.com/payloadcms/payload/tree/main/packages/storage-vercel-blob |
| AWS S3 | https://github.com/payloadcms/payload/tree/main/packages/storage-s3 |
| Azure | https://github.com/payloadcms/payload/tree/main/packages/storage-azure |
| Google Cloud Storage | https://github.com/payloadcms/payload/tree/main/packages/storage-gcs |
```tsx
// ❌ Before (required peer dependencies depending on adapter)
@@ -785,4 +1095,4 @@ plugins: [
## `@payloadcms/richtext-lexical`
// TODO: Add migration guide for `@payloadcms/richtext-lexical`
If you have custom features for `@payloadcms/richtext-lexical` you will need to migrate your code to the new API. Read more about the new API in the [documentation](https://payloadcms.com/docs/lexical/building-custom-features).

View File

@@ -36,7 +36,7 @@ Forms can be as simple or complex as you need, from a basic contact form, to a m
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-form-builder@beta
pnpm add @payloadcms/plugin-form-builder
```
## Basic Usage

View File

@@ -48,7 +48,7 @@ Install the plugin using any JavaScript package manager like [Yarn](https://yarn
or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-nested-docs@beta
pnpm add @payloadcms/plugin-nested-docs
```
## Basic Usage
@@ -238,10 +238,4 @@ import { PluginConfig, GenerateURL, GenerateLabel } from '@payloadcms/plugin-nes
## Examples
The [Examples Directory](https://github.com/payloadcms/payload/tree/main/examples) contains an
official [Nested Docs Plugin Example](https://github.com/payloadcms/payload/tree/main/examples/nested-docs) which
demonstrates exactly how to configure this plugin in Payload and implement it on your front-end.
The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an
official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website)
and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommerce), both of which use this
plugin.
The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website) and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommerce), both of which use this plugin.

View File

@@ -32,7 +32,7 @@ For example, if you have a page at `/about` and you want to change it to `/about
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-redirects@beta
pnpm add @payloadcms/plugin-redirects
```
## Basic Usage
@@ -102,4 +102,4 @@ import { PluginConfig } from '@payloadcms/plugin-redirects/types'
## Examples
The [Examples Directory](https://github.com/payloadcms/payload/tree/main/examples) contains an official [Redirects Plugin Example](https://github.com/payloadcms/payload/tree/main/examples/redirects) which demonstrates exactly how to configure this plugin in Payload and implement it on your front-end. The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website) and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommere), both of which use this plugin.
The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website) and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommerce), both of which use this plugin.

View File

@@ -39,7 +39,7 @@ This plugin is a great way to implement a fast, immersive search experience such
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-search@beta
pnpm add @payloadcms/plugin-search
```
## Basic Usage

View File

@@ -31,7 +31,7 @@ This multi-faceted software offers a range of features that will help you manage
- **Integrations**: Connects with various tools and services for enhanced workflow and issue management
<Banner type="info">
This plugin is completely open-source and the [source code can be found here](https://github.com/payloadcms/payload/tree/beta/packages/plugin-sentry). If you need help, check out our [Community Help](https://payloadcms.com/community-help). If you think you've found a bug, please [open a new issue](https://github.com/payloadcms/payload/issues/new?assignees=&labels=plugin%3A%20seo&template=bug_report.md&title=plugin-sentry%3A) with as much detail as possible.
This plugin is completely open-source and the [source code can be found here](https://github.com/payloadcms/payload/tree/main/packages/plugin-sentry). If you need help, check out our [Community Help](https://payloadcms.com/community-help). If you think you've found a bug, please [open a new issue](https://github.com/payloadcms/payload/issues/new?assignees=&labels=plugin%3A%20seo&template=bug_report.md&title=plugin-sentry%3A) with as much detail as possible.
</Banner>
## Installation
@@ -39,7 +39,7 @@ This multi-faceted software offers a range of features that will help you manage
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-sentry@beta
pnpm add @payloadcms/plugin-sentry
```
## Sentry for Next.js setup

View File

@@ -37,7 +37,7 @@ To help you visualize what your page might look like in a search engine, a previ
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-seo@beta
pnpm add @payloadcms/plugin-seo
```
## Basic Usage

View File

@@ -39,7 +39,7 @@ The beauty of this plugin is the entirety of your application's content and busi
Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io):
```bash
pnpm add @payloadcms/plugin-stripe@beta
pnpm add @payloadcms/plugin-stripe
```
## Basic Usage

View File

@@ -147,11 +147,11 @@ But, if you do, and you still want to use an ephemeral filesystem provider, you
Payload provides a list of official cloud storage adapters for you to use:
- [Azure Blob Storage](https://github.com/payloadcms/payload/tree/beta/packages/storage-azure)
- [Google Cloud Storage](https://github.com/payloadcms/payload/tree/beta/packages/storage-gcs)
- [AWS S3](https://github.com/payloadcms/payload/tree/beta/packages/storage-s3)
- [Uploadthing](https://github.com/payloadcms/payload/tree/beta/packages/storage-uploadthing)
- [Vercel Blob Storage](https://github.com/payloadcms/payload/tree/beta/packages/storage-vercel-blob)
- [Azure Blob Storage](https://github.com/payloadcms/payload/tree/main/packages/storage-azure)
- [Google Cloud Storage](https://github.com/payloadcms/payload/tree/main/packages/storage-gcs)
- [AWS S3](https://github.com/payloadcms/payload/tree/main/packages/storage-s3)
- [Uploadthing](https://github.com/payloadcms/payload/tree/main/packages/storage-uploadthing)
- [Vercel Blob Storage](https://github.com/payloadcms/payload/tree/main/packages/storage-vercel-blob)
Follow the docs to configure any one of these storage providers. For local development, it might be handy to simply store uploads on your own computer, and then when it comes to production, simply enable the plugin for the cloud storage vendor of your choice.

View File

@@ -107,9 +107,9 @@ const getPosts = async () => {
The `defaultPopulate` property allows you specify which fields to select when populating the collection from another document.
This is especially useful for links where only the `slug` is needed instead of the entire document.
With this feature, you can dramatically reduce the amount of JSON that is populated from [Relationship](/docs/beta/fields/relationship) or [Upload](/docs/beta/fields/upload) fields.
With this feature, you can dramatically reduce the amount of JSON that is populated from [Relationship](/docs/fields/relationship) or [Upload](/docs/fields/upload) fields.
For example, in your content model, you might have a `Link` field which links out to a different page. When you go to retrieve these links, you really only need the `slug` of the page.
For example, in your content model, you might have a `Link` field which links out to a different page. When you go to retrieve these links, you really only need the `slug` of the page.
Loading all of the page content, its related links, and everything else is going to be overkill and will bog down your Payload APIs. Instead, you can define the `defaultPopulate` property on your `Pages` collection, so that when Payload "populates" a related Page, it only selects the `slug` field and therefore returns significantly less JSON:

View File

@@ -9,7 +9,7 @@ keywords: slatejs, lexical, rich text, json, custom editor, javascript, typescri
Payload currently supports two official rich text editors and you can choose either one depending on your needs.
1. [SlateJS](/docs/rich-text/slate) - stable, backwards-compatible with 1.0
2. [Lexical](/docs/lexical/overview) - beta, where things will be moving in the future
2. [Lexical](/docs/lexical/overview) - recommended
These editors are built on an "adapter pattern" which means that you will need to install the editor you'd like to use. Take a look at the docs for the editor you'd like to use for instructions on how to install it.

View File

@@ -9,12 +9,12 @@ keywords: uploads, images, media, storage, adapters, s3, vercel, google cloud, a
Payload offers additional storage adapters to handle file uploads. These adapters allow you to store files in different locations, such as Amazon S3, Vercel Blob Storage, Google Cloud Storage, and more.
| Service | Package |
| -------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Vercel Blob | [`@payloadcms/storage-vercel-blob`](https://github.com/payloadcms/payload/tree/beta/packages/storage-vercel-blob) |
| AWS S3 | [`@payloadcms/storage-s3`](https://github.com/payloadcms/payload/tree/beta/packages/storage-s3) |
| Azure | [`@payloadcms/storage-azure`](https://github.com/payloadcms/payload/tree/beta/packages/storage-azure) |
| Google Cloud Storage | [`@payloadcms/storage-gcs`](https://github.com/payloadcms/payload/tree/beta/packages/storage-gcs) |
| Uploadthing | [`@payloadcms/storage-uploadthing`](https://github.com/payloadcms/payload/tree/beta/packages/uploadthing) |
| -------------------- |-------------------------------------------------------------------------------------------------------------------|
| Vercel Blob | [`@payloadcms/storage-vercel-blob`](https://github.com/payloadcms/payload/tree/main/packages/storage-vercel-blob) |
| AWS S3 | [`@payloadcms/storage-s3`](https://github.com/payloadcms/payload/tree/main/packages/storage-s3) |
| Azure | [`@payloadcms/storage-azure`](https://github.com/payloadcms/payload/tree/main/packages/storage-azure) |
| Google Cloud Storage | [`@payloadcms/storage-gcs`](https://github.com/payloadcms/payload/tree/main/packages/storage-gcs) |
| Uploadthing | [`@payloadcms/storage-uploadthing`](https://github.com/payloadcms/payload/tree/main/packages/uploadthing) |
## Vercel Blob Storage
[`@payloadcms/storage-vercel-blob`](https://www.npmjs.com/package/@payloadcms/storage-vercel-blob)
@@ -22,7 +22,7 @@ Payload offers additional storage adapters to handle file uploads. These adapter
### Installation
```sh
pnpm add @payloadcms/storage-vercel-blob@beta
pnpm add @payloadcms/storage-vercel-blob
```
### Usage
@@ -71,7 +71,7 @@ export default buildConfig({
### Installation
```sh
pnpm add @payloadcms/storage-s3@beta
pnpm add @payloadcms/storage-s3
```
### Usage
@@ -119,7 +119,7 @@ See the the [AWS SDK Package](https://github.com/aws/aws-sdk-js-v3) and [`S3Clie
### Installation
```sh
pnpm add @payloadcms/storage-azure@beta
pnpm add @payloadcms/storage-azure
```
### Usage
@@ -168,7 +168,7 @@ export default buildConfig({
### Installation
```sh
pnpm add @payloadcms/storage-gcs@beta
pnpm add @payloadcms/storage-gcs
```
### Usage
@@ -218,7 +218,7 @@ export default buildConfig({
### Installation
```sh
pnpm add @payloadcms/storage-uploadthing@beta
pnpm add @payloadcms/storage-uploadthing
```
### Usage
@@ -261,7 +261,7 @@ If you need to create a custom storage adapter, you can use the [`@payloadcms/pl
### Installation
`pnpm add @payloadcms/plugin-cloud-storage@beta`
`pnpm add @payloadcms/plugin-cloud-storage`
### Usage

View File

@@ -28,7 +28,7 @@ export const rootParserOptions = {
ecmaVersion: 'latest',
projectService: {
maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING: 40,
allowDefaultProject: ['scripts/*.ts', '*.js', '*.mjs', '*.spec.ts', '*.d.ts'],
allowDefaultProject: ['scripts/*.ts', '*.js', '*.mjs', '*.d.ts'],
},
}

View File

@@ -1,27 +1,26 @@
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import React from 'react'
import { Gutter } from '../Gutter'
import { HeaderNav } from './Nav'
import classes from './index.module.scss'
import { HeaderNav } from './Nav'
export function Header() {
return (
<header className={classes.header}>
<Gutter className={classes.wrap}>
<Link href="/" className={classes.logo}>
<Link className={classes.logo} href="/">
<picture>
<source
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg"
/>
<Image
width={150}
height={30}
alt="Payload Logo"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
height={30}
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg"
width={150}
/>
</picture>
</Link>

View File

@@ -1,27 +1,26 @@
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import React from 'react'
import { Gutter } from '../Gutter'
import { HeaderNav } from './Nav'
import classes from './index.module.scss'
import { HeaderNav } from './Nav'
export const Header: React.FC = () => {
return (
<header className={classes.header}>
<Gutter className={classes.wrap}>
<Link href="/" className={classes.logo}>
<Link className={classes.logo} href="/">
<picture>
<source
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg"
/>
<Image
width={150}
height={30}
alt="Payload Logo"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
height={30}
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg"
width={150}
/>
</picture>
</Link>

View File

@@ -48,12 +48,12 @@ See the [Collections](https://payloadcms.com/docs/configuration/collections) doc
```ts
import { headers as getHeaders } from 'next/headers.js'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { getPayload } from 'payload'
import config from '../../payload.config'
export default async function AccountPage({ searchParams }) {
const headers = getHeaders()
const payload = await getPayloadHMR({ config: configPromise })
const payload = await getPayload({ config: configPromise })
const { permissions, user } = await payload.auth({ headers })
if (!user) {

View File

@@ -3,8 +3,8 @@ import Link from 'next/link'
import React from 'react'
import { Gutter } from '../Gutter'
import { HeaderNav } from './Nav'
import classes from './index.module.scss'
import { HeaderNav } from './Nav'
export function Header() {
return (
@@ -14,12 +14,12 @@ export function Header() {
<picture>
<source
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg"
/>
<Image
alt="Payload Logo"
height={30}
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg"
width={150}
/>
</picture>

View File

@@ -1,7 +1,7 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import React, { Fragment } from 'react'
import config from '../../../payload.config'
@@ -14,7 +14,7 @@ import classes from './index.module.scss'
export default async function Account() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { permissions, user } = await payload.auth({ headers })
if (!user) {

View File

@@ -1,6 +1,6 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import React from 'react'
import config from '../../../payload.config'
@@ -11,7 +11,7 @@ import classes from './index.module.scss'
export default async function CreateAccount() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { user } = await payload.auth({ headers })
if (user) {

View File

@@ -1,17 +1,17 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import React from 'react'
import config from '../../../payload.config'
import { Gutter } from '../_components/Gutter'
import { RenderParams } from '../_components/RenderParams'
import { LoginForm } from './LoginForm'
import classes from './index.module.scss'
import { LoginForm } from './LoginForm'
export default async function Login() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { user } = await payload.auth({ headers })
if (user) {

View File

@@ -1,16 +1,16 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import Link from 'next/link'
import { getPayload } from 'payload'
import React from 'react'
import config from '../../../payload.config'
import { Gutter } from '../_components/Gutter'
import { LogoutPage } from './LogoutPage'
import classes from './index.module.scss'
import { LogoutPage } from './LogoutPage'
export default async function Logout() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { user } = await payload.auth({ headers })
if (!user) {

View File

@@ -1,6 +1,6 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import Link from 'next/link'
import { getPayload } from 'payload'
import React, { Fragment } from 'react'
import config from '../../payload.config'
@@ -9,7 +9,7 @@ import { HydrateClientUser } from './_components/HydrateClientUser'
export default async function HomePage() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { permissions, user } = await payload.auth({ headers })
return (

View File

@@ -1,16 +1,16 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import React from 'react'
import config from '../../../payload.config'
import { Gutter } from '../_components/Gutter'
import { RecoverPasswordForm } from './RecoverPasswordForm'
import classes from './index.module.scss'
import { RecoverPasswordForm } from './RecoverPasswordForm'
export default async function RecoverPassword() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { user } = await payload.auth({ headers })
if (user) {

View File

@@ -1,16 +1,16 @@
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { headers as getHeaders } from 'next/headers.js'
import { redirect } from 'next/navigation'
import { getPayload } from 'payload'
import React from 'react'
import config from '../../../payload.config'
import { Gutter } from '../_components/Gutter'
import { ResetPasswordForm } from './ResetPasswordForm'
import classes from './index.module.scss'
import { ResetPasswordForm } from './ResetPasswordForm'
export default async function ResetPassword() {
const headers = getHeaders()
const payload = await getPayloadHMR({ config })
const payload = await getPayload({ config })
const { user } = await payload.auth({ headers })
if (user) {

View File

@@ -1,6 +0,0 @@
DATABASE_URI=mongodb://127.0.0.1/payload-example-custom-server
PAYLOAD_SECRET=PAYLOAD_CUSTOM_SERVER_EXAMPLE_SECRET_KEY
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000
NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000
PAYLOAD_PUBLIC_SEED=true
PAYLOAD_DROP_DATABASE=true

View File

@@ -1,5 +0,0 @@
module.exports = {
root: true,
extends: ['plugin:@next/next/recommended', '@payloadcms'],
ignorePatterns: ['**/payload-types.ts'],
}

View File

@@ -1,4 +0,0 @@
build
dist
node_modules
package - lock.json.env.next.vercel

View File

@@ -1 +0,0 @@
**/payload-types.ts

View File

@@ -1,121 +0,0 @@
# Payload Custom Server Example
This example demonstrates how to serve your front-end alongside [Payload](https://github.com/payloadcms/payload) in a single Express server. This pattern will cut down on hosting costs and can simplify your deployment process.
## Quick Start
To spin up this example locally, follow these steps:
1. First clone the repo
1. Then `cd YOUR_PROJECT_REPO && cp .env.example .env`
1. Next `yarn && yarn dev`
1. Now `open http://localhost:3000/admin` to access the admin panel
1. Login with email `demo@payloadcms.com` and password `demo`
That's it! Changes made in `./src` will be reflected in your app. See the [Development](#development) section for more details.
## How it works
When you use Payload, you plug it into _**your**_ Express server. That's a fundamental difference between Payload and other application frameworks. It means that when you use Payload, you're technically _adding_ Payload to _your_ app, and not building a "Payload app".
One of the strengths of this pattern is that it lets you do powerful things like integrate your Payload instance directly with your front-end. This will allow you to host Payload alongside a fully dynamic, CMS-integrated website or app on a single, combined server—while still getting all of the benefits of a headless CMS.
### Express
In every Payload app is a `server.ts` file in which you instantiate your own Express server and attach Payload to it. This is where you can can add any custom Express middleware or routes you need to serve your front-end. To combine Payload with your framework on the same server, we need to do three main things:
1. Modify your `server.ts` file to build and serve your front-end using the APIs provided by your framework
2. Modify your `package.json` scripts include your framework's build commands
3. Use a separate `tsconfig.server.json` file to build the server, because your front-end may require incompatible TypeScript settings
This example demonstrates how to do this with [Next.js](https://nextjs.org), although the same principles apply to any front-end framework like [Vue](https://vuejs.org), [Nuxt](https://nuxt.com), or [SvelteKit](https://kit.svelte.dev). If your framework does not yet have instructions listed here, please consider contributing them to this example for others to use. To quickly eject Next.js from this example, see the [Eject](#eject) section.
#### Next.js
For Next.js apps, your `server.ts` file looks something like this:
```ts
import next from 'next'
import nextBuild from 'next/dist/build'
// Instantiate Express and Payload
// ...
// If building, start the server to build the Next.js app then exit
if (process.env.NEXT_BUILD) {
app.listen(3000, async () => {
await nextBuild(path.join(__dirname, '../'))
process.exit()
})
return
}
// Attach Next.js routes and start the server
const nextApp = next({
dev: process.env.NODE_ENV !== 'production',
})
const nextHandler = nextApp.getRequestHandler()
app.get('*', (req, res) => nextHandler(req, res))
nextApp.prepare().then(() => {
app.listen(3000)
})
```
Check out the [server.ts](./src/server.ts) in this repository for a complete working example. You can also see the [Next.js docs](https://nextjs.org/docs/advanced-features/custom-server) for more details.
Then your `package.json` might look something like this:
```json
// ...
"scripts": {
// ...
"build:payload": "payload build",
"build:server": "tsc --project tsconfig.server.json",
"build:next": "next build",
"build": "yarn build:payload && yarn build:server && yarn build:next",
}
```
Check out the [package.json](./src/package.json) in this repository for a complete working example. You can also see the [Next.js docs](https://nextjs.org/docs/api-reference/cli#build) for more details.
## Eject
If you prefer another front-end framework or would like to use Payload as a standalone CMS, you can easily eject the front-end from this template. To eject, simply run `yarn eject`. This will uninstall all Next.js related dependencies and delete all files and folders related to the Next.js front-end. It also removes all custom routing from your `server.ts` file and updates your `eslintrc.js`.
> Note: Your eject script may not work as expected if you've made significant modifications to your project. If you run into any issues, compare your project's dependencies and file structure with this template, see [./src/eject](./src/eject) for full details.
## Development
To spin up this example locally, follow the [Quick Start](#quick-start).
### Seed
On boot, a seed script is included to scaffold a basic database for you to use as an example. This is done by setting the `PAYLOAD_DROP_DATABASE` and `PAYLOAD_PUBLIC_SEED` environment variables which are included in the `.env.example` by default. You can remove these from your `.env` to prevent this behavior. You can also freshly seed your project at any time by running `yarn seed`. This seed creates an admin user with email `demo@payloadcms.com`, password `demo`, and a `home` page.
> NOTICE: seeding the database is destructive because it drops your current database to populate a fresh one from the seed template. Only run this command if you are starting a new project or can afford to lose your current data.
### Conflicting routes
> In a monorepo when routes are bootstrapped to the same host, they can conflict with Payload's own routes if they have the same name. In our template we've named the Nextjs API routes to `next` to avoid this conflict.
>
> This can happen with any other routes conflicting with Payload such as `admin` and we recommend using different names for custom routes.
> Alternatively you can also rename Payload's own routes via the [configuration](https://payloadcms.com/docs/configuration/overview).
## Production
To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps:
1. First, invoke the `payload build` script by running `yarn build` or `npm run build` in your project root. This creates a `./build` directory with a production-ready admin bundle.
1. Then, run `yarn serve` or `npm run serve` to run Node in production and serve Payload from the `./build` directory.
### Deployment
The easiest way to deploy your project is to use [Payload Cloud](https://payloadcms.com/new/import), a one-click hosting solution to deploy production-ready instances of your Payload apps directly from your GitHub repo. You can also choose to self-host your app, check out the [Deployment](https://payloadcms.com/docs/production/deployment) docs for more details.
## Questions
If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions).

View File

@@ -1,36 +0,0 @@
import fs from 'fs'
import path from 'path'
// Run this script to eject the front-end from this template
// This will remove all template-specific files and directories
// See `yarn eject` in `package.json` for the exact command
// See `./README.md#eject` for more information
const files = ['./next.config.js', './next-env.d.ts']
const directories = ['./src/app']
const eject = async (): Promise<void> => {
files.forEach((file) => {
fs.unlinkSync(path.join(__dirname, file))
})
directories.forEach((directory) => {
fs.rm(path.join(__dirname, directory), { recursive: true }, (err) => {
if (err) throw err
})
})
// create a new `./src/server.ts` file
// use contents from `./src/server.default.ts`
const serverFile = path.join(__dirname, './src/server.ts')
const serverDefaultFile = path.join(__dirname, './src/server.default.ts')
fs.copyFileSync(serverDefaultFile, serverFile)
// remove `'plugin:@next/next/recommended', ` from `./.eslintrc.js`
const eslintConfigFile = path.join(__dirname, './.eslintrc.js')
const eslintConfig = fs.readFileSync(eslintConfigFile, 'utf8')
const updatedEslintConfig = eslintConfig.replace(`'plugin:@next/next/recommended', `, '')
fs.writeFileSync(eslintConfigFile, updatedEslintConfig, 'utf8')
}
eject()

View File

@@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View File

@@ -1,9 +0,0 @@
require('dotenv').config()
module.exports = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: ['localhost', process.env.NEXT_PUBLIC_PAYLOAD_URL],
},
}

View File

@@ -1,6 +0,0 @@
{
"watch": ["server.ts"],
"exec": "ts-node --project tsconfig.server.json src/server.ts -- -I",
"ext": "js ts",
"stdin": false
}

View File

@@ -1,58 +0,0 @@
{
"name": "payload-example-custom-server",
"description": "Payload custom server example.",
"version": "1.0.0",
"main": "dist/server.js",
"license": "MIT",
"scripts": {
"dev": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts nodemon",
"seed": "rm -rf media && cross-env PAYLOAD_PUBLIC_SEED=true PAYLOAD_DROP_DATABASE=true PAYLOAD_CONFIG_PATH=src/payload.config.ts ts-node src/server.ts",
"build:payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
"build:server": "tsc --project tsconfig.server.json",
"build:next": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NEXT_BUILD=true node dist/server.js",
"build": "cross-env NODE_ENV=production yarn build:payload && yarn build:server && yarn copyfiles && yarn build:next",
"serve": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js",
"eject": "yarn remove next react react-dom @next/eslint-plugin-next && ts-node eject.ts",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png}\" dist/",
"generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
"generate:graphQLSchema": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:graphQLSchema",
"lint": "eslint src",
"lint:fix": "eslint --fix --ext .ts,.tsx src"
},
"dependencies": {
"@payloadcms/bundler-webpack": "latest",
"@payloadcms/db-mongodb": "latest",
"@payloadcms/richtext-slate": "latest",
"dotenv": "^8.2.0",
"escape-html": "^1.0.3",
"express": "^4.17.1",
"next": "^13.4.8",
"payload": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@next/eslint-plugin-next": "^13.1.6",
"@payloadcms/eslint-config": "^0.0.2",
"@types/escape-html": "^1.0.2",
"@types/express": "^4.17.9",
"@types/node": "18.11.3",
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.6",
"@typescript-eslint/eslint-plugin": "^5.51.0",
"@typescript-eslint/parser": "^5.51.0",
"copyfiles": "^2.4.1",
"cross-env": "^7.0.3",
"eslint": "^8.19.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-filenames": "^1.3.2",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-simple-import-sort": "^10.0.0",
"nodemon": "^2.0.22",
"prettier": "^2.7.1",
"ts-node": "10.9.1",
"typescript": "^4.8.4"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -1,15 +0,0 @@
<svg width="260" height="260" viewBox="0 0 260 260" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
path {
fill: #0F0F0F;
}
@media (prefers-color-scheme: dark) {
path {
fill: white;
}
}
</style>
<path d="M120.59 8.5824L231.788 75.6142V202.829L148.039 251.418V124.203L36.7866 57.2249L120.59 8.5824Z" />
<path d="M112.123 244.353V145.073L28.2114 193.769L112.123 244.353Z" />
</svg>

Before

Width:  |  Height:  |  Size: 437 B

View File

@@ -1,7 +0,0 @@
.gutterLeft {
padding-left: var(--gutter-h);
}
.gutterRight {
padding-right: var(--gutter-h);
}

View File

@@ -1,33 +0,0 @@
import React, { forwardRef, Ref } from 'react'
import classes from './index.module.scss'
type Props = {
left?: boolean
right?: boolean
className?: string
children: React.ReactNode
ref?: Ref<HTMLDivElement>
}
export const Gutter: React.FC<Props> = forwardRef<HTMLDivElement, Props>((props, ref) => {
const { left = true, right = true, className, children } = props
return (
<div
ref={ref}
className={[
left && classes.gutterLeft,
right && classes.gutterRight,
className,
classes.gutter,
]
.filter(Boolean)
.join(' ')}
>
{children}
</div>
)
})
Gutter.displayName = 'Gutter'

View File

@@ -1,180 +0,0 @@
import React, { Fragment } from 'react'
import escapeHTML from 'escape-html'
import Link from 'next/link'
type Node = {
type: string
value?: {
url: string
alt: string
}
children?: Node[]
url?: string
[key: string]: unknown
newTab?: boolean
}
export type CustomRenderers = {
[key: string]: (args: { node: Node; Serialize: SerializeFunction; index: number }) => JSX.Element // eslint-disable-line
}
type SerializeFunction = React.FC<{
content?: Node[]
customRenderers?: CustomRenderers
}>
const isText = (value: any): boolean =>
typeof value === 'object' && value !== null && typeof value.text === 'string'
export const Serialize: SerializeFunction = ({ content, customRenderers }) => {
return (
<Fragment>
{content?.map((node, i) => {
if (isText(node)) {
// @ts-expect-error
let text = <span dangerouslySetInnerHTML={{ __html: escapeHTML(node.text) }} />
if (node.bold) {
text = <strong key={i}>{text}</strong>
}
if (node.code) {
text = <code key={i}>{text}</code>
}
if (node.italic) {
text = <em key={i}>{text}</em>
}
if (node.underline) {
text = (
<span style={{ textDecoration: 'underline' }} key={i}>
{text}
</span>
)
}
if (node.strikethrough) {
text = (
<span style={{ textDecoration: 'line-through' }} key={i}>
{text}
</span>
)
}
return <Fragment key={i}>{text}</Fragment>
}
if (!node) {
return null
}
if (
customRenderers &&
customRenderers[node.type] &&
typeof customRenderers[node.type] === 'function'
) {
return customRenderers[node.type]({ node, Serialize, index: i })
}
switch (node.type) {
case 'br':
return <br key={i} />
case 'h1':
return (
<h1 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h1>
)
case 'h2':
return (
<h2 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h2>
)
case 'h3':
return (
<h3 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h3>
)
case 'h4':
return (
<h4 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h4>
)
case 'h5':
return (
<h5 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h5>
)
case 'h6':
return (
<h6 key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</h6>
)
case 'quote':
return (
<blockquote key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</blockquote>
)
case 'ul':
return (
<ul key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</ul>
)
case 'ol':
return (
<ol key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</ol>
)
case 'li':
return (
<li key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</li>
)
case 'link':
return (
<Link
href={escapeHTML(node.url)}
key={i}
{...(node.newTab
? {
target: '_blank',
rel: 'noopener noreferrer',
}
: {})}
>
<Serialize content={node.children} customRenderers={customRenderers} />
</Link>
)
default:
return (
<p key={i}>
<Serialize content={node.children} customRenderers={customRenderers} />
</p>
)
}
})}
</Fragment>
)
}

View File

@@ -1,20 +0,0 @@
.richText {
text-align: center; // hack but whatever
max-width: 1000px;
a {
text-decoration: underline;
}
:first-child {
margin-top: 0;
}
:last-child {
margin-bottom: 0;
}
span {
white-space: pre-wrap;
}
}

View File

@@ -1,23 +0,0 @@
'use client'
import React from 'react'
import { CustomRenderers, Serialize as SerializeContent } from './Serialize'
import classes from './index.module.scss'
export const RichText: React.FC<{
className?: string
content: any
customRenderers?: CustomRenderers
}> = ({ className, content, customRenderers }) => {
if (!content) {
return null
}
return (
<div className={[classes.richText, className].filter(Boolean).join(' ')}>
<SerializeContent content={content} customRenderers={customRenderers} />
</div>
)
}

View File

@@ -1,118 +0,0 @@
$breakpoint: 1000px;
:root {
--max-width: 1600px;
--foreground-rgb: 0, 0, 0;
--background-rgb: 255, 255, 255;
--block-spacing: 2rem;
--gutter-h: 4rem;
--base: 1rem;
@media (max-width: $breakpoint) {
--block-spacing: 1rem;
--gutter-h: 2rem;
--base: 0.75rem;
}
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-rgb: 7, 7, 7;
}
}
* {
box-sizing: border-box;
}
html {
font-size: 20px;
line-height: 1.5;
font-family:
system-ui,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Open Sans',
'Helvetica Neue',
sans-serif;
@media (max-width: $breakpoint) {
font-size: 16px;
}
}
html,
body {
max-width: 100vw;
overflow-x: hidden;
}
body {
margin: 0;
color: rgb(var(--foreground-rgb));
background: rgb(var(--background-rgb));
}
img {
height: auto;
max-width: 100%;
display: block;
}
h1 {
font-size: 4.5rem;
line-height: 1.2;
margin: 0 0 2.5rem 0;
@media (max-width: $breakpoint) {
font-size: 3rem;
margin: 0 0 1.5rem 0;
}
}
h2 {
font-size: 3.5rem;
line-height: 1.2;
margin: 0 0 2.5rem 0;
}
h3 {
font-size: 2.5rem;
line-height: 1.2;
margin: 0 0 2rem 0;
}
h4 {
font-size: 1.5rem;
line-height: 1.2;
margin: 0 0 1rem 0;
}
h5 {
font-size: 1.25rem;
line-height: 1.2;
margin: 0 0 1rem 0;
}
h6 {
font-size: 1rem;
line-height: 1.2;
margin: 0 0 1rem 0;
}
a {
color: inherit;
text-decoration: none;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}

View File

@@ -1,16 +0,0 @@
.body {
padding: 6rem 0;
min-height: 100vh;
}
.header {
margin-bottom: 4rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
width: 200px;
}

View File

@@ -1,36 +0,0 @@
import React from 'react'
import Link from 'next/link'
import './app.scss'
import classes from './layout.module.scss'
export const metadata = {
title: 'Payload Custom Server',
description: 'Serve Payload alongside any front-end framework.',
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className={classes.body}>
<header className={classes.header}>
<Link href="https://payloadcms.com" target="_blank" rel="noopener noreferrer">
<picture>
<source
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
/>
<img
className={classes.logo}
alt="Payload Logo"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
/>
</picture>
</Link>
</header>
{children}
</body>
</html>
)
}

View File

@@ -1,10 +0,0 @@
import { NextResponse } from 'next/server'
/**
* The Next.js API routes can conflict with Payload's own routes if they share the same path
* To avoid this you can customise the path of Payload or the API route of Nextjs as we've done here
* See readme: https://github.com/payloadcms/payload/tree/main/examples/custom-server#conflicting-routes
* */
export async function GET(): Promise<NextResponse> {
return NextResponse.json({ success: true })
}

View File

@@ -1,10 +0,0 @@
import { NextResponse } from 'next/server'
/**
* The Next.js API routes can conflict with Payload's own routes if they share the same path
* To avoid this you can customise the path of Payload or the API route of Nextjs as we've done here
* See readme: https://github.com/payloadcms/payload/tree/main/examples/custom-server#conflicting-routes
* */
export async function POST(): Promise<NextResponse> {
return NextResponse.json({ success: true })
}

View File

@@ -1,17 +0,0 @@
.main {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
margin: 0 auto;
@media (max-width: 768px) {
padding: 2rem 0;
}
}
.body {
display: flex;
flex-direction: column;
justify-content: space-between;
}

View File

@@ -1,39 +0,0 @@
import React, { Fragment } from 'react'
import { notFound } from 'next/navigation'
import { getPayloadClient } from '../getPayload'
import { Page } from './../payload-types'
import { Gutter } from './_components/Gutter'
import { RichText } from './_components/RichText'
import classes from './page.module.scss'
export default async function Home() {
const payload = await getPayloadClient()
const { docs } = await payload.find({
collection: 'pages',
where: {
slug: {
equals: 'home',
},
},
})
const home = docs?.[0] as Page
if (!home) {
return notFound()
}
return (
<Fragment>
<main className={classes.main}>
<Gutter>
<div className={classes.body}>
<RichText content={home.richText} />
</div>
</Gutter>
</main>
</Fragment>
)
}

View File

@@ -1,39 +0,0 @@
import type { CollectionConfig } from 'payload/types'
import formatSlug from '../utilities/formatSlug'
export const Pages: CollectionConfig = {
slug: 'pages',
admin: {
useAsTitle: 'title',
},
access: {
read: () => true,
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
required: true,
},
{
name: 'richText',
type: 'richText',
label: 'Content',
},
{
name: 'slug',
label: 'Slug',
type: 'text',
admin: {
position: 'sidebar',
},
hooks: {
beforeValidate: [formatSlug('title')],
},
},
],
}
export default Pages

View File

@@ -1,17 +0,0 @@
import React from 'react'
const BeforeLogin: React.FC = () => {
if (process.env.PAYLOAD_PUBLIC_SEED === 'true') {
return (
<p>
{'Log in with the email '}
<strong>demo@payloadcms.com</strong>
{' and the password '}
<strong>demo</strong>.
</p>
)
}
return null
}
export default BeforeLogin

View File

@@ -1,54 +0,0 @@
import dotenv from 'dotenv'
import path from 'path'
import type { Payload } from 'payload'
import payload from 'payload'
import type { InitOptions } from 'payload/config'
import { seed as seedData } from './seed'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
let cached = (global as any).payload
if (!cached) {
cached = (global as any).payload = { client: null, promise: null }
}
interface Args {
initOptions?: Partial<InitOptions>
seed?: boolean
}
export const getPayloadClient = async ({ initOptions, seed }: Args = {}): Promise<Payload> => {
if (!process.env.PAYLOAD_SECRET) {
throw new Error('PAYLOAD_SECRET environment variable is missing')
}
if (cached.client) {
return cached.client
}
if (!cached.promise) {
cached.promise = payload.init({
secret: process.env.PAYLOAD_SECRET,
local: initOptions?.express ? false : true,
...(initOptions || {}),
})
}
try {
process.env.PAYLOAD_DROP_DATABASE = seed ? 'true' : 'false'
cached.client = await cached.promise
if (seed) {
await seedData(payload)
}
} catch (e: unknown) {
cached.promise = null
throw e
}
return cached.client
}

View File

@@ -1,77 +0,0 @@
/* tslint:disable */
/* eslint-disable */
/**
* This file was automatically generated by Payload.
* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,
* and re-run `payload generate:types` to regenerate this file.
*/
export interface Config {
collections: {
pages: Page
users: User
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {}
}
export interface Page {
id: string
title: string
richText?: {
[k: string]: unknown
}[]
slug?: string
updatedAt: string
createdAt: string
}
export interface User {
id: string
updatedAt: string
createdAt: string
email: string
resetPasswordToken?: string
resetPasswordExpiration?: string
salt?: string
hash?: string
loginAttempts?: number
lockUntil?: string
password?: string
}
export interface PayloadPreference {
id: string
user: {
relationTo: 'users'
value: string | User
}
key?: string
value?:
| {
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null
updatedAt: string
createdAt: string
}
export interface PayloadMigration {
id: string
name?: string
batch?: number
updatedAt: string
createdAt: string
}
declare module 'payload' {
export interface GeneratedTypes {
collections: {
pages: Page
users: User
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
}
}

View File

@@ -1,32 +0,0 @@
import { webpackBundler } from '@payloadcms/bundler-webpack'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { slateEditor } from '@payloadcms/richtext-slate'
import dotenv from 'dotenv'
import path from 'path'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
import { buildConfig } from 'payload/config'
import { Pages } from './collections/Pages'
import BeforeLogin from './components/BeforeLogin'
export default buildConfig({
serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL || '',
collections: [Pages],
admin: {
bundler: webpackBundler(),
components: {
beforeLogin: [BeforeLogin],
},
},
editor: slateEditor({}),
db: mongooseAdapter({
url: process.env.DATABASE_URI,
}),
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
})

View File

@@ -1,93 +0,0 @@
import type { Payload } from 'payload'
export const seed = async (payload: Payload): Promise<void> => {
// create admin
await payload.create({
collection: 'users',
data: {
email: 'demo@payloadcms.com',
password: 'demo',
},
})
// create home page
await Promise.all([
await payload.create({
collection: 'pages',
data: {
title: 'Home',
richText: [
{
children: [
{
text: 'Payload Custom Server Example',
},
],
type: 'h1',
},
{
children: [
{
text: 'This is an example of how to host ',
},
{
type: 'link',
linkType: 'custom',
url: 'https://payloadcms.com',
children: [
{
text: 'Payload',
},
],
newTab: true,
},
{
text: ' alongside your front-end by sharing a single Express server. You are currently browsing a ',
},
{
type: 'link',
linkType: 'custom',
url: 'https://nextjs.org',
children: [
{
text: 'Next.js',
},
],
newTab: true,
},
{
text: ' app, but you can easily swap in any framework you like—check out the ',
},
{
type: 'link',
linkType: 'custom',
url: 'http://github.com/payloadcms/payload/tree/main/examples/custom-server',
children: [
{
text: 'README.md',
},
],
},
{
text: ' for instructions on how to do this. ',
},
{
type: 'link',
linkType: 'custom',
url: 'http://localhost:3000/admin',
children: [
{
text: 'Click here',
},
],
},
{
text: ' to navigate to the admin panel and login.',
},
],
},
],
},
}),
])
}

View File

@@ -1,35 +0,0 @@
import dotenv from 'dotenv'
import path from 'path'
// This file is used to replace `server.ts` when ejecting i.e. `yarn eject`
// See `../eject.ts` for exact details on how this file is used
// See `./README.md#eject` for more information
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
import express from 'express'
import { getPayloadClient } from './getPayload'
const app = express()
const PORT = process.env.PORT || 3000
const start = async (): Promise<void> => {
const payload = await getPayloadClient({
initOptions: {
express: app,
onInit: async (newPayload) => {
newPayload.logger.info(`Payload Admin URL: ${newPayload.getAdminURL()}`)
},
},
seed: process.env.PAYLOAD_PUBLIC_SEED === 'true',
})
app.listen(PORT, async () => {
payload.logger.info(`App URL: ${process.env.PAYLOAD_PUBLIC_SERVER_URL}`)
})
}
start()

View File

@@ -1,56 +0,0 @@
import dotenv from 'dotenv'
import next from 'next'
import nextBuild from 'next/dist/build'
import path from 'path'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
import express from 'express'
import { getPayloadClient } from './getPayload'
const app = express()
const PORT = process.env.PORT || 3000
const start = async (): Promise<void> => {
const payload = await getPayloadClient({
initOptions: {
express: app,
onInit: async (newPayload) => {
newPayload.logger.info(`Payload Admin URL: ${newPayload.getAdminURL()}`)
},
},
seed: process.env.PAYLOAD_PUBLIC_SEED === 'true',
})
if (process.env.NEXT_BUILD) {
app.listen(PORT, async () => {
payload.logger.info(`Next.js is now building...`)
// @ts-expect-error
await nextBuild(path.join(__dirname, '..'))
process.exit()
})
return
}
const nextApp = next({
dev: process.env.NODE_ENV !== 'production',
})
const nextHandler = nextApp.getRequestHandler()
app.use((req, res) => nextHandler(req, res))
nextApp.prepare().then(() => {
payload.logger.info('Next.js started')
app.listen(PORT, async () => {
payload.logger.info(`Next.js App URL: ${process.env.PAYLOAD_PUBLIC_SERVER_URL}`)
})
})
}
start()

View File

@@ -1,24 +0,0 @@
import type { FieldHook } from 'payload/types'
const format = (val: string): string =>
val
.replace(/ /g, '-')
.replace(/[^\w-/]+/g, '')
.toLowerCase()
const formatSlug =
(fallback: string): FieldHook =>
({ value, originalDoc, data }) => {
if (typeof value === 'string') {
return format(value)
}
const fallbackData = data?.[fallback] || originalDoc?.[fallback]
if (fallbackData && typeof fallbackData === 'string') {
return format(fallbackData)
}
return value
}
export default formatSlug

View File

@@ -1,39 +0,0 @@
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"jsx": "preserve",
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"plugins": [
{
"name": "next"
}
]
},
"include": [
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
],
"ts-node": {
"transpileOnly": true,
"swc": true
}
}

View File

@@ -1,10 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist",
"noEmit": false,
"jsx": "react"
},
"include": ["src/server.ts", "src/payload.config.ts"]
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,11 @@
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import React from 'react'
import type { MainMenu } from '../../../payload-types'
import { MainMenu } from '../../../payload-types'
import { CMSLink } from '../CMSLink'
import { Gutter } from '../Gutter'
import classes from './index.module.scss'
export async function Header() {
@@ -20,17 +20,17 @@ export async function Header() {
return (
<header className={classes.header}>
<Gutter className={classes.wrap}>
<Link href="/" className={classes.logo}>
<Link className={classes.logo} href="/">
<picture>
<source
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg"
/>
<Image
width={150}
height={30}
alt="Payload Logo"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
height={30}
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg"
width={150}
/>
</picture>
</Link>

View File

@@ -1,13 +1,14 @@
import React, { useState } from 'react'
import type { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar'
import Image from 'next/image'
import Link from 'next/link'
import { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar'
import React, { useState } from 'react'
import type { MainMenu } from '../../payload-types'
import { MainMenu } from '../../payload-types'
import { AdminBar } from '../AdminBar'
import { CMSLink } from '../CMSLink'
import { Gutter } from '../Gutter'
import classes from './index.module.scss'
type HeaderBarProps = {
@@ -18,17 +19,17 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => {
return (
<header className={classes.header}>
<Gutter className={classes.wrap}>
<Link href="/" className={classes.logo}>
<Link className={classes.logo} href="/">
<picture>
<source
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg"
media="(prefers-color-scheme: dark)"
srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg"
/>
<Image
width={150}
height={30}
alt="Payload Logo"
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg"
height={30}
src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg"
width={150}
/>
</picture>
</Link>
@@ -39,12 +40,12 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => {
}
export const Header: React.FC<{
adminBarProps: PayloadAdminBarProps
globals: {
mainMenu: MainMenu
}
adminBarProps: PayloadAdminBarProps
}> = (props) => {
const { globals, adminBarProps } = props
const { adminBarProps, globals } = props
const [user, setUser] = useState<PayloadMeUser>()
@@ -56,7 +57,7 @@ export const Header: React.FC<{
return (
<div>
<AdminBar adminBarProps={adminBarProps} user={user} setUser={setUser} />
<AdminBar adminBarProps={adminBarProps} setUser={setUser} user={user} />
<HeaderBar>
{hasNavItems && (
<nav className={classes.nav}>

View File

@@ -1,43 +1,35 @@
import type { Page } from '../payload-types'
export const home: Partial<Page> = {
title: 'Home Page',
slug: 'home',
_status: 'published',
richText: [
{
children: [
{ text: 'This is a ' },
{ type: 'link', newTab: true, url: 'https://nextjs.org/', children: [{ text: '' }] },
{ type: 'link', children: [{ text: '' }], newTab: true, url: 'https://nextjs.org/' },
{ text: '' },
{
type: 'link',
linkType: 'custom',
url: 'https://nextjs.org/',
newTab: true,
children: [{ text: 'Next.js' }],
linkType: 'custom',
newTab: true,
url: 'https://nextjs.org/',
},
{ text: " app made explicitly for Payload's " },
{
type: 'link',
newTab: true,
url: 'https://github.com/payloadcms/payload/tree/main/examples/redirects',
children: [{ text: '' }],
},
{ text: '' },
{
type: 'link',
children: [{ text: 'Draft Preview Example' }],
linkType: 'custom',
newTab: true,
url: 'https://github.com/payloadcms/payload/tree/main/examples/draft-preview/payload',
children: [{ text: 'Draft Preview Example' }],
},
{ text: '. This example demonstrates how to implement draft preview into Payload using ' },
{
type: 'link',
children: [{ text: 'Drafts' }],
newTab: true,
url: 'https://payloadcms.com/docs/versions/drafts#drafts',
children: [{ text: 'Drafts' }],
},
{ text: '.' },
],
@@ -47,30 +39,31 @@ export const home: Partial<Page> = {
children: [
{
type: 'link',
linkType: 'custom',
url: 'http://localhost:3000/admin',
newTab: true,
children: [{ text: 'Log in to the admin panel' }],
linkType: 'custom',
newTab: true,
url: 'http://localhost:3000/admin',
},
{ text: ' and refresh this page to see the ' },
{
type: 'link',
children: [{ text: 'Payload Admin Bar' }],
linkType: 'custom',
newTab: true,
url: 'https://github.com/payloadcms/payload-admin-bar',
children: [{ text: 'Payload Admin Bar' }],
},
{
text: ' appear at the top of this site. This will allow you to seamlessly navigate between the two apps. Then, navigate to the ',
},
{
type: 'link',
children: [{ text: 'example page' }],
linkType: 'custom',
url: 'http://localhost:3001/example-page',
children: [{ text: 'example page' }],
},
{ text: ' to see how we control access to draft content. ' },
],
},
],
title: 'Home Page',
}

View File

@@ -3,7 +3,7 @@
// @ts-nocheck
//This copy-and-pasted from lexical here here: https://github.com/facebook/lexical/blob/c2ceee223f46543d12c574e62155e619f9a18a5d/packages/lexical/src/LexicalConstants.ts
import type { ElementFormatType, TextFormatType } from 'lexical'
import type { ElementFormatType, TextFormatType } from '@payloadcms/richtext-lexical/lexical'
import type { TextDetailType, TextModeType } from 'lexical/nodes/LexicalTextNode'
/**
@@ -81,7 +81,7 @@ export const RTL_REGEX = new RegExp('^[^' + LTR + ']*[' + RTL + ']')
// eslint-disable-next-line
export const LTR_REGEX = new RegExp('^[^' + RTL + ']*[' + LTR + ']')
export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
export const TEXT_TYPE_TO_FORMAT: Record<string | TextFormatType, number> = {
bold: IS_BOLD,
code: IS_CODE,
highlight: IS_HIGHLIGHT,
@@ -92,7 +92,7 @@ export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
underline: IS_UNDERLINE,
}
export const DETAIL_TYPE_TO_DETAIL: Record<TextDetailType | string, number> = {
export const DETAIL_TYPE_TO_DETAIL: Record<string | TextDetailType, number> = {
directionless: IS_DIRECTIONLESS,
unmergeable: IS_UNMERGEABLE,
}

View File

@@ -1,7 +1,15 @@
import type { SerializedListItemNode, SerializedListNode } from '@lexical/list'
import type { SerializedHeadingNode } from '@lexical/rich-text'
import type { LinkFields, SerializedLinkNode } from '@payloadcms/richtext-lexical'
import type { SerializedElementNode, SerializedLexicalNode, SerializedTextNode } from 'lexical'
import type {
SerializedElementNode,
SerializedLexicalNode,
SerializedTextNode,
} from '@payloadcms/richtext-lexical/lexical'
import type {
SerializedListItemNode,
SerializedListNode,
} from '@payloadcms/richtext-lexical/lexical/list'
import type { SerializedHeadingNode } from '@payloadcms/richtext-lexical/lexical/rich-text'
import type { JSX } from 'react'
import React, { Fragment } from 'react'
@@ -90,12 +98,6 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
'children' in _node ? serializedChildrenFn(_node as SerializedElementNode) : ''
switch (_node.type) {
case 'linebreak': {
return <br key={index} />
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'heading': {
const node = _node as SerializedHeadingNode
@@ -103,6 +105,26 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
const Tag = node?.tag as Heading
return <Tag key={index}>{serializedChildren}</Tag>
}
case 'linebreak': {
return <br key={index} />
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
case 'list': {
const node = _node as SerializedListNode
@@ -139,26 +161,12 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
)
}
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'quote': {
return <blockquote key={index}>{serializedChildren}</blockquote>
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
/* case 'block': {
// todo: fix types

View File

@@ -12,10 +12,6 @@
"@apollo/client": "^3.7.0",
"@faceless-ui/css-grid": "^1.2.0",
"@faceless-ui/modal": "^2.0.2",
"@lexical/list": "^0.14.5",
"@lexical/react": "0.14.5",
"@lexical/rich-text": "^0.14.5",
"@lexical/utils": "0.14.5",
"@payloadcms/plugin-form-builder": "beta",
"@payloadcms/richtext-lexical": "beta",
"escape-html": "^1.0.3",

View File

@@ -3,7 +3,7 @@
// @ts-nocheck
//This copy-and-pasted from lexical here here: https://github.com/facebook/lexical/blob/c2ceee223f46543d12c574e62155e619f9a18a5d/packages/lexical/src/LexicalConstants.ts
import type { ElementFormatType, TextFormatType } from 'lexical'
import type { ElementFormatType, TextFormatType } from '@payloadcms/richtext-lexical/lexical'
import type { TextDetailType, TextModeType } from 'lexical/nodes/LexicalTextNode'
/**
@@ -81,7 +81,7 @@ export const RTL_REGEX = new RegExp('^[^' + LTR + ']*[' + RTL + ']')
// eslint-disable-next-line
export const LTR_REGEX = new RegExp('^[^' + RTL + ']*[' + LTR + ']')
export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
export const TEXT_TYPE_TO_FORMAT: Record<string | TextFormatType, number> = {
bold: IS_BOLD,
code: IS_CODE,
highlight: IS_HIGHLIGHT,
@@ -92,7 +92,7 @@ export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
underline: IS_UNDERLINE,
}
export const DETAIL_TYPE_TO_DETAIL: Record<TextDetailType | string, number> = {
export const DETAIL_TYPE_TO_DETAIL: Record<string | TextDetailType, number> = {
directionless: IS_DIRECTIONLESS,
unmergeable: IS_UNMERGEABLE,
}

View File

@@ -1,7 +1,14 @@
import type { SerializedListItemNode, SerializedListNode } from '@lexical/list'
import type { SerializedHeadingNode } from '@lexical/rich-text'
import type { LinkFields, SerializedLinkNode } from '@payloadcms/richtext-lexical'
import type { SerializedElementNode, SerializedLexicalNode, SerializedTextNode } from 'lexical'
import type {
SerializedElementNode,
SerializedLexicalNode,
SerializedTextNode,
} from '@payloadcms/richtext-lexical/lexical'
import type {
SerializedListItemNode,
SerializedListNode,
} from '@payloadcms/richtext-lexical/lexical/list'
import type { SerializedHeadingNode } from '@payloadcms/richtext-lexical/lexical/rich-text'
import React, { Fragment } from 'react'
@@ -90,12 +97,6 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
'children' in _node ? serializedChildrenFn(_node as SerializedElementNode) : ''
switch (_node.type) {
case 'linebreak': {
return <br key={index} />
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'heading': {
const node = _node as SerializedHeadingNode
@@ -103,6 +104,26 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
const Tag = node?.tag as Heading
return <Tag key={index}>{serializedChildren}</Tag>
}
case 'linebreak': {
return <br key={index} />
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
case 'list': {
const node = _node as SerializedListNode
@@ -139,26 +160,12 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
)
}
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'quote': {
return <blockquote key={index}>{serializedChildren}</blockquote>
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
/* case 'block': {
// todo: fix types

View File

@@ -12,10 +12,6 @@
"@apollo/client": "^3.7.0",
"@faceless-ui/css-grid": "^1.2.0",
"@faceless-ui/modal": "^2.0.2",
"@lexical/list": "^0.14.5",
"@lexical/react": "0.14.5",
"@lexical/rich-text": "^0.14.5",
"@lexical/utils": "0.14.5",
"@payloadcms/plugin-form-builder": "beta",
"@payloadcms/richtext-lexical": "beta",
"escape-html": "^1.0.3",

View File

@@ -17,10 +17,6 @@
"@apollo/client": "^3.7.0",
"@faceless-ui/css-grid": "^1.2.0",
"@faceless-ui/modal": "^2.0.2",
"@lexical/list": "^0.14.5",
"@lexical/react": "0.14.5",
"@lexical/rich-text": "^0.14.5",
"@lexical/utils": "0.14.5",
"@payloadcms/db-mongodb": "beta",
"@payloadcms/next": "beta",
"@payloadcms/plugin-cloud": "beta",

View File

@@ -3,7 +3,7 @@
// @ts-nocheck
//This copy-and-pasted from lexical here here: https://github.com/facebook/lexical/blob/c2ceee223f46543d12c574e62155e619f9a18a5d/packages/lexical/src/LexicalConstants.ts
import type { ElementFormatType, TextFormatType } from 'lexical'
import type { ElementFormatType, TextFormatType } from '@payloadcms/richtext-lexical/lexical'
import type { TextDetailType, TextModeType } from 'lexical/nodes/LexicalTextNode'
/**
@@ -81,7 +81,7 @@ export const RTL_REGEX = new RegExp('^[^' + LTR + ']*[' + RTL + ']')
// eslint-disable-next-line
export const LTR_REGEX = new RegExp('^[^' + RTL + ']*[' + LTR + ']')
export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
export const TEXT_TYPE_TO_FORMAT: Record<string | TextFormatType, number> = {
bold: IS_BOLD,
code: IS_CODE,
highlight: IS_HIGHLIGHT,
@@ -92,7 +92,7 @@ export const TEXT_TYPE_TO_FORMAT: Record<TextFormatType | string, number> = {
underline: IS_UNDERLINE,
}
export const DETAIL_TYPE_TO_DETAIL: Record<TextDetailType | string, number> = {
export const DETAIL_TYPE_TO_DETAIL: Record<string | TextDetailType, number> = {
directionless: IS_DIRECTIONLESS,
unmergeable: IS_UNMERGEABLE,
}

View File

@@ -1,7 +1,14 @@
import type { SerializedListItemNode, SerializedListNode } from '@lexical/list'
import type { SerializedHeadingNode } from '@lexical/rich-text'
import type { LinkFields, SerializedLinkNode } from '@payloadcms/richtext-lexical'
import type { SerializedElementNode, SerializedLexicalNode, SerializedTextNode } from 'lexical'
import type {
SerializedElementNode,
SerializedLexicalNode,
SerializedTextNode,
} from '@payloadcms/richtext-lexical/lexical'
import type {
SerializedListItemNode,
SerializedListNode,
} from '@payloadcms/richtext-lexical/lexical/list'
import type { SerializedHeadingNode } from '@payloadcms/richtext-lexical/lexical/rich-text'
import React, { Fragment } from 'react'
@@ -90,12 +97,6 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
'children' in _node ? serializedChildrenFn(_node as SerializedElementNode) : ''
switch (_node.type) {
case 'linebreak': {
return <br key={index} />
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'heading': {
const node = _node as SerializedHeadingNode
@@ -103,6 +104,26 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
const Tag = node?.tag as Heading
return <Tag key={index}>{serializedChildren}</Tag>
}
case 'linebreak': {
return <br key={index} />
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
case 'list': {
const node = _node as SerializedListNode
@@ -139,26 +160,12 @@ export function serializeLexical({ nodes }: Props): JSX.Element {
)
}
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'quote': {
return <blockquote key={index}>{serializedChildren}</blockquote>
}
case 'link': {
const node = _node as SerializedLinkNode
const fields: LinkFields = node.fields
return (
<CMSLink
key={index}
newTab={Boolean(fields?.newTab)}
reference={fields.doc as any}
type={fields.linkType === 'internal' ? 'reference' : 'custom'}
url={fields.url}
>
{serializedChildren}
</CMSLink>
)
}
default:
return null

Some files were not shown because too many files have changed in this diff Show More