Compare commits

...

39 Commits

Author SHA1 Message Date
Elliot DeNolf
a6ba9e3a41 chore(release): v3.3.0 [skip ci] 2024-12-03 12:53:42 -05:00
Paul
d1de106944 fix(ui): data disappearing when form state updates in globals (#9682)
Fixes a bug where data would visually disappear from the form when
merging new form stats when saving globals.
2024-12-03 15:41:21 +00:00
Dan Ribbens
6104fe5011 feat: disableLocalStrategy with auth fields still enabled (#9579)
Adds configuration options to `auth.disableLocalStrategy` to allow
customization of how payload treats an auth enabled collection.

Two new properties have been added to `disableLocalStrategy`:

- `enableFields` Include auth fields on the collection even though the
local strategy is disabled. Useful when you do not want the database or
types to vary depending on the auth configuration used.
- `optionalPassword`: makes the password field not required
2024-12-03 09:52:23 -05:00
Patrik
40f5c72e8d chore(examples): migrates form-builder example to 3.0 (#9681)
### What?

Migrates the `form-builder` example to payload `3.0`.

`Updates`:

- Now has a next app directly along side payload.

- Removes `form-builder/next-app` & `form-builder/next-pages` example
front-ends and only uses new recommended approach (i.e admin panel &
front-end on the same port - `3000`)
2024-12-03 09:47:08 -05:00
Harley Salas
cf34d3aec4 docs: add payload.auth to local api (#9632)
### What?
https://payloadcms.com/docs does not document the `payload.auth`
feature.

### Why?
With custom components, there is no explanation as to how you can get
the current user on the server side. It is also something useful to know
for many other scenarios. A Discord user even mentioned today, that they
spent quite some time, trying to figure out how to get the current user,
while on the server.

While I don't think it's the cleanest "place" to document it, I think
its what makes the most sense, given the current state of the
documentation. I tried to follow the existing format as close as
possible. The comments are longer, but I feel the information is
absolutely necessary to provide.

Confirmed that formatting works as expected and there are no errors
parsing the addition:

![image](https://github.com/user-attachments/assets/c8e203cd-3c9c-482c-850b-2a16f3958344)


Fixes #9631
2024-12-02 19:14:06 -06:00
Paul
5b3079a88e chore(scripts): fix generate template variations script (#9671) 2024-12-02 23:30:52 +00:00
Alessio Gravili
0dbfc237d3 fix: throw proper error if import handler paths are not able to be imported, improve import handler path docs (#9679)
Fixes https://github.com/payloadcms/payload/issues/9453
2024-12-02 23:26:43 +00:00
Alessio Gravili
a89d54454a fix: ensure jobs do not retry indefinitely by default, fix undefined values in error messages (#9605)
## Fix default retries

By default, if no `retries` property has been set, jobs / tasks should
not be retried. This was not the case previously, as the `maxRetries`
variable was `undefined`, causing jobs to retry endlessly. This PR sets
them to `0` by default.

Additionally, this fixes some undesirable behavior of the workflow
retries property. Workflow retries now act as **maximum**,
workflow-level retries. Only tasks that do not have a retry property set
will inherit the workflow-level retries.

## Fix error messages

Previously, you were able to encounter error messages with undefined
values like these:

![CleanShot 2024-11-28 at 15 23
37@2x](https://github.com/user-attachments/assets/81617ca8-11de-4d35-b9bf-cc6c5bc515be)

Reason is that it was always using `job.workflowSlug` for the error
messages. However, if you queue a task directly, without a workflow,
`job.workflowSlug` is undefined and `job.taskSlug` should be used
instead.

This PR then gets rid of the second undefined value by ensuring that
`maxRetries´ is never undefined
2024-12-02 22:05:48 +00:00
Elliot DeNolf
e4c3c5b1d2 ci: allow more commit types in release notes (#9677)
More commit types will now show in the release notes. The full list of
allowable types are the following and will show in order:

```ts
const commitTypesForChangelog = [
  'feat',
  'fix',
  'perf',
  'refactor',
  'docs',
  'style',
  'test',
  'templates',
  'examples',
  'build',
  'ci',
  'chore',
]
  ```
2024-12-02 15:59:52 -05:00
Patrik
58b7415385 feat(ui): adds beforeInput & afterInput props for arrays, blocks, collapsible, group, radio, & relationship fields. (#9674)
The following fields did not have the ability to add beforeInput &
afterInput:
- Arrays
- Blocks
- Collapsibles
- Groups
- Radios
- Relationships

### How?

Adds the ability to define and add before and after inputs to these
fields in your config.

Here are examples of the above fields with beforeInputs & afterInputs
defined (I.e. `#before-input` & `#after-input`):

`Arrays`:
![Screenshot 2024-12-02 at 1 22
15 PM](https://github.com/user-attachments/assets/8a2d5351-acab-4b28-b9bd-b19e1942da7e)


`Blocks`:
![Screenshot 2024-12-02 at 1 35
53 PM](https://github.com/user-attachments/assets/e9b5f22b-2671-4efb-8ee4-b4de3a1addc5)


`Collapsible`:
![Screenshot 2024-12-02 at 1 46
34 PM](https://github.com/user-attachments/assets/38f7a016-8a79-4ece-90d2-0b1761db19cd)


`Groups`:
![Screenshot 2024-12-02 at 1 52
34 PM](https://github.com/user-attachments/assets/dc6a123b-ee01-4021-bbbf-ac1b8c086072)


`Radios`:
![Screenshot 2024-12-02 at 1 59
35 PM](https://github.com/user-attachments/assets/4ddd16a1-2ad2-44f5-a7e9-86aa6e4e947b)


`Relationships`:
![Screenshot 2024-12-02 at 1 21
55 PM](https://github.com/user-attachments/assets/b4679baf-6157-41c9-8485-ca570be979d2)
2024-12-02 19:37:16 +00:00
Dan Ribbens
631edd4c17 fix: latest: true version disappear on parallel writes (#9032)
What?
Fixes issue when on parallel writes in result you can have 0 latest:
true versions.

Why?
There must be always a version with latest: true

How?
Ensures that we always have a version with latest: true by adding a
filter on createdAt < createdVersion.createdAt.
Instead, this ponentially can lead to a situation where we have 2
versions with latest: true, if they were created at the exact same time,
but this shouldn't happen in a real world scenario and it's much less
problematic than not having a version with latest: true.

Fixes https://github.com/payloadcms/payload/issues/5895

Changes from #8986

---------

Co-authored-by: Sasha <64744993+r1tsuu@users.noreply.github.com>
2024-12-02 14:34:45 -05:00
Tobias Arends
c5fe021570 fix: duplicate afterRead collection hook call on loginOperation (#9664)
Hi there,

i noticed that the `afterRead` hook is triggered twice on
`loginOperation`.

This just removes the duplicated code.

-Tobi
2024-12-02 14:07:15 -05:00
Jacob Fletcher
edc04aec56 refactor: deprecates params and search params contexts (#9581)
As described in #9576, the `SearchParamsProvider` can become stale when
navigating routes and relying on search params during initial render.
This is because this context, along with the `ParamsProvider`, is
duplicative to the internal lifecycle of `useSearchParams` and
`useParams` from `next/navigation`– but always one render behind.
Instead, we need to use the hooks directly from `next/navigation` as
described in the jsdocs. This will also remove any abstraction over top
the web standard for `URLSearchParams`.

For this reason, these providers and their corresponding hooks have been
marked with the deprecated flag and will continue to behave as they do
now, but will be removed in the next major release. This PR replaces all
internal reliance on these hooks with `next/navigation` as suggested,
except for the `useParams` hook, which was never used in the first
place.

```diff
'use client'
- import { useSearchParams } from '@payloadcms/ui'
+ import { useSearchParams } from 'next/navigation'
+ import { parseSearchParams } from '@payloadcms/ui'

export function MyClientComponent() {
- const { searchParams } = useSearchParams()
+ const searchParams = useSearchParams()
+ const parsedParams = parseSearchParams(searchParams)

  // ...
}
```
_MyClientComponent.tsx_
2024-12-02 13:57:59 -05:00
Jacob Fletcher
d04cea123c fix(ui): properly animates height for dynamically rendered children (#9665)
Fixes https://github.com/payloadcms/payload/issues/9567. When using the
`AnimateHeight` component on a patched browser such as Webkit,
components with dynamically rendered children are not properly animating
in, such as blocks with rich text. This is because the height of that
content is unable to be calculated before it's rendered, preventing the
component from acquiring a target height to animate toward. This change
was originally introduced in #9456 in effort to remove unnecessary
dependencies.

The fix is to setup a ResizeObserver during animation to watch for
changes to the content's height. This way, as components dynamically
render in based on the "open" state, the hook will simply increment the
target height accordingly.
2024-12-02 13:18:16 -05:00
Alessio Gravili
24c75b09c0 fix(ui): upgrade sonner from 1.5.0 to 1.7.0 (#9666)
This fixes React 19 peer dependency warnings for sonner
2024-12-02 18:08:22 +00:00
Alessio Gravili
877b89962e chore: upgrade all dependencies used to build payload (swc, esbuild, react compiler, babel) (#9658) 2024-12-02 09:07:48 -07:00
Alessio Gravili
71ba4a8bce chore: upgrade all react and next-related packages (#9655)
This PR updates all react and next-related packages to the latest
version in our test directory and in our templates, while still allowing
older versions to be used.

Additionally, this ensures that the "scheduler" package version we
install matches the version installed by react-dom
2024-12-02 00:48:39 -07:00
Alessio Gravili
9d724086c7 feat(ui): upgrade react-datepicker dependency from 6.2.0 to 7.5.0 (#9654)
The new version comes with included types (we can uninstall
`@types/react-datepicker`!), removes 1 dependency and adds official
support for React 19
2024-12-02 05:53:12 +00:00
Alessio Gravili
0b445c8013 ci: add back CI-level automatic retrying for failing int and e2e tests (#9652)
We should fix all the flaky tests in the future - in the meantime this
PR will reduce collectively wasted engineer hours, as we now don't have
to manually open the awkward GH actions UI and press the retry button -
often multiple times for each PR.

It may not be enough to simply retry the test:int / test:e2e commands to
get the tests not to flake for the next run, but let's see how this goes
2024-12-01 22:46:26 -07:00
Alessio Gravili
73e0e25e14 fix(ui): upgrade react-select, fixes type issues with select input (#9653)
React-select fixed React 19 type compatibility here:
https://github.com/JedWatson/react-select/pull/5974
2024-12-01 21:35:03 -07:00
Alessio Gravili
f07679745a fix: job task output data was not fetched and restored, if task failed previously (#9651)
Assume you had the following workflow:

```ts
 handler: async ({ job, inlineTask, req }) => {
          const { customerData } = await inlineTask('Fetch Customer Data', {
            task: ({ req }) => {
              if (Math.random() < 0.2) {
                throw new Error('Failed on purpose')
              }
              return {
                output: {
                  customerData: 'test',
                },
              }
            },
            retries: {
              attempts: 40,
            },
          })
          
          console.log('customer Data', customerData)

          await inlineTask('Analyze Segments', {
          // Rest of task...
```

It was possible for the following to happen:

Run attempt 1:

- Task "Fetch Customer Data" fails
- Task is added to job log without output data and state "failed"

Run attempt 2:

- Task "Fetch Customer Data" succeeds
- Task is added to job log with correct output data and state
"succeeded"
- Task "Analyze Segments" fails
- Task is added to job log without output data and state "failed"

Run attempt 3:

- Task "Fetch Customer Data" has already run successfully => restore
from DB
- Task "Analyze Segments" fails because input data is undefined.

The restoration of the already-succeeded "Fetch Customer Data" task did
not fetch and restore the correct output data, as it was taking the
output data from the previously failed task that did not save any, even
though it should have been taking and restoring the output data of the
last-run, successful task run.

This PR fixed that
2024-12-02 03:49:31 +00:00
Alessio Gravili
963387f7b0 feat(ui): export CodeEditor (#9650)
Requirement for https://github.com/payloadcms/payload/pull/9645
2024-12-02 03:19:26 +00:00
Alessio Gravili
4cd31ce343 fix: prevent workflow destructuring errors for failing tasks (#9649)
When destructuring the output of task in a job workflow handler, there
is a chance of a destructuring error being thrown if the task fails
2024-12-02 02:31:17 +00:00
Alessio Gravili
f151723745 feat(ui): export TabsProvider and TabComponent (#9647)
Requirement for https://github.com/payloadcms/payload/pull/9645
2024-12-02 02:28:13 +00:00
Said Akhrarov
2b4522b1db fix(translations): changes rs and rs-Latin dateFNSkey to proper locale instead of en-US (#9621)
### What?
Adds Serbian `rs` and `rs-Latin` to `importDateFNSLocale` as well as
changes their `dateFNSKey` in the language definition to the appropriate
key instead of `en-US`

### Why?
To support Serbian language with appropriately localized dates.

### How?
Minor changes in translations package.
2024-12-01 21:09:56 +00:00
Alessio Gravili
e6ea68e848 fix: ensure job errors are saved in payload (#9644)
Previously, job errors were not saved in payload
2024-12-01 20:57:14 +00:00
Elliot DeNolf
1e8c9d3a09 docs: add upgrade from previous beta section to migration guide (#9642) 2024-12-01 11:25:44 -05:00
Elliot DeNolf
fdfa07b863 feat(examples): add custom server example [skip-lint] (#9641)
Example using [Next.js Custom
Server](https://nextjs.org/docs/pages/building-your-application/configuring/custom-server)
with express.

Made from official
[examples/custom-server](https://github.com/vercel/next.js/tree/canary/examples/custom-server)
from Next.js repository.
2024-12-01 11:11:47 -05:00
Elliot DeNolf
519752f152 feat: export built-in field validations (#9622)
Export the built-in field validations that Payload uses.
2024-11-29 23:13:42 -05:00
Riley Pearce
2d2e7d50f0 fix(next): remove keyboard focus for closed nav items (#9558)
Fixes: #9610.

### What?

Currently some links inside the main nav are still focusable with a
keyboard when the main nav is closed.

### Why?

This leads to the active keyboard focus getting lost until it eventually
finds its way to the hamburger menu button. It can also lead to links
that are not currently visible being selected accidentally.

### How?

When the [inert
attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inert)
is set to `true`, we can prevent focus on any child elements
automatically. We simply toggle the attribute on or off based on whether
the nav is open or closed.

The inert attribute has [great
compatibility](https://caniuse.com/mdn-html_global_attributes_inert)
with modern browsers these days, making it a solid choice to resolve
this issue.

### Recordings

#### Before

You can see down the bottom left of the screen that links available in
the main nav are still focusable even when the main nav is closed.


https://github.com/user-attachments/assets/e16d5336-7d2b-42f1-886b-cfa3ed82dbb1

#### After

You can see that focus is immediately moved to the hamburger menu when
the main nav is closed.


https://github.com/user-attachments/assets/8c81197a-53aa-4af1-8e5c-f6835ba955a5
2024-11-29 13:58:40 -07:00
Alessio Gravili
030b759529 fix(richtext-lexical): ensure lexical doesn't break if used without react installed (#9620) 2024-11-29 20:54:38 +00:00
Jacob Fletcher
3d1a0656d2 fix(live-preview): populates localized relationships in client-side live preview (#9617)
Fixes #5026. When using client-side Live Preview, switching locale would
not populate relationships in that locale, and would use the default
locale instead. This was because locale was simply not being handled.
Now, we pass the locale through the event, and use it to make localized
queries when populating those relationships.
2024-11-29 15:41:39 -05:00
Yunsup Sim
9892303f1f fix(richtext-lexical): add form id to drawSlug (#9613)
Fixes #9532 

The error occurs because the drawerSlug declaration in
`blocks/client/component` contains `formData.id`, while
`blocks/client/componentInline` does not. So I add `formData.id`.

### Before



https://github.com/user-attachments/assets/14247634-ab60-437f-8986-c76cafec5c09


### After


https://github.com/user-attachments/assets/b26bc1ca-b071-4bf5-a9f0-fda4e9282538
2024-11-29 20:40:35 +00:00
Elliot DeNolf
0716128b3b chore: add contributor count badge to readme 2024-11-29 14:40:34 -05:00
Sasha
bc2d7c91e0 docs: fix links to /access-control/overview (#9619)
Fixes links to **Access Control** like here
https://payloadcms.com/docs/access-control/fields
2024-11-29 21:40:03 +02:00
Sasha
b8965077b8 fix(plugin-search): delete proper search document when doc has the same value but different relationTo (#9616)
Fixes https://github.com/payloadcms/payload/issues/9612

Previously, the plugin search with different collections but the same
IDs could delete a wrong search document on synchronization, because we
queried the search document only by `doc.value`. Instead, we should also
query by `doc.relationTo`.
2024-11-29 21:25:26 +02:00
Vasileios Drosatos
aa5dd8a77f docs: adds missing comma to example config in localization.mdx (#9618) 2024-11-29 19:02:39 +00:00
Elliot DeNolf
702df1f5da ci: add github-releases-to-discord 2024-11-29 13:57:37 -05:00
Elliot DeNolf
f150a68f56 ci: small tweaks to post-release 2024-11-29 13:57:25 -05:00
441 changed files with 13428 additions and 34768 deletions

View File

@@ -18,7 +18,7 @@
},
"devDependencies": {
"@octokit/webhooks-types": "^7.5.1",
"@swc/jest": "^0.2.36",
"@swc/jest": "^0.2.37",
"@types/jest": "^27.5.2",
"@types/node": "^20.16.5",
"@typescript-eslint/eslint-plugin": "^4.33.0",

View File

@@ -274,11 +274,17 @@ jobs:
if: matrix.database == 'supabase'
- name: Integration Tests
run: pnpm test:int
uses: nick-fields/retry@v3
env:
NODE_OPTIONS: --max-old-space-size=8096
PAYLOAD_DATABASE: ${{ matrix.database }}
POSTGRES_URL: ${{ env.POSTGRES_URL }}
with:
retry_on: any
max_attempts: 5
timeout_minutes: 15
command: pnpm test:int
on_retry_command: pnpm clean:all && pnpm install
tests-e2e:
runs-on: ubuntu-latest
@@ -374,7 +380,13 @@ jobs:
run: pnpm exec playwright install-deps chromium
- name: E2E Tests
run: PLAYWRIGHT_JSON_OUTPUT_NAME=results_${{ matrix.suite }}.json pnpm test:e2e:prod:ci ${{ matrix.suite }}
uses: nick-fields/retry@v3
with:
retry_on: any
max_attempts: 5
timeout_minutes: 20
command: PLAYWRIGHT_JSON_OUTPUT_NAME=results_${{ matrix.suite }}.json pnpm test:e2e:prod:ci ${{ matrix.suite }}
on_retry_command: pnpm clean:all && pnpm install && pnpm build:all
env:
PLAYWRIGHT_JSON_OUTPUT_NAME: results_${{ matrix.suite }}.json
NEXT_TELEMETRY_DISABLED: 1

View File

@@ -23,8 +23,6 @@ jobs:
if: ${{ github.event_name != 'workflow_dispatch' }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: ./.github/actions/release-commenter
continue-on-error: true
env:
@@ -39,6 +37,20 @@ jobs:
comment-template: |
🚀 This is included in version {release_link}
github-releases-to-discord:
runs-on: ubuntu-latest
if: ${{ github.event_name != 'workflow_dispatch' }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Github Releases To Discord
uses: SethCohen/github-releases-to-discord@v1
with:
webhook_url: ${{ secrets.DISCORD_RELEASES_WEBHOOK_URL }}
color: '16777215'
username: 'Payload Releases'
avatar_url: 'https://l4wlsi8vxy8hre4v.public.blob.vercel-storage.com/discord-bot-logo.png'
update_templates:
runs-on: ubuntu-latest
permissions:

View File

@@ -24,14 +24,15 @@ jobs:
chore
ci
docs
examples
feat
fix
perf
refactor
revert
style
templates
test
types
scopes: |
cpa
db-\*

View File

@@ -9,6 +9,8 @@
&nbsp;
<a href="https://www.npmjs.com/package/payload"><img alt="npm" src="https://img.shields.io/npm/dw/payload?style=flat-square" /></a>
&nbsp;
<a href="https://github.com/payloadcms/payload/graphs/contributors"><img alt="npm" src="https://img.shields.io/github/contributors-anon/payloadcms/payload?color=yellow&style=flat-square" /></a>
&nbsp;
<a href="https://www.npmjs.com/package/payload"><img alt="npm" src="https://img.shields.io/npm/v/payload?style=flat-square" /></a>
&nbsp;
<a href="https://twitter.com/payloadcms"><img src="https://img.shields.io/badge/follow-payloadcms-1DA1F2?logo=twitter&style=flat-square" alt="Payload Twitter" /></a>

View File

@@ -6,7 +6,7 @@ desc: With Collection-level Access Control you can define which users can create
keywords: collections, access control, permissions, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
Collection Access Control is [Access Control](../access-control) used to restrict access to Documents within a [Collection](../collections/overview), as well as what they can and cannot see within the [Admin Panel](../admin/overview) as it relates to that Collection.
Collection Access Control is [Access Control](../overview) used to restrict access to Documents within a [Collection](../collections/overview), as well as what they can and cannot see within the [Admin Panel](../admin/overview) as it relates to that Collection.
To add Access Control to a Collection, use the `access` property in your [Collection Config](../configuration/collections):

View File

@@ -6,7 +6,7 @@ desc: Field-level Access Control is specified within a field's config, and allow
keywords: fields, access control, permissions, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
Field Access Control is [Access Control](../access-control) used to restrict access to specific [Fields](../fields/overview) within a Document.
Field Access Control is [Access Control](../overview) used to restrict access to specific [Fields](../fields/overview) within a Document.
To add Access Control to a Field, use the `access` property in your [Field Config](../fields/overview):

View File

@@ -6,7 +6,7 @@ desc: Global-level Access Control is specified within each Global's `access` pro
keywords: globals, access control, permissions, documentation, Content Management System, cms, headless, javascript, node, react, nextjs
---
Global Access Control is [Access Control](../access-control) used to restrict access to [Global](../globals/overview) Documents, as well as what they can and cannot see within the [Admin Panel](../admin/overview) as it relates to that Global.
Global Access Control is [Access Control](../overview) used to restrict access to [Global](../globals/overview) Documents, as well as what they can and cannot see within the [Admin Panel](../admin/overview) as it relates to that Global.
To add Access Control to a Global, use the `access` property in your [Global Config](../configuration/globals):

View File

@@ -35,7 +35,7 @@ import { buildConfig } from 'payload'
export default buildConfig({
// ...
localization: {
locales: ['en', 'es', 'de'] // required
locales: ['en', 'es', 'de'], // required
defaultLocale: 'en', // required
},
})

View File

@@ -23,14 +23,14 @@ Simply add a task to the `jobs.tasks` array in your Payload config. A task consi
| Option | Description |
| --------------------------- | -------------------------------------------------------------------------------- |
| `slug` | Define a slug-based name for this job. This slug needs to be unique among both tasks and workflows.|
| `handler` | The function that should be responsible for running the job. You can either pass a string-based path to the job function file, or the job function itself. If you are using large dependencies within your job, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. |
| `handler` | The function that should be responsible for running the job. You can either pass a string-based path to the job function file, or the job function itself. If you are using large dependencies within your job, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. Passing a string path is an advanced feature that may require a sophisticated build pipeline in order to work. |
| `inputSchema` | Define the input field schema - payload will generate a type for this schema. |
| `interfaceName` | You can use interfaceName to change the name of the interface that is generated for this task. By default, this is "Task" + the capitalized task slug. |
| `outputSchema` | Define the output field schema - payload will generate a type for this schema. |
| `label` | Define a human-friendly label for this task. |
| `onFail` | Function to be executed if the task fails. |
| `onSuccess` | Function to be executed if the task succeeds. |
| `retries` | Specify the number of times that this step should be retried if it fails. |
| `retries` | Specify the number of times that this step should be retried if it fails. If this is undefined, the task will either inherit the retries from the workflow or have no retries. If this is 0, the task will not be retried. By default, this is undefined. |
The logic for the Task is defined in the `handler` - which can be defined as a function, or a path to a function. The `handler` will run once a worker picks picks up a Job that includes this task.
@@ -93,6 +93,8 @@ export default buildConfig({
In addition to defining handlers as functions directly provided to your Payload config, you can also pass an _absolute path_ to where the handler is defined. If your task has large dependencies, and you are planning on executing your jobs in a separate process that has access to the filesystem, this could be a handy way to make sure that your Payload + Next.js app remains quick to compile and has minimal dependencies.
Keep in mind that this is an advanced feature that may require a sophisticated build pipeline, especially when using it in production or within Next.js, e.g. by calling opening the `/api/payload-jobs/run` endpoint. You will have to transpile the handler files separately and ensure they are available in the same location when the job is run. If you're using an endpoint to execute your jobs, it's recommended to define your handlers as functions directly in your Payload Config, or use import paths handlers outside of Next.js.
In general, this is an advanced use case. Here's how this would look:
`payload.config.ts:`

View File

@@ -2,7 +2,7 @@
title: Workflows
label: Workflows
order: 30
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
---
@@ -25,11 +25,12 @@ To define a JS-based workflow, simply add a workflow to the `jobs.wokflows` arra
| Option | Description |
| --------------------------- | -------------------------------------------------------------------------------- |
| `slug` | Define a slug-based name for this workflow. This slug needs to be unique among both tasks and workflows.|
| `handler` | The function that should be responsible for running the workflow. You can either pass a string-based path to the workflow function file, or workflow job function itself. If you are using large dependencies within your workflow, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. |
| `handler` | The function that should be responsible for running the workflow. You can either pass a string-based path to the workflow function file, or workflow job function itself. If you are using large dependencies within your workflow, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. Passing a string path is an advanced feature that may require a sophisticated build pipeline in order to work. |
| `inputSchema` | Define the input field schema - payload will generate a type for this schema. |
| `interfaceName` | You can use interfaceName to change the name of the interface that is generated for this workflow. By default, this is "Workflow" + the capitalized workflow slug. |
| `label` | Define a human-friendly label for this workflow. |
| `queue` | Optionally, define the queue name that this workflow should be tied to. Defaults to "default". |
| `retries` | You can define `retries` on the workflow level, which will enforce that the workflow can only fail up to that number of retries. If a task does not have retries specified, it will inherit the retry count as specified on the workflow. You can specify `0` as `workflow` retries, which will disregard all `task` retry specifications and fail the entire workflow on any task failure. You can leave `workflow` retries as undefined, in which case, the workflow will respect what each task dictates as their own retry count. By default this is undefined, meaning workflows retries are defined by their tasks |
Example:

View File

@@ -304,6 +304,27 @@ const result = await payload.delete({
If a collection has [`Authentication`](/docs/authentication/overview) enabled, additional Local API operations will be
available:
### Auth
```js
// If you're using nextjs, you'll have to import headers from next/headers, like so:
// import { headers as nextHeaders } from 'next/headers'
// you'll also have to await headers inside your function, or component, like so:
// const headers = await nextHeaders()
// If you're using payload outside of NextJS, you'll have to provide headers accordingly.
// result will be formatted as follows:
// {
// permissions: { ... }, // object containing current user's permissions
// user: { ... }, // currently logged in user's document
// responseHeaders: { ... } // returned headers from the response
// }
const result = await payload.auth({headers})
```
### Login
```js

View File

@@ -10,6 +10,8 @@ keywords: local api, config, configuration, documentation, Content Management Sy
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.
If you are upgrading from a _previous beta_, please see the [Upgrade From Previous Beta](#upgrade-from-previous-beta) section.
## 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, 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.
@@ -26,6 +28,7 @@ All breaking changes are listed below. If you encounter changes that are not exp
- [Types](#types)
- [Email Adapters](#email-adapters)
- [Plugins](#plugins)
- [Upgrade From Previous Beta](#upgrade-from-previous-beta)
## Installation
@@ -1100,3 +1103,9 @@ plugins: [
## `@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).
## Upgrade from previous beta
Reference this [community-made site](https://payload-releases-filter.vercel.app/?version=3&from=152429656&to=188243150&sort=asc&breaking=on). Set your version, sort by oldest first, enable breaking changes only.
Then go through each one of the breaking changes and make the adjustments. You can optionally reference the [blank template](https://github.com/payloadcms/payload/tree/main/templates/blank) for how things should end up.

367
examples/custom-server/.gitignore vendored Normal file
View File

@@ -0,0 +1,367 @@
# Created by https://www.toptal.com/developers/gitignore/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=node,macos,windows,webstorm,sublimetext,visualstudiocode
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
### SublimeText ###
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### WebStorm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### WebStorm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk

View File

@@ -0,0 +1,5 @@
# Payload 3 with Custom Server
Uses a [Next.js Custom Server](https://nextjs.org/docs/pages/building-your-application/configuring/custom-server) with express.
Made from official [examples/custom-server](https://github.com/vercel/next.js/tree/canary/examples/custom-server) from Next.js repository.

5
examples/custom-server/next-env.d.ts vendored Normal file
View File

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

View File

@@ -0,0 +1,6 @@
import { withPayload } from "@payloadcms/next/withPayload";
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default withPayload(nextConfig)

View File

@@ -0,0 +1,5 @@
{
"watch": ["src/server.ts"],
"exec": "tsx src/server.ts",
"ext": "ts"
}

View File

@@ -0,0 +1,41 @@
{
"name": "payload-3-custom-server",
"scripts": {
"dev": "nodemon",
"build": "next build && tsc --project tsconfig.server.json",
"start": "cross-env NODE_ENV=production node dist/server.js",
"generate:importmap": "cross-env NODE_OPTIONS=--no-deprecation payload generate:importmap",
"generate:types": "cross-env NODE_OPTIONS=--no-deprecation payload generate:types",
"payload": "cross-env NODE_OPTIONS=--no-deprecation payload"
},
"type": "module",
"dependencies": {
"@payloadcms/db-mongodb": "latest",
"@payloadcms/next": "latest",
"@payloadcms/payload-cloud": "latest",
"@payloadcms/richtext-lexical": "latest",
"cross-env": "^7.0.3",
"express": "^4.21.1",
"graphql": "^16.8.1",
"next": "15.0.3",
"payload": "latest",
"react": "19.0.0-rc-65a56d0e-20241020",
"react-dom": "19.0.0-rc-65a56d0e-20241020"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/node": "^18.11.5",
"@types/react": "npm:types-react@19.0.0-rc.1",
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1",
"nodemon": "^3.1.7",
"ts-node": "^10.9.2",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
},
"pnpm": {
"overrides": {
"@types/react": "npm:types-react@19.0.0-rc.1",
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.1"
}
}
}

View File

@@ -0,0 +1,3 @@
export default function B() {
return <div>b</div>;
}

View File

@@ -0,0 +1,11 @@
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}

View File

@@ -0,0 +1,24 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import type { Metadata } from 'next'
import config from '@payload-config'
import { NotFoundPage, generatePageMetadata } from '@payloadcms/next/views'
import { importMap } from '../importMap'
type Args = {
params: Promise<{
segments: string[]
}>
searchParams: Promise<{
[key: string]: string | string[]
}>
}
export const generateMetadata = ({ params, searchParams }: Args): Promise<Metadata> =>
generatePageMetadata({ config, params, searchParams })
const NotFound = ({ params, searchParams }: Args) =>
NotFoundPage({ config, params, searchParams, importMap })
export default NotFound

View File

@@ -0,0 +1,24 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import type { Metadata } from 'next'
import config from '@payload-config'
import { RootPage, generatePageMetadata } from '@payloadcms/next/views'
import { importMap } from '../importMap'
type Args = {
params: Promise<{
segments: string[]
}>
searchParams: Promise<{
[key: string]: string | string[]
}>
}
export const generateMetadata = ({ params, searchParams }: Args): Promise<Metadata> =>
generatePageMetadata({ config, params, searchParams })
const Page = ({ params, searchParams }: Args) =>
RootPage({ config, params, searchParams, importMap })
export default Page

View File

@@ -0,0 +1,5 @@
export const importMap = {
}

View File

@@ -0,0 +1,19 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import config from '@payload-config'
import '@payloadcms/next/css'
import {
REST_DELETE,
REST_GET,
REST_OPTIONS,
REST_PATCH,
REST_POST,
REST_PUT,
} from '@payloadcms/next/routes'
export const GET = REST_GET(config)
export const POST = REST_POST(config)
export const DELETE = REST_DELETE(config)
export const PATCH = REST_PATCH(config)
export const PUT = REST_PUT(config)
export const OPTIONS = REST_OPTIONS(config)

View File

@@ -0,0 +1,7 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import config from '@payload-config'
import '@payloadcms/next/css'
import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes'
export const GET = GRAPHQL_PLAYGROUND_GET(config)

View File

@@ -0,0 +1,31 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import config from '@payload-config'
import '@payloadcms/next/css'
import type { ServerFunctionClient } from 'payload'
import { handleServerFunctions, RootLayout } from '@payloadcms/next/layouts'
import React from 'react'
import { importMap } from './admin/importMap.js'
import './custom.scss'
type Args = {
children: React.ReactNode
}
const serverFunction: ServerFunctionClient = async function (args) {
'use server'
return handleServerFunctions({
...args,
config,
importMap,
})
}
const Layout = ({ children }: Args) => (
<RootLayout config={config} importMap={importMap} serverFunction={serverFunction}>
{children}
</RootLayout>
)
export default Layout

View File

@@ -0,0 +1,16 @@
import type { CollectionConfig } from 'payload'
export const Media: CollectionConfig = {
slug: 'media',
access: {
read: () => true,
},
fields: [
{
name: 'alt',
type: 'text',
required: true,
},
],
upload: true,
}

View File

@@ -0,0 +1,13 @@
import type { CollectionConfig } from 'payload'
export const Users: CollectionConfig = {
slug: 'users',
admin: {
useAsTitle: 'email',
},
auth: true,
fields: [
// Email added by default
// Add more fields as needed
],
}

View File

@@ -0,0 +1,229 @@
/* 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 {
auth: {
users: UserAuthOperations;
};
collections: {
users: User;
media: Media;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
'payload-migrations': PayloadMigration;
};
collectionsJoins: {};
collectionsSelect: {
users: UsersSelect<false> | UsersSelect<true>;
media: MediaSelect<false> | MediaSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
'payload-migrations': PayloadMigrationsSelect<false> | PayloadMigrationsSelect<true>;
};
db: {
defaultIDType: string;
};
globals: {};
globalsSelect: {};
locale: null;
user: User & {
collection: 'users';
};
jobs: {
tasks: unknown;
workflows: unknown;
};
}
export interface UserAuthOperations {
forgotPassword: {
email: string;
password: string;
};
login: {
email: string;
password: string;
};
registerFirstUser: {
email: string;
password: string;
};
unlock: {
email: string;
password: string;
};
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "users".
*/
export interface User {
id: string;
updatedAt: string;
createdAt: string;
email: string;
resetPasswordToken?: string | null;
resetPasswordExpiration?: string | null;
salt?: string | null;
hash?: string | null;
loginAttempts?: number | null;
lockUntil?: string | null;
password?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media".
*/
export interface Media {
id: string;
alt: string;
updatedAt: string;
createdAt: string;
url?: string | null;
thumbnailURL?: string | null;
filename?: string | null;
mimeType?: string | null;
filesize?: number | null;
width?: number | null;
height?: number | null;
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-locked-documents".
*/
export interface PayloadLockedDocument {
id: string;
document?:
| ({
relationTo: 'users';
value: string | User;
} | null)
| ({
relationTo: 'media';
value: string | Media;
} | null);
globalSlug?: string | null;
user: {
relationTo: 'users';
value: string | User;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-preferences".
*/
export interface PayloadPreference {
id: string;
user: {
relationTo: 'users';
value: string | User;
};
key?: string | null;
value?:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-migrations".
*/
export interface PayloadMigration {
id: string;
name?: string | null;
batch?: number | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "users_select".
*/
export interface UsersSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
email?: T;
resetPasswordToken?: T;
resetPasswordExpiration?: T;
salt?: T;
hash?: T;
loginAttempts?: T;
lockUntil?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media_select".
*/
export interface MediaSelect<T extends boolean = true> {
alt?: T;
updatedAt?: T;
createdAt?: T;
url?: T;
thumbnailURL?: T;
filename?: T;
mimeType?: T;
filesize?: T;
width?: T;
height?: T;
focalX?: T;
focalY?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-locked-documents_select".
*/
export interface PayloadLockedDocumentsSelect<T extends boolean = true> {
document?: T;
globalSlug?: T;
user?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-preferences_select".
*/
export interface PayloadPreferencesSelect<T extends boolean = true> {
user?: T;
key?: T;
value?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-migrations_select".
*/
export interface PayloadMigrationsSelect<T extends boolean = true> {
name?: T;
batch?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "auth".
*/
export interface Auth {
[k: string]: unknown;
}
declare module 'payload' {
export interface GeneratedTypes extends Config {}
}

View File

@@ -0,0 +1,31 @@
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import path from 'path'
import express from 'express'
import { buildConfig } from 'payload'
import { fileURLToPath } from 'url'
import { Users } from './collections/Users'
import { Media } from './collections/Media'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export default buildConfig({
admin: {
user: Users.slug,
importMap: {
baseDir: path.resolve(dirname),
},
},
collections: [Users, Media],
editor: lexicalEditor(),
secret: process.env.PAYLOAD_SECRET || '',
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
db: mongooseAdapter({
url: process.env.DATABASE_URI || '',
}),
plugins: [],
})

View File

@@ -0,0 +1,26 @@
import express from 'express'
import type { Request, Response } from 'express'
import { parse } from 'url'
import next from 'next'
const port = parseInt(process.env.PORT || '3000', 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.all('*', (req, res) => {
const parsedUrl = parse(req.url!, true)
handle(req, res, parsedUrl)
})
server.listen(port, () => {
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`,
)
})
})

View File

@@ -1,14 +1,15 @@
{
"compilerOptions": {
"baseUrl": ".",
"target": "es5",
"lib": [
"DOM",
"DOM.Iterable",
"ES2022"
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
@@ -22,6 +23,7 @@
"name": "next"
}
],
"strictNullChecks": true,
"paths": {
"@/*": [
"./src/*"
@@ -30,7 +32,6 @@
"./src/payload.config.ts"
]
},
"target": "ES2022",
},
"include": [
"next-env.d.ts",

View File

@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"outDir": "dist",
"lib": ["es2019"],
"target": "ESNext",
"isolatedModules": false,
"noEmit": false
},
"include": ["src/server.ts"]
}

View File

@@ -1,4 +1,3 @@
DATABASE_URI=mongodb://127.0.0.1/payload-template-blank-3-0
DATABASE_URI=mongodb://127.0.0.1/payload-form-builder-example
PAYLOAD_SECRET=YOUR_SECRET_HERE
PAYLOAD_SEED=true
NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000

View File

@@ -0,0 +1,8 @@
module.exports = {
extends: 'next',
root: true,
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
}

View File

@@ -0,0 +1,53 @@
# Payload Form Builder Example
The [Payload Form Builder Example](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload) demonstrates how to implement the official [Form Builder Plugin](https://payloadcms.com/docs/plugins/form-builder) in [Payload](https://github.com/payloadcms/payload).
**IMPORTANT—This example includes a fully integrated Next.js App Router front-end that runs on the same server as Payload.**
## Quick Start
1. Clone this repo
2. `cd` into this directory and run `pnpm i --ignore-workspace`\*, `yarn`, or `npm install`
> \*If you are running using pnpm within the Payload Monorepo, the `--ignore-workspace` flag is needed so that pnpm generates a lockfile in this example's directory despite the fact that one exists in root.
3. `cp .env.example .env` to copy the example environment variables
4. `pnpm dev`, `yarn dev` or `npm run dev` to start the server
- Press `y` when prompted to seed the database
5. `open http://localhost:3000` to access the home page
6. `open http://localhost:3000/admin` to access the admin panel
- Login with email `demo@payloadcms.com` and password `demo`
That's it! Changes made in `./src` will be
## How it works
The [Form Builder Plugin](https://payloadcms.com/docs/plugins/form-builder) automatically adds the `forms` and `formSubmissions` collections to your config which your front-end can use to query forms and submit form data. You can embed forms into layout building blocks by referring a `forms` document in a relationship field.
See the official [Form Builder Plugin](https://payloadcms.com/docs/plugins/form-builder) 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. You can remove `pnpm seed` from the `dev` script in the `package.json` to prevent this behavior. You can also freshly seed your project at any time by running `pnpm seed`. This seed creates a user with email `demo@payloadcms.com` and password `demo` along with a home page and an example page with two versions, one published and the other draft.
> 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.
## Production
To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps:
1. Invoke the `next build` script by running `pnpm build` or `npm run build` in your project root. This creates a `.next` directory with a production-ready admin bundle.
1. Finally run `pnpm start` or `npm run start` 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,10 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
max_line_length = null

View File

@@ -1 +0,0 @@
NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000

View File

@@ -1,21 +0,0 @@
module.exports = {
extends: ['plugin:@next/next/core-web-vitals', '@payloadcms'],
ignorePatterns: ['**/payload-types.ts'],
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
{
files: ['./app/**/*.ts', './app/**/*.tsx'],
rules: {
'no-restricted-exports': 'off',
},
},
],
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
root: true,
}

View File

@@ -1,38 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
.env

View File

@@ -1,38 +0,0 @@
# Form Builder Example Front-End
This is a [Next.js](https://nextjs.org) app using the [Pages Router](https://nextjs.org/docs/pages). It was made explicitly for Payload's [Form Builder Example](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload).
> This example uses the Pages Router, the legacy API of Next.js. If your app is using the latest [App Router](https://nextjs.org/docs/app), we will add an example for that soon.
## Getting Started
### Payload
First you'll need a running Payload app. There is one made explicitly for this example and [can be found here](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload). If you have not done so already, clone it down and follow the setup instructions there.
### Next.js App
1. Clone this repo
2. `cd` into this directory and run `yarn` or `npm install`
3. `cp .env.example .env` to copy the example environment variables
4. `yarn dev` or `npm run dev` to start the server
5. `open http://localhost:3001` to see the result
Once running you will find a couple seeded pages on your local environment with some basic instructions. You can also start editing the pages by modifying the documents within Payload. See the [Form Builder Example](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload) for full details.
## Learn More
To learn more about Payload and Next.js, take a look at the following resources:
- [Payload Documentation](https://payloadcms.com/docs) - learn about Payload features and API.
- [Form Builder Plugin Documentation](https://github.com/payloadcms/plugin-form-builder) - learn about the plugin's features.
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Payload GitHub repository](https://github.com/payloadcms/payload/) as well as [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Payload deployment documentation](https://payloadcms.com/docs/production/deployment) or the [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View File

@@ -1,40 +0,0 @@
import type { GetStaticPaths } from 'next'
import React from 'react'
import type { Page } from '../../payload-types'
import Blocks from '../../components/Blocks'
export default async function Page({ params: { slug = 'home' } }) {
const page = await getPage(slug)
return (
<React.Fragment>
<Blocks blocks={page.layout} />
</React.Fragment>
)
}
export const getPage = async (slug: string) => {
const pageQuery = await fetch(
`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages?where[slug][equals]=${slug}`,
).then((res) => res.json())
return pageQuery.docs[0]
}
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
const pagesQuery: { docs: Page[] } = await fetch(
`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/pages?limit=100`,
).then((res) => res.json())
return {
fallback: 'blocking',
paths: pagesQuery.docs.map((page) => ({
params: {
slug: page.slug,
},
})),
}
}

View File

@@ -1,53 +0,0 @@
import { ModalContainer, ModalProvider } from '@faceless-ui/modal'
import React from 'react'
import type { MainMenu } from '../payload-types'
import { CloseModalOnRouteChange } from '../components/CloseModalOnRouteChange'
import { Header } from '../components/Header'
import '../css/app.scss'
import { GlobalsProvider } from '../providers/Globals'
export interface IGlobals {
mainMenu: MainMenu
}
export const metadata = {
description: 'An example of how to authenticate with Payload from a Next.js app.',
title: 'Payload Auth + Next.js App Router Example',
}
export const getAllGlobals = async (): Promise<IGlobals> => {
const [mainMenu] = await Promise.all([
fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/globals/main-menu?depth=1`).then((res) =>
res.json(),
),
])
return {
mainMenu,
}
}
export default async function RootLayout(props: { children: React.ReactNode }) {
const { children } = props
const globals = await getAllGlobals()
return (
<html lang="en">
<body>
<React.Fragment>
<GlobalsProvider {...globals}>
<ModalProvider classPrefix="form" transTime={0} zIndex="var(--modal-z-index)">
<CloseModalOnRouteChange />
<Header />
{/* <Component {...pageProps} /> */}
{children}
<ModalContainer />
</ModalProvider>
</GlobalsProvider>
</React.Fragment>
</body>
</html>
)
}

View File

@@ -1,62 +0,0 @@
import type { CheckboxField } from 'payload-plugin-form-builder/dist/types'
import type { FieldErrorsImpl, FieldValues, UseFormRegister } from 'react-hook-form'
import React, { useState } from 'react'
import { Check } from '../../../icons/Check'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Checkbox: React.FC<
CheckboxField & {
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
getValues: any
register: UseFormRegister<FieldValues & any>
setValue: any
}
> = ({
name,
errors,
getValues,
label,
register,
required: requiredFromProps,
setValue,
width,
}) => {
const [checked, setChecked] = useState(false)
const isCheckboxChecked = getValues(name)
return (
<Width width={width}>
<div className={[classes.checkbox, checked && classes.checked].filter(Boolean).join(' ')}>
<div className={classes.container}>
<input
type="checkbox"
{...register(name, { required: requiredFromProps })}
checked={isCheckboxChecked}
/>
<button
onClick={() => {
setValue(name, !checked)
setChecked(!checked)
}}
type="button"
>
<span className={classes.input}>
<Check />
</span>
</button>
<span className={classes.label}>{label}</span>
</div>
{requiredFromProps && errors[name] && checked === false && <Error />}
</div>
</Width>
)
}

View File

@@ -1,49 +0,0 @@
import type { SelectField } from 'payload-plugin-form-builder/dist/types'
import type { Control, FieldErrorsImpl, FieldValues } from 'react-hook-form'
import React from 'react'
import { Controller } from 'react-hook-form'
import ReactSelect from 'react-select'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Select: React.FC<
SelectField & {
control: Control<FieldValues, any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, control, errors, label, options, required, width }) => {
return (
<Width width={width}>
<div className={classes.select}>
<label className={classes.label} htmlFor={name}>
{label}
</label>
<Controller
control={control}
defaultValue=""
name={name}
render={({ field: { onChange, value } }) => (
<ReactSelect
className={classes.reactSelect}
classNamePrefix="rs"
inputId={name}
instanceId={name}
onChange={(val) => onChange(val.value)}
options={options}
value={options.find((s) => s.value === value)}
/>
)}
rules={{ required }}
/>
{required && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,50 +0,0 @@
import type { StateField } from 'payload-plugin-form-builder/dist/types'
import type { Control, FieldErrorsImpl, FieldValues } from 'react-hook-form'
import React from 'react'
import { Controller } from 'react-hook-form'
import ReactSelect from 'react-select'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
import { stateOptions } from './options'
export const State: React.FC<
StateField & {
control: Control<FieldValues, any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, control, errors, label, required, width }) => {
return (
<Width width={width}>
<div className={classes.select}>
<label className={classes.label} htmlFor={name}>
{label}
</label>
<Controller
control={control}
defaultValue=""
name={name}
render={({ field: { onChange, value } }) => (
<ReactSelect
className={classes.reactSelect}
classNamePrefix="rs"
id={name}
instanceId={name}
onChange={(val) => onChange(val.value)}
options={stateOptions}
value={stateOptions.find((t) => t.value === value)}
/>
)}
rules={{ required }}
/>
{required && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,37 +0,0 @@
import type { TextField } from 'payload-plugin-form-builder/dist/types'
import type { FieldErrorsImpl, FieldValues, UseFormRegister } from 'react-hook-form'
import React from 'react'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Textarea: React.FC<
TextField & {
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
register: UseFormRegister<FieldValues & any>
rows?: number
}
> = ({ name, errors, label, register, required: requiredFromProps, rows = 3, width }) => {
return (
<Width width={width}>
<div className={classes.wrap}>
<label className={classes.label} htmlFor={name}>
{label}
</label>
<textarea
className={classes.textarea}
id={name}
rows={rows}
{...register(name, { required: requiredFromProps })}
/>
{requiredFromProps && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,42 +0,0 @@
import type { FormFieldBlock } from 'payload-plugin-form-builder/dist/types'
export const buildInitialFormState = (fields: FormFieldBlock[]) => {
return fields.reduce((initialSchema, field) => {
if (field.blockType === 'checkbox') {
return {
...initialSchema,
[field.name]: false,
}
}
if (field.blockType === 'country') {
return {
...initialSchema,
[field.name]: '',
}
}
if (field.blockType === 'email') {
return {
...initialSchema,
[field.name]: '',
}
}
if (field.blockType === 'text') {
return {
...initialSchema,
[field.name]: '',
}
}
if (field.blockType === 'select') {
return {
...initialSchema,
[field.name]: '',
}
}
if (field.blockType === 'state') {
return {
...initialSchema,
[field.name]: '',
}
}
}, {})
}

View File

@@ -1,51 +0,0 @@
import React, { Fragment } from 'react'
import type { Page } from '../../payload-types'
import { toKebabCase } from '../../utilities/toKebabCase'
import { VerticalPadding } from '../VerticalPadding'
import { FormBlock } from './Form'
const blockComponents = {
formBlock: FormBlock,
}
const Blocks: React.FC<{
blocks: Page['layout']
}> = (props) => {
const { blocks } = props
const hasBlocks = blocks && Array.isArray(blocks) && blocks.length > 0
if (hasBlocks) {
return (
<Fragment>
{blocks.map((block, index) => {
const { blockName, blockType, form } = block
const isFormBlock = blockType === 'formBlock'
{
/*@ts-expect-error*/
}
const formID: string = isFormBlock && form && (typeof form === 'string' ? form : form.id)
if (blockType && blockType in blockComponents) {
const Block = blockComponents[blockType]
return (
<VerticalPadding bottom="small" key={isFormBlock ? formID : index} top="small">
{/*@ts-expect-error*/}
<Block id={toKebabCase(blockName)} {...block} />
</VerticalPadding>
)
}
return null
})}
</Fragment>
)
}
return null
}
export default Blocks

View File

@@ -1,18 +0,0 @@
'use client'
import type React from 'react'
import { useModal } from '@faceless-ui/modal'
import { usePathname } from 'next/navigation'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
export const CloseModalOnRouteChange: React.FC = () => {
const { closeAllModals } = useModal()
const pathname = usePathname()
useEffect(() => {
closeAllModals()
}, [pathname, closeAllModals])
return null
}

View File

@@ -1,54 +0,0 @@
'use client'
import { ModalToggler } from '@faceless-ui/modal'
import Link from 'next/link'
import React from 'react'
import { useGlobals } from '../../providers/Globals'
import { Gutter } from '../Gutter'
import { CMSLink } from '../Link'
import { Logo } from '../Logo'
import { MenuIcon } from '../icons/Menu'
import { MobileMenuModal, slug as menuModalSlug } from './MobileMenuModal'
import classes from './index.module.scss'
type HeaderBarProps = {
children?: React.ReactNode
}
export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => {
return (
<header className={classes.header}>
<Gutter className={classes.wrap}>
<Link href="/">
<Logo />
</Link>
{children}
<ModalToggler className={classes.mobileMenuToggler} slug={menuModalSlug}>
<MenuIcon />
</ModalToggler>
</Gutter>
</header>
)
}
export const Header: React.FC = () => {
const {
mainMenu: { navItems },
} = useGlobals()
return (
<React.Fragment>
<HeaderBar>
<nav className={classes.nav}>
{navItems.map(({ link }, i) => {
return <CMSLink key={i} {...link} />
})}
</nav>
</HeaderBar>
<MobileMenuModal navItems={navItems} />
</React.Fragment>
)
}

View File

@@ -1,67 +0,0 @@
import Link from 'next/link'
import React from 'react'
import type { Page } from '../../payload-types'
import { Button } from '../Button'
type CMSLinkType = {
appearance?: 'default' | 'primary' | 'secondary'
children?: React.ReactNode
className?: string
label?: string
newTab?: boolean
reference?: {
relationTo: 'pages'
value: Page | string
}
type?: 'custom' | 'reference'
url?: string
}
export const CMSLink: React.FC<CMSLinkType> = ({
type,
appearance,
children,
className,
label,
newTab,
reference,
url,
}) => {
const href =
type === 'reference' && typeof reference?.value === 'object' && reference.value.slug
? `/${reference.value.slug}`
: url
if (!appearance) {
const newTabProps = newTab ? { rel: 'noopener noreferrer', target: '_blank' } : {}
if (type === 'custom') {
return (
<Link href={url} {...newTabProps} className={className}>
{label && label}
{children && children}
</Link>
)
}
if (href) {
return (
<Link href={href} {...newTabProps} className={className}>
{label && label}
{children && children}
</Link>
)
}
}
const buttonProps = {
appearance,
href,
label,
newTab,
}
return <Button className={className} {...buttonProps} el="link" />
}

View File

@@ -1,3 +0,0 @@
.container {
max-width: 480px;
}

View File

@@ -1,26 +0,0 @@
import React from 'react'
import styles from './index.module.scss'
import { serializeLexical } from './serialize'
const RichText: React.FC<{ className?: string; content: any; enableGutter?: boolean }> = ({
className,
content,
enableGutter = true,
}) => {
if (!content) {
return null
}
return (
<div className={[className].filter(Boolean).join(' ')}>
{content &&
!Array.isArray(content) &&
typeof content === 'object' &&
'root' in content &&
serializeLexical({ nodes: content?.root?.children })}
</div>
)
}
export default RichText

View File

@@ -1,128 +0,0 @@
/* eslint-disable regexp/no-obscure-range */
/* eslint-disable @typescript-eslint/no-redundant-type-constituents */
// @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 '@payloadcms/richtext-lexical/lexical'
import type { TextDetailType, TextModeType } from 'lexical/nodes/LexicalTextNode'
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// DOM
export const DOM_ELEMENT_TYPE = 1
export const DOM_TEXT_TYPE = 3
// Reconciling
export const NO_DIRTY_NODES = 0
export const HAS_DIRTY_NODES = 1
export const FULL_RECONCILE = 2
// Text node modes
export const IS_NORMAL = 0
export const IS_TOKEN = 1
export const IS_SEGMENTED = 2
// IS_INERT = 3
// Text node formatting
export const IS_BOLD = 1
export const IS_ITALIC = 1 << 1
export const IS_STRIKETHROUGH = 1 << 2
export const IS_UNDERLINE = 1 << 3
export const IS_CODE = 1 << 4
export const IS_SUBSCRIPT = 1 << 5
export const IS_SUPERSCRIPT = 1 << 6
export const IS_HIGHLIGHT = 1 << 7
export const IS_ALL_FORMATTING =
IS_BOLD |
IS_ITALIC |
IS_STRIKETHROUGH |
IS_UNDERLINE |
IS_CODE |
IS_SUBSCRIPT |
IS_SUPERSCRIPT |
IS_HIGHLIGHT
// Text node details
export const IS_DIRECTIONLESS = 1
export const IS_UNMERGEABLE = 1 << 1
// Element node formatting
export const IS_ALIGN_LEFT = 1
export const IS_ALIGN_CENTER = 2
export const IS_ALIGN_RIGHT = 3
export const IS_ALIGN_JUSTIFY = 4
export const IS_ALIGN_START = 5
export const IS_ALIGN_END = 6
// Reconciliation
export const NON_BREAKING_SPACE = '\u00A0'
const ZERO_WIDTH_SPACE = '\u200b'
export const DOUBLE_LINE_BREAK = '\n\n'
// For FF, we need to use a non-breaking space, or it gets composition
// in a stuck state.
const RTL = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC'
const LTR =
'A-Za-z\u00C0-\u00D6\u00D8-\u00F6' +
'\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C' +
'\uFE00-\uFE6F\uFEFD-\uFFFF'
// eslint-disable-next-line
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<string | TextFormatType, number> = {
bold: IS_BOLD,
code: IS_CODE,
highlight: IS_HIGHLIGHT,
italic: IS_ITALIC,
strikethrough: IS_STRIKETHROUGH,
subscript: IS_SUBSCRIPT,
superscript: IS_SUPERSCRIPT,
underline: IS_UNDERLINE,
}
export const DETAIL_TYPE_TO_DETAIL: Record<string | TextDetailType, number> = {
directionless: IS_DIRECTIONLESS,
unmergeable: IS_UNMERGEABLE,
}
export const ELEMENT_TYPE_TO_FORMAT: Record<Exclude<ElementFormatType, ''>, number> = {
center: IS_ALIGN_CENTER,
end: IS_ALIGN_END,
justify: IS_ALIGN_JUSTIFY,
left: IS_ALIGN_LEFT,
right: IS_ALIGN_RIGHT,
start: IS_ALIGN_START,
}
export const ELEMENT_FORMAT_TO_TYPE: Record<number, ElementFormatType> = {
[IS_ALIGN_CENTER]: 'center',
[IS_ALIGN_END]: 'end',
[IS_ALIGN_JUSTIFY]: 'justify',
[IS_ALIGN_LEFT]: 'left',
[IS_ALIGN_RIGHT]: 'right',
[IS_ALIGN_START]: 'start',
}
export const TEXT_MODE_TO_TYPE: Record<TextModeType, 0 | 1 | 2> = {
normal: IS_NORMAL,
segmented: IS_SEGMENTED,
token: IS_TOKEN,
}
export const TEXT_TYPE_TO_MODE: Record<number, TextModeType> = {
[IS_NORMAL]: 'normal',
[IS_SEGMENTED]: 'segmented',
[IS_TOKEN]: 'token',
}

View File

@@ -1,208 +0,0 @@
import type { LinkFields, SerializedLinkNode } from '@payloadcms/richtext-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'
import { CMSLink } from '../Link'
import {
IS_BOLD,
IS_CODE,
IS_ITALIC,
IS_STRIKETHROUGH,
IS_SUBSCRIPT,
IS_SUPERSCRIPT,
IS_UNDERLINE,
} from './nodeFormat'
interface Props {
nodes: SerializedLexicalNode[]
}
export function serializeLexical({ nodes }: Props): JSX.Element {
return (
<Fragment>
{nodes?.map((_node, index): JSX.Element | null => {
if (_node.type === 'text') {
const node = _node as SerializedTextNode
let text = <React.Fragment key={index}>{node.text}</React.Fragment>
if (node.format & IS_BOLD) {
text = <strong key={index}>{text}</strong>
}
if (node.format & IS_ITALIC) {
text = <em key={index}>{text}</em>
}
if (node.format & IS_STRIKETHROUGH) {
text = (
<span key={index} style={{ textDecoration: 'line-through' }}>
{text}
</span>
)
}
if (node.format & IS_UNDERLINE) {
text = (
<span key={index} style={{ textDecoration: 'underline' }}>
{text}
</span>
)
}
if (node.format & IS_CODE) {
text = <code key={index}>{node.text}</code>
}
if (node.format & IS_SUBSCRIPT) {
text = <sub key={index}>{text}</sub>
}
if (node.format & IS_SUPERSCRIPT) {
text = <sup key={index}>{text}</sup>
}
return text
}
if (_node == null) {
return null
}
// NOTE: Hacky fix for
// https://github.com/facebook/lexical/blob/d10c4e6e55261b2fdd7d1845aed46151d0f06a8c/packages/lexical-list/src/LexicalListItemNode.ts#L133
// which does not return checked: false (only true - i.e. there is no prop for false)
const serializedChildrenFn = (node: SerializedElementNode): JSX.Element | null => {
if (node.children == null) {
return null
} else {
if (node?.type === 'list' && (node as SerializedListNode)?.listType === 'check') {
for (const item of node.children) {
if ('checked' in item) {
if (!item?.checked) {
item.checked = false
}
}
}
return serializeLexical({ nodes: node.children })
} else {
return serializeLexical({ nodes: node.children })
}
}
}
const serializedChildren =
'children' in _node ? serializedChildrenFn(_node as SerializedElementNode) : ''
switch (_node.type) {
case 'heading': {
const node = _node as SerializedHeadingNode
type Heading = Extract<keyof JSX.IntrinsicElements, 'h1' | 'h2' | 'h3' | 'h4' | 'h5'>
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
type List = Extract<keyof JSX.IntrinsicElements, 'ol' | 'ul'>
const Tag = node?.tag as List
return (
<Tag className="list" key={index}>
{serializedChildren}
</Tag>
)
}
case 'listitem': {
const node = _node as SerializedListItemNode
if (node?.checked != null) {
return (
<li
aria-checked={node.checked ? 'true' : 'false'}
className={` ${node.checked ? '' : ''}`}
key={index}
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role
role="checkbox"
tabIndex={-1}
value={node?.value}
>
{serializedChildren}
</li>
)
} else {
return (
<li key={index} value={node?.value}>
{serializedChildren}
</li>
)
}
}
case 'paragraph': {
return <p key={index}>{serializedChildren}</p>
}
case 'quote': {
return <blockquote key={index}>{serializedChildren}</blockquote>
}
/* case 'block': {
// todo: fix types
//@ts-expect-error
const block = _node.fields
//@ts-expect-error
const blockType = _node.fields?.blockType
if (!block || !blockType) {
return null
}
switch (blockType) {
case 'content':
return <ContentBlock {...block} />
case 'cta':
return <CallToActionBlock {...block} />
case 'archive':
return <ArchiveBlock {...block} />
case 'mediaBlock':
return <MediaBlock {...block} />
case 'banner':
return <BannerBlock {...block} />
case 'code':
return <CodeBlock {...block} />
default:
return null
}
} */
default:
return null
}
})}
</Fragment>
)
}

View File

@@ -1,10 +0,0 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['localhost', process.env.NEXT_PUBLIC_PAYLOAD_URL || ''].filter(Boolean),
},
reactStrictMode: true,
swcMinify: true,
}
module.exports = nextConfig

View File

@@ -1,41 +0,0 @@
{
"name": "payload-example-form-builder-website",
"version": "0.1.0",
"private": true,
"scripts": {
"build": "next build",
"dev": "next dev -p 3001",
"lint": "next lint",
"start": "next start"
},
"dependencies": {
"@apollo/client": "^3.7.0",
"@faceless-ui/css-grid": "^1.2.0",
"@faceless-ui/modal": "^2.0.2",
"@payloadcms/plugin-form-builder": "beta",
"@payloadcms/richtext-lexical": "beta",
"escape-html": "^1.0.3",
"graphql": "^16.8.1",
"next": "^14.3.0-canary.68",
"react": "18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.41.0",
"react-select": "^5.7.0",
"sass": "^1.55.0",
"slate": "^0.84.0"
},
"devDependencies": {
"@next/eslint-plugin-next": "^13.5.6",
"@types/node": "^20",
"@types/react": "^18.0.21",
"eslint": "8.57.0",
"eslint-config-next": "12.3.1",
"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",
"typescript": "^5.4"
}
}

View File

@@ -1,241 +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
forms: Form
'form-submissions': FormSubmission
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {
'main-menu': MainMenu
}
}
export interface Page {
id: string
title: string
layout: {
form: string | Form
enableIntro?: boolean
introContent: {
[k: string]: unknown
}[]
id?: string
blockName?: string
blockType: 'formBlock'
}[]
slug?: string
updatedAt: string
createdAt: string
_status?: 'draft' | 'published'
}
export interface Form {
id: string
title: string
fields?: (
| {
name: string
label?: string
width?: number
defaultValue?: string
required?: boolean
id?: string
blockName?: string
blockType: 'text'
}
| {
name: string
label?: string
width?: number
defaultValue?: string
required?: boolean
id?: string
blockName?: string
blockType: 'textarea'
}
| {
name: string
label?: string
width?: number
defaultValue?: string
options?: {
label: string
value: string
id?: string
}[]
required?: boolean
id?: string
blockName?: string
blockType: 'select'
}
| {
name: string
label?: string
width?: number
required?: boolean
id?: string
blockName?: string
blockType: 'email'
}
| {
name: string
label?: string
width?: number
required?: boolean
id?: string
blockName?: string
blockType: 'state'
}
| {
name: string
label?: string
width?: number
required?: boolean
id?: string
blockName?: string
blockType: 'country'
}
| {
name: string
label?: string
width?: number
defaultValue?: number
required?: boolean
id?: string
blockName?: string
blockType: 'number'
}
| {
name: string
label?: string
width?: number
required?: boolean
defaultValue?: boolean
id?: string
blockName?: string
blockType: 'checkbox'
}
| {
message?: {
[k: string]: unknown
}[]
id?: string
blockName?: string
blockType: 'message'
}
)[]
submitButtonLabel?: string
confirmationType?: 'message' | 'redirect'
confirmationMessage: {
[k: string]: unknown
}[]
redirect?: {
url: string
}
emails?: {
emailTo?: string
cc?: string
bcc?: string
replyTo?: string
emailFrom?: string
subject: string
message?: {
[k: string]: unknown
}[]
id?: 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 FormSubmission {
id: string
form: string | Form
submissionData?: {
field: string
value: string
id?: string
}[]
updatedAt: string
createdAt: 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
}
export interface MainMenu {
id: string
navItems?: {
link: {
type?: 'reference' | 'custom'
newTab?: boolean
reference: {
relationTo: 'pages'
value: string | Page
}
url: string
label: string
}
id?: string
}[]
updatedAt?: string
createdAt?: string
}
declare module 'payload' {
export interface GeneratedTypes {
collections: {
pages: Page
users: User
forms: Form
'form-submissions': FormSubmission
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {
'main-menu': MainMenu
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +0,0 @@
'use client'
import React, { createContext, useContext } from 'react'
import type { MainMenu } from '../../payload-types'
export type MainMenuType = MainMenu
export interface IGlobals {
mainMenu: MainMenuType
}
export const GlobalsContext = createContext<IGlobals>({} as IGlobals)
export const useGlobals = (): IGlobals => useContext(GlobalsContext)
export const GlobalsProvider: React.FC<
IGlobals & {
children: React.ReactNode
}
> = (props) => {
const { children, mainMenu } = props
return (
<GlobalsContext.Provider
value={{
mainMenu,
}}
>
{children}
</GlobalsContext.Provider>
)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1 +0,0 @@
export default !!(typeof window !== 'undefined' && window.document && window.document.createElement)

View File

@@ -1,29 +0,0 @@
module.exports.formatSlug = (reference) => {
let slug = ''
const { relationTo, value } = reference
if (typeof value === 'object' && value !== null) {
const { slug: referenceSlug, breadcrumbs } = value
// pages could be nested, so use breadcrumbs
if (relationTo === 'pages') {
if (breadcrumbs) {
const { url: lastCrumbURL = '' } = breadcrumbs?.[breadcrumbs.length - 1] || {} // last crumb
slug = lastCrumbURL
} else {
slug = referenceSlug
}
}
if (relationTo !== 'pages') {
slug = `/${relationTo}/${referenceSlug}`
if (relationTo === 'media') {
slug = value.url
}
}
}
return slug
}

View File

@@ -1,10 +0,0 @@
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
max_line_length = null

View File

@@ -1 +0,0 @@
NEXT_PUBLIC_PAYLOAD_URL=http://localhost:3000

View File

@@ -1,15 +0,0 @@
module.exports = {
extends: ['plugin:@next/next/core-web-vitals', '@payloadcms'],
ignorePatterns: ['**/payload-types.ts'],
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
],
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
root: true,
}

View File

@@ -1,38 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
.env

View File

@@ -1,38 +0,0 @@
# Form Builder Example Front-End
This is a [Next.js](https://nextjs.org) app using the [Pages Router](https://nextjs.org/docs/pages). It was made explicitly for Payload's [Form Builder Example](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload).
> This example uses the Pages Router, the legacy API of Next.js. If your app is using the latest [App Router](https://nextjs.org/docs/app), we will add an example for that soon.
## Getting Started
### Payload
First you'll need a running Payload app. There is one made explicitly for this example and [can be found here](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload). If you have not done so already, clone it down and follow the setup instructions there.
### Next.js App
1. Clone this repo
2. `cd` into this directory and run `yarn` or `npm install`
3. `cp .env.example .env` to copy the example environment variables
4. `yarn dev` or `npm run dev` to start the server
5. `open http://localhost:3001` to see the result
Once running you will find a couple seeded pages on your local environment with some basic instructions. You can also start editing the pages by modifying the documents within Payload. See the [Form Builder Example](https://github.com/payloadcms/payload/tree/main/examples/form-builder/payload) for full details.
## Learn More
To learn more about Payload and Next.js, take a look at the following resources:
- [Payload Documentation](https://payloadcms.com/docs) - learn about Payload features and API.
- [Form Builder Plugin Documentation](https://github.com/payloadcms/plugin-form-builder) - learn about the plugin's features.
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Payload GitHub repository](https://github.com/payloadcms/payload/) as well as [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Payload deployment documentation](https://payloadcms.com/docs/production/deployment) or the [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View File

@@ -1,69 +0,0 @@
@use '../shared.scss';
.checkbox {
position: relative;
margin-bottom: var(--base);
:global {
button {
border: 0;
background: none;
box-shadow: none;
border-radius: 0;
padding: 0;
display: flex;
align-items: center;
cursor: pointer;
font-size: 1rem;
&:focus,
&:active {
outline: none;
}
&:hover {
svg {
opacity: 0.2;
}
}
}
input {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
}
}
.container {
display: flex;
}
.input {
@include shared.formInput;
padding: 0;
line-height: 0;
position: relative;
width: var(--base);
height: var(--base);
margin-right: calc(var(--base) * 0.5);
margin-bottom: 0;
svg {
opacity: 0;
}
}
.checked {
:global {
svg {
opacity: 1 !important;
}
}
}
.label {
display: block;
}

View File

@@ -1,61 +0,0 @@
import React, { useState } from 'react'
import { CheckboxField } from 'payload-plugin-form-builder/dist/types'
import { UseFormRegister, FieldErrorsImpl, FieldValues } from 'react-hook-form'
import { Check } from '../../../icons/Check'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Checkbox: React.FC<
CheckboxField & {
register: UseFormRegister<FieldValues & any>
setValue: any
getValues: any
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({
name,
label,
width,
register,
setValue,
getValues,
required: requiredFromProps,
errors,
}) => {
const [checked, setChecked] = useState(false)
const isCheckboxChecked = getValues(name)
return (
<Width width={width}>
<div className={[classes.checkbox, checked && classes.checked].filter(Boolean).join(' ')}>
<div className={classes.container}>
<input
type="checkbox"
{...register(name, { required: requiredFromProps })}
checked={isCheckboxChecked}
/>
<button
type="button"
onClick={() => {
setValue(name, !checked)
setChecked(!checked)
}}
>
<span className={classes.input}>
<Check />
</span>
</button>
<span className={classes.label}>{label}</span>
</div>
{requiredFromProps && errors[name] && checked === false && <Error />}
</div>
</Width>
)
}

View File

@@ -1,123 +0,0 @@
@use '../shared.scss';
.select {
position: relative;
margin-bottom: var(--base);
}
.label {
margin-bottom: 10px;
display: block;
}
.reactSelect {
display: flex;
:global {
div.rs__control {
@include shared.formInput;
height: auto;
}
.rs__input-container {
color: var(--color-black);
}
.rs__value-container {
padding: 0;
> * {
margin-top: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
}
}
.rs__single-value {
color: var(--color-black);
}
.rs__indicators {
position: absolute;
top: calc(var(--base) * 0.9);
right: calc(var(--base) * 0.9);
.arrow {
transform: rotate(90deg);
}
}
.rs__indicator {
padding: 0px 4px;
cursor: pointer;
svg path {
fill: var(--color-dark-gray);
}
&:hover {
svg path {
fill: var(--color-dark-gray);
}
}
}
.rs__indicator-separator {
display: none;
}
.rs__menu {
color: var(--color-black);
background-color: var(--color-white);
z-index: 2;
border-radius: 0;
box-shadow: 0 4px 11px hsl(0deg 0% 0% / 10%);
}
.rs__menu-list {
padding: calc(var(--base) / 4) 0;
}
.rs__group-heading {
margin-bottom: calc(var(--base) / 2);
}
.rs__option {
font-size: 1rem;
padding: calc(var(--base) / 2) var(--base);
&--is-focused {
background-color: var(--color-light-gray);
color: var(--color-black);
}
&--is-selected {
background-color: var(--color-light-gray);
color: var(--color-black);
}
}
.rs__multi-value {
padding: 0;
background: var(--color-light-gray);
}
.rs__multi-value__label {
max-width: 150px;
color: var(--color-black);
padding: calc(var(--base) / 8) calc(var(--base) / 4);
}
.rs__multi-value__remove {
cursor: pointer;
&:hover {
color: var(--color-black);
background: var(--color-light-gray);
}
}
.rs__clear-indicator {
cursor: pointer;
}
}
}

View File

@@ -1,48 +0,0 @@
import React from 'react'
import ReactSelect from 'react-select'
import { CountryField } from 'payload-plugin-form-builder/dist/types'
import { Controller, Control, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { countryOptions } from './options'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Country: React.FC<
CountryField & {
control: Control<FieldValues, any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, control, required, errors }) => {
return (
<Width width={width}>
<div className={classes.select}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<Controller
control={control}
rules={{ required }}
name={name}
defaultValue=""
render={({ field: { onChange, value } }) => (
<ReactSelect
instanceId={name}
options={countryOptions}
value={countryOptions.find((c) => c.value === value)}
onChange={(val) => onChange(val.value)}
className={classes.reactSelect}
classNamePrefix="rs"
inputId={name}
/>
)}
/>
{required && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,982 +0,0 @@
export const countryOptions = [
{
label: 'Afghanistan',
value: 'AF',
},
{
label: 'Åland Islands',
value: 'AX',
},
{
label: 'Albania',
value: 'AL',
},
{
label: 'Algeria',
value: 'DZ',
},
{
label: 'American Samoa',
value: 'AS',
},
{
label: 'Andorra',
value: 'AD',
},
{
label: 'Angola',
value: 'AO',
},
{
label: 'Anguilla',
value: 'AI',
},
{
label: 'Antarctica',
value: 'AQ',
},
{
label: 'Antigua and Barbuda',
value: 'AG',
},
{
label: 'Argentina',
value: 'AR',
},
{
label: 'Armenia',
value: 'AM',
},
{
label: 'Aruba',
value: 'AW',
},
{
label: 'Australia',
value: 'AU',
},
{
label: 'Austria',
value: 'AT',
},
{
label: 'Azerbaijan',
value: 'AZ',
},
{
label: 'Bahamas',
value: 'BS',
},
{
label: 'Bahrain',
value: 'BH',
},
{
label: 'Bangladesh',
value: 'BD',
},
{
label: 'Barbados',
value: 'BB',
},
{
label: 'Belarus',
value: 'BY',
},
{
label: 'Belgium',
value: 'BE',
},
{
label: 'Belize',
value: 'BZ',
},
{
label: 'Benin',
value: 'BJ',
},
{
label: 'Bermuda',
value: 'BM',
},
{
label: 'Bhutan',
value: 'BT',
},
{
label: 'Bolivia',
value: 'BO',
},
{
label: 'Bosnia and Herzegovina',
value: 'BA',
},
{
label: 'Botswana',
value: 'BW',
},
{
label: 'Bouvet Island',
value: 'BV',
},
{
label: 'Brazil',
value: 'BR',
},
{
label: 'British Indian Ocean Territory',
value: 'IO',
},
{
label: 'Brunei Darussalam',
value: 'BN',
},
{
label: 'Bulgaria',
value: 'BG',
},
{
label: 'Burkina Faso',
value: 'BF',
},
{
label: 'Burundi',
value: 'BI',
},
{
label: 'Cambodia',
value: 'KH',
},
{
label: 'Cameroon',
value: 'CM',
},
{
label: 'Canada',
value: 'CA',
},
{
label: 'Cape Verde',
value: 'CV',
},
{
label: 'Cayman Islands',
value: 'KY',
},
{
label: 'Central African Republic',
value: 'CF',
},
{
label: 'Chad',
value: 'TD',
},
{
label: 'Chile',
value: 'CL',
},
{
label: 'China',
value: 'CN',
},
{
label: 'Christmas Island',
value: 'CX',
},
{
label: 'Cocos (Keeling) Islands',
value: 'CC',
},
{
label: 'Colombia',
value: 'CO',
},
{
label: 'Comoros',
value: 'KM',
},
{
label: 'Congo',
value: 'CG',
},
{
label: 'Congo, The Democratic Republic of the',
value: 'CD',
},
{
label: 'Cook Islands',
value: 'CK',
},
{
label: 'Costa Rica',
value: 'CR',
},
{
label: "Cote D'Ivoire",
value: 'CI',
},
{
label: 'Croatia',
value: 'HR',
},
{
label: 'Cuba',
value: 'CU',
},
{
label: 'Cyprus',
value: 'CY',
},
{
label: 'Czech Republic',
value: 'CZ',
},
{
label: 'Denmark',
value: 'DK',
},
{
label: 'Djibouti',
value: 'DJ',
},
{
label: 'Dominica',
value: 'DM',
},
{
label: 'Dominican Republic',
value: 'DO',
},
{
label: 'Ecuador',
value: 'EC',
},
{
label: 'Egypt',
value: 'EG',
},
{
label: 'El Salvador',
value: 'SV',
},
{
label: 'Equatorial Guinea',
value: 'GQ',
},
{
label: 'Eritrea',
value: 'ER',
},
{
label: 'Estonia',
value: 'EE',
},
{
label: 'Ethiopia',
value: 'ET',
},
{
label: 'Falkland Islands (Malvinas)',
value: 'FK',
},
{
label: 'Faroe Islands',
value: 'FO',
},
{
label: 'Fiji',
value: 'FJ',
},
{
label: 'Finland',
value: 'FI',
},
{
label: 'France',
value: 'FR',
},
{
label: 'French Guiana',
value: 'GF',
},
{
label: 'French Polynesia',
value: 'PF',
},
{
label: 'French Southern Territories',
value: 'TF',
},
{
label: 'Gabon',
value: 'GA',
},
{
label: 'Gambia',
value: 'GM',
},
{
label: 'Georgia',
value: 'GE',
},
{
label: 'Germany',
value: 'DE',
},
{
label: 'Ghana',
value: 'GH',
},
{
label: 'Gibraltar',
value: 'GI',
},
{
label: 'Greece',
value: 'GR',
},
{
label: 'Greenland',
value: 'GL',
},
{
label: 'Grenada',
value: 'GD',
},
{
label: 'Guadeloupe',
value: 'GP',
},
{
label: 'Guam',
value: 'GU',
},
{
label: 'Guatemala',
value: 'GT',
},
{
label: 'Guernsey',
value: 'GG',
},
{
label: 'Guinea',
value: 'GN',
},
{
label: 'Guinea-Bissau',
value: 'GW',
},
{
label: 'Guyana',
value: 'GY',
},
{
label: 'Haiti',
value: 'HT',
},
{
label: 'Heard Island and Mcdonald Islands',
value: 'HM',
},
{
label: 'Holy See (Vatican City State)',
value: 'VA',
},
{
label: 'Honduras',
value: 'HN',
},
{
label: 'Hong Kong',
value: 'HK',
},
{
label: 'Hungary',
value: 'HU',
},
{
label: 'Iceland',
value: 'IS',
},
{
label: 'India',
value: 'IN',
},
{
label: 'Indonesia',
value: 'ID',
},
{
label: 'Iran, Islamic Republic Of',
value: 'IR',
},
{
label: 'Iraq',
value: 'IQ',
},
{
label: 'Ireland',
value: 'IE',
},
{
label: 'Isle of Man',
value: 'IM',
},
{
label: 'Israel',
value: 'IL',
},
{
label: 'Italy',
value: 'IT',
},
{
label: 'Jamaica',
value: 'JM',
},
{
label: 'Japan',
value: 'JP',
},
{
label: 'Jersey',
value: 'JE',
},
{
label: 'Jordan',
value: 'JO',
},
{
label: 'Kazakhstan',
value: 'KZ',
},
{
label: 'Kenya',
value: 'KE',
},
{
label: 'Kiribati',
value: 'KI',
},
{
label: "Democratic People's Republic of Korea",
value: 'KP',
},
{
label: 'Korea, Republic of',
value: 'KR',
},
{
label: 'Kosovo',
value: 'XK',
},
{
label: 'Kuwait',
value: 'KW',
},
{
label: 'Kyrgyzstan',
value: 'KG',
},
{
label: "Lao People's Democratic Republic",
value: 'LA',
},
{
label: 'Latvia',
value: 'LV',
},
{
label: 'Lebanon',
value: 'LB',
},
{
label: 'Lesotho',
value: 'LS',
},
{
label: 'Liberia',
value: 'LR',
},
{
label: 'Libyan Arab Jamahiriya',
value: 'LY',
},
{
label: 'Liechtenstein',
value: 'LI',
},
{
label: 'Lithuania',
value: 'LT',
},
{
label: 'Luxembourg',
value: 'LU',
},
{
label: 'Macao',
value: 'MO',
},
{
label: 'Macedonia, The Former Yugoslav Republic of',
value: 'MK',
},
{
label: 'Madagascar',
value: 'MG',
},
{
label: 'Malawi',
value: 'MW',
},
{
label: 'Malaysia',
value: 'MY',
},
{
label: 'Maldives',
value: 'MV',
},
{
label: 'Mali',
value: 'ML',
},
{
label: 'Malta',
value: 'MT',
},
{
label: 'Marshall Islands',
value: 'MH',
},
{
label: 'Martinique',
value: 'MQ',
},
{
label: 'Mauritania',
value: 'MR',
},
{
label: 'Mauritius',
value: 'MU',
},
{
label: 'Mayotte',
value: 'YT',
},
{
label: 'Mexico',
value: 'MX',
},
{
label: 'Micronesia, Federated States of',
value: 'FM',
},
{
label: 'Moldova, Republic of',
value: 'MD',
},
{
label: 'Monaco',
value: 'MC',
},
{
label: 'Mongolia',
value: 'MN',
},
{
label: 'Montenegro',
value: 'ME',
},
{
label: 'Montserrat',
value: 'MS',
},
{
label: 'Morocco',
value: 'MA',
},
{
label: 'Mozambique',
value: 'MZ',
},
{
label: 'Myanmar',
value: 'MM',
},
{
label: 'Namibia',
value: 'NA',
},
{
label: 'Nauru',
value: 'NR',
},
{
label: 'Nepal',
value: 'NP',
},
{
label: 'Netherlands',
value: 'NL',
},
{
label: 'Netherlands Antilles',
value: 'AN',
},
{
label: 'New Caledonia',
value: 'NC',
},
{
label: 'New Zealand',
value: 'NZ',
},
{
label: 'Nicaragua',
value: 'NI',
},
{
label: 'Niger',
value: 'NE',
},
{
label: 'Nigeria',
value: 'NG',
},
{
label: 'Niue',
value: 'NU',
},
{
label: 'Norfolk Island',
value: 'NF',
},
{
label: 'Northern Mariana Islands',
value: 'MP',
},
{
label: 'Norway',
value: 'NO',
},
{
label: 'Oman',
value: 'OM',
},
{
label: 'Pakistan',
value: 'PK',
},
{
label: 'Palau',
value: 'PW',
},
{
label: 'Palestinian Territory, Occupied',
value: 'PS',
},
{
label: 'Panama',
value: 'PA',
},
{
label: 'Papua New Guinea',
value: 'PG',
},
{
label: 'Paraguay',
value: 'PY',
},
{
label: 'Peru',
value: 'PE',
},
{
label: 'Philippines',
value: 'PH',
},
{
label: 'Pitcairn',
value: 'PN',
},
{
label: 'Poland',
value: 'PL',
},
{
label: 'Portugal',
value: 'PT',
},
{
label: 'Puerto Rico',
value: 'PR',
},
{
label: 'Qatar',
value: 'QA',
},
{
label: 'Reunion',
value: 'RE',
},
{
label: 'Romania',
value: 'RO',
},
{
label: 'Russian Federation',
value: 'RU',
},
{
label: 'Rwanda',
value: 'RW',
},
{
label: 'Saint Helena',
value: 'SH',
},
{
label: 'Saint Kitts and Nevis',
value: 'KN',
},
{
label: 'Saint Lucia',
value: 'LC',
},
{
label: 'Saint Pierre and Miquelon',
value: 'PM',
},
{
label: 'Saint Vincent and the Grenadines',
value: 'VC',
},
{
label: 'Samoa',
value: 'WS',
},
{
label: 'San Marino',
value: 'SM',
},
{
label: 'Sao Tome and Principe',
value: 'ST',
},
{
label: 'Saudi Arabia',
value: 'SA',
},
{
label: 'Senegal',
value: 'SN',
},
{
label: 'Serbia',
value: 'RS',
},
{
label: 'Seychelles',
value: 'SC',
},
{
label: 'Sierra Leone',
value: 'SL',
},
{
label: 'Singapore',
value: 'SG',
},
{
label: 'Slovakia',
value: 'SK',
},
{
label: 'Slovenia',
value: 'SI',
},
{
label: 'Solomon Islands',
value: 'SB',
},
{
label: 'Somalia',
value: 'SO',
},
{
label: 'South Africa',
value: 'ZA',
},
{
label: 'South Georgia and the South Sandwich Islands',
value: 'GS',
},
{
label: 'Spain',
value: 'ES',
},
{
label: 'Sri Lanka',
value: 'LK',
},
{
label: 'Sudan',
value: 'SD',
},
{
label: 'Suriname',
value: 'SR',
},
{
label: 'Svalbard and Jan Mayen',
value: 'SJ',
},
{
label: 'Swaziland',
value: 'SZ',
},
{
label: 'Sweden',
value: 'SE',
},
{
label: 'Switzerland',
value: 'CH',
},
{
label: 'Syrian Arab Republic',
value: 'SY',
},
{
label: 'Taiwan',
value: 'TW',
},
{
label: 'Tajikistan',
value: 'TJ',
},
{
label: 'Tanzania, United Republic of',
value: 'TZ',
},
{
label: 'Thailand',
value: 'TH',
},
{
label: 'Timor-Leste',
value: 'TL',
},
{
label: 'Togo',
value: 'TG',
},
{
label: 'Tokelau',
value: 'TK',
},
{
label: 'Tonga',
value: 'TO',
},
{
label: 'Trinidad and Tobago',
value: 'TT',
},
{
label: 'Tunisia',
value: 'TN',
},
{
label: 'Turkey',
value: 'TR',
},
{
label: 'Turkmenistan',
value: 'TM',
},
{
label: 'Turks and Caicos Islands',
value: 'TC',
},
{
label: 'Tuvalu',
value: 'TV',
},
{
label: 'Uganda',
value: 'UG',
},
{
label: 'Ukraine',
value: 'UA',
},
{
label: 'United Arab Emirates',
value: 'AE',
},
{
label: 'United Kingdom',
value: 'GB',
},
{
label: 'United States',
value: 'US',
},
{
label: 'United States Minor Outlying Islands',
value: 'UM',
},
{
label: 'Uruguay',
value: 'UY',
},
{
label: 'Uzbekistan',
value: 'UZ',
},
{
label: 'Vanuatu',
value: 'VU',
},
{
label: 'Venezuela',
value: 'VE',
},
{
label: 'Viet Nam',
value: 'VN',
},
{
label: 'Virgin Islands, British',
value: 'VG',
},
{
label: 'Virgin Islands, U.S.',
value: 'VI',
},
{
label: 'Wallis and Futuna',
value: 'WF',
},
{
label: 'Western Sahara',
value: 'EH',
},
{
label: 'Yemen',
value: 'YE',
},
{
label: 'Zambia',
value: 'ZM',
},
{
label: 'Zimbabwe',
value: 'ZW',
},
]

View File

@@ -1,15 +0,0 @@
@use '../shared.scss';
.wrap {
position: relative;
margin-bottom: var(--base);
}
.input {
@include shared.formInput;
}
.label {
margin-bottom: 10px;
display: block;
}

View File

@@ -1,36 +0,0 @@
import React from 'react'
import { EmailField } from 'payload-plugin-form-builder/dist/types'
import { UseFormRegister, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Email: React.FC<
EmailField & {
register: UseFormRegister<FieldValues & any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, width, label, register, required: requiredFromProps, errors }) => {
return (
<Width width={width}>
<div className={classes.wrap}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<input
type="text"
placeholder="Email"
className={classes.input}
id={name}
{...register(name, { required: requiredFromProps, pattern: /^\S+@\S+$/i })}
/>
{requiredFromProps && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,4 +0,0 @@
.error {
margin-top: 5px;
color: var(--color-red);
}

View File

@@ -1,6 +0,0 @@
import * as React from 'react'
import classes from './index.module.scss'
export const Error: React.FC = () => {
return <div className={classes.error}>This field is required</div>
}

View File

@@ -1,9 +0,0 @@
@use '../.../../../../../css/queries.scss' as *;
.message {
margin: var(--base) 0 var(--base) 0;
@include mid-break {
margin: calc(var(--base) * 0.5) 0 calc(var(--base) * 0.5) 0;
}
}

View File

@@ -1,14 +0,0 @@
import React from 'react'
import { MessageField } from 'payload-plugin-form-builder/dist/types'
import RichText from '../../../RichText'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Message: React.FC<MessageField> = ({ message }) => {
return (
<Width width="100">
<RichText content={message} className={classes.message} />
</Width>
)
}

View File

@@ -1,15 +0,0 @@
@use '../shared.scss';
.wrap {
position: relative;
margin-bottom: var(--base);
}
.input {
@include shared.formInput;
}
.label {
margin-bottom: 10px;
display: block;
}

View File

@@ -1,35 +0,0 @@
import React from 'react'
import { TextField } from 'payload-plugin-form-builder/dist/types'
import { UseFormRegister, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Number: React.FC<
TextField & {
register: UseFormRegister<FieldValues & any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, register, required: requiredFromProps, errors }) => {
return (
<Width width={width}>
<div className={classes.wrap}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<input
type="number"
className={classes.input}
id={name}
{...register(name, { required: requiredFromProps })}
/>
{requiredFromProps && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,123 +0,0 @@
@use '../shared.scss';
.select {
position: relative;
margin-bottom: var(--base);
}
.label {
margin-bottom: 10px;
display: block;
}
.reactSelect {
display: flex;
:global {
div.rs__control {
@include shared.formInput;
height: auto;
}
.rs__input-container {
color: var(--color-black);
}
.rs__value-container {
padding: 0;
> * {
margin-top: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
}
}
.rs__single-value {
color: var(--color-black);
}
.rs__indicators {
position: absolute;
top: calc(var(--base) * 0.9);
right: calc(var(--base) * 0.9);
.arrow {
transform: rotate(90deg);
}
}
.rs__indicator {
padding: 0px 4px;
cursor: pointer;
svg path {
fill: var(--color-dark-gray);
}
&:hover {
svg path {
fill: var(--color-dark-gray);
}
}
}
.rs__indicator-separator {
display: none;
}
.rs__menu {
color: var(--color-black);
background-color: var(--color-white);
z-index: 2;
border-radius: 0;
box-shadow: 0 4px 11px hsl(0deg 0% 0% / 10%);
}
.rs__menu-list {
padding: calc(var(--base) / 4) 0;
}
.rs__group-heading {
margin-bottom: calc(var(--base) / 2);
}
.rs__option {
font-size: 1rem;
padding: calc(var(--base) / 2) var(--base);
&--is-focused {
background-color: var(--color-light-gray);
color: var(--color-black);
}
&--is-selected {
background-color: var(--color-light-gray);
color: var(--color-black);
}
}
.rs__multi-value {
padding: 0;
background: var(--color-light-gray);
}
.rs__multi-value__label {
max-width: 150px;
color: var(--color-black);
padding: calc(var(--base) / 8) calc(var(--base) / 4);
}
.rs__multi-value__remove {
cursor: pointer;
&:hover {
color: var(--color-black);
background: var(--color-light-gray);
}
}
.rs__clear-indicator {
cursor: pointer;
}
}
}

View File

@@ -1,47 +0,0 @@
import React from 'react'
import ReactSelect from 'react-select'
import { SelectField } from 'payload-plugin-form-builder/dist/types'
import { Controller, Control, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Select: React.FC<
SelectField & {
control: Control<FieldValues, any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, options, control, required, errors }) => {
return (
<Width width={width}>
<div className={classes.select}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<Controller
control={control}
rules={{ required }}
name={name}
defaultValue=""
render={({ field: { onChange, value } }) => (
<ReactSelect
instanceId={name}
options={options}
value={options.find((s) => s.value === value)}
onChange={(val) => onChange(val.value)}
className={classes.reactSelect}
classNamePrefix="rs"
inputId={name}
/>
)}
/>
{required && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,123 +0,0 @@
@use '../shared.scss';
.select {
position: relative;
margin-bottom: var(--base);
}
.label {
margin-bottom: 10px;
display: block;
}
.reactSelect {
display: flex;
:global {
div.rs__control {
@include shared.formInput;
height: auto;
}
.rs__input-container {
color: var(--color-black);
}
.rs__value-container {
padding: 0;
> * {
margin-top: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
}
}
.rs__single-value {
color: var(--color-black);
}
.rs__indicators {
position: absolute;
top: calc(var(--base) * 0.9);
right: calc(var(--base) * 0.9);
.arrow {
transform: rotate(90deg);
}
}
.rs__indicator {
padding: 0px 4px;
cursor: pointer;
svg path {
fill: var(--color-dark-gray);
}
&:hover {
svg path {
fill: var(--color-dark-gray);
}
}
}
.rs__indicator-separator {
display: none;
}
.rs__menu {
color: var(--color-black);
background-color: var(--color-white);
z-index: 2;
border-radius: 0;
box-shadow: 0 4px 11px hsl(0deg 0% 0% / 10%);
}
.rs__menu-list {
padding: calc(var(--base) / 4) 0;
}
.rs__group-heading {
margin-bottom: calc(var(--base) / 2);
}
.rs__option {
font-size: 1rem;
padding: calc(var(--base) / 2) var(--base);
&--is-focused {
background-color: var(--color-light-gray);
color: var(--color-black);
}
&--is-selected {
background-color: var(--color-light-gray);
color: var(--color-black);
}
}
.rs__multi-value {
padding: 0;
background: var(--color-light-gray);
}
.rs__multi-value__label {
max-width: 150px;
color: var(--color-black);
padding: calc(var(--base) / 8) calc(var(--base) / 4);
}
.rs__multi-value__remove {
cursor: pointer;
&:hover {
color: var(--color-black);
background: var(--color-light-gray);
}
}
.rs__clear-indicator {
cursor: pointer;
}
}
}

View File

@@ -1,48 +0,0 @@
import React from 'react'
import ReactSelect from 'react-select'
import { StateField } from 'payload-plugin-form-builder/dist/types'
import { Controller, Control, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { stateOptions } from './options'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const State: React.FC<
StateField & {
control: Control<FieldValues, any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, control, required, errors }) => {
return (
<Width width={width}>
<div className={classes.select}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<Controller
control={control}
rules={{ required }}
name={name}
defaultValue=""
render={({ field: { onChange, value } }) => (
<ReactSelect
instanceId={name}
options={stateOptions}
value={stateOptions.find((t) => t.value === value)}
onChange={(val) => onChange(val.value)}
className={classes.reactSelect}
classNamePrefix="rs"
id={name}
/>
)}
/>
{required && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,52 +0,0 @@
export const stateOptions = [
{ label: 'Alabama', value: 'AL' },
{ label: 'Alaska', value: 'AK' },
{ label: 'Arizona', value: 'AZ' },
{ label: 'Arkansas', value: 'AR' },
{ label: 'California', value: 'CA' },
{ label: 'Colorado', value: 'CO' },
{ label: 'Connecticut', value: 'CT' },
{ label: 'Delaware', value: 'DE' },
{ label: 'Florida', value: 'FL' },
{ label: 'Georgia', value: 'GA' },
{ label: 'Hawaii', value: 'HI' },
{ label: 'Idaho', value: 'ID' },
{ label: 'Illinois', value: 'IL' },
{ label: 'Indiana', value: 'IN' },
{ label: 'Iowa', value: 'IA' },
{ label: 'Kansas', value: 'KS' },
{ label: 'Kentucky', value: 'KY' },
{ label: 'Louisiana', value: 'LA' },
{ label: 'Maine', value: 'ME' },
{ label: 'Maryland', value: 'MD' },
{ label: 'Massachusetts', value: 'MA' },
{ label: 'Michigan', value: 'MI' },
{ label: 'Minnesota', value: 'MN' },
{ label: 'Mississippi', value: 'MS' },
{ label: 'Missouri', value: 'MO' },
{ label: 'Montana', value: 'MT' },
{ label: 'Nebraska', value: 'NE' },
{ label: 'Nevada', value: 'NV' },
{ label: 'New Hampshire', value: 'NH' },
{ label: 'New Jersey', value: 'NJ' },
{ label: 'New Mexico', value: 'NM' },
{ label: 'New York', value: 'NY' },
{ label: 'North Carolina', value: 'NC' },
{ label: 'North Dakota', value: 'ND' },
{ label: 'Ohio', value: 'OH' },
{ label: 'Oklahoma', value: 'OK' },
{ label: 'Oregon', value: 'OR' },
{ label: 'Pennsylvania', value: 'PA' },
{ label: 'Rhode Island', value: 'RI' },
{ label: 'South Carolina', value: 'SC' },
{ label: 'South Dakota', value: 'SD' },
{ label: 'Tennessee', value: 'TN' },
{ label: 'Texas', value: 'TX' },
{ label: 'Utah', value: 'UT' },
{ label: 'Vermont', value: 'VT' },
{ label: 'Virginia', value: 'VA' },
{ label: 'Washington', value: 'WA' },
{ label: 'West Virginia', value: 'WV' },
{ label: 'Wisconsin', value: 'WI' },
{ label: 'Wyoming', value: 'WY' },
]

View File

@@ -1,15 +0,0 @@
@use '../shared.scss';
.wrap {
position: relative;
margin-bottom: var(--base);
}
.input {
@include shared.formInput;
}
.label {
margin-bottom: 10px;
display: block;
}

View File

@@ -1,35 +0,0 @@
import React from 'react'
import { TextField } from 'payload-plugin-form-builder/dist/types'
import { UseFormRegister, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Text: React.FC<
TextField & {
register: UseFormRegister<FieldValues & any>
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, register, required: requiredFromProps, errors }) => {
return (
<Width width={width}>
<div className={classes.wrap}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<input
type="text"
className={classes.input}
id={name}
{...register(name, { required: requiredFromProps })}
/>
{requiredFromProps && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,16 +0,0 @@
@use '../shared.scss';
.wrap {
position: relative;
margin-bottom: var(--base);
}
.textarea {
@include shared.formInput;
height: unset;
}
.label {
margin-bottom: 10px;
display: block;
}

View File

@@ -1,36 +0,0 @@
import React from 'react'
import { TextField } from 'payload-plugin-form-builder/dist/types'
import { UseFormRegister, FieldValues, FieldErrorsImpl } from 'react-hook-form'
import { Error } from '../Error'
import { Width } from '../Width'
import classes from './index.module.scss'
export const Textarea: React.FC<
TextField & {
register: UseFormRegister<FieldValues & any>
rows?: number
errors: Partial<
FieldErrorsImpl<{
[x: string]: any
}>
>
}
> = ({ name, label, width, rows = 3, register, required: requiredFromProps, errors }) => {
return (
<Width width={width}>
<div className={classes.wrap}>
<label htmlFor={name} className={classes.label}>
{label}
</label>
<textarea
rows={rows}
className={classes.textarea}
id={name}
{...register(name, { required: requiredFromProps })}
/>
{requiredFromProps && errors[name] && <Error />}
</div>
</Width>
)
}

View File

@@ -1,10 +0,0 @@
@use '../../../../css/queries.scss' as *;
.width {
padding-left: calc(var(--base) * 0.5);
padding-right: calc(var(--base) * 0.5);
@include mid-break {
width: 100% !important;
}
}

View File

@@ -1,13 +0,0 @@
import * as React from 'react'
import classes from './index.module.scss'
export const Width: React.FC<{
width?: string
children: React.ReactNode
}> = ({ width, children }) => {
return (
<div className={classes.width} style={{ width: width ? `${width}%` : undefined }}>
{children}
</div>
)
}

View File

@@ -1,21 +0,0 @@
import { Checkbox } from './Checkbox'
import { Country } from './Country'
import { Email } from './Email'
import { Message } from './Message'
import { Number } from './Number'
import { Select } from './Select'
import { State } from './State'
import { Text } from './Text'
import { Textarea } from './Textarea'
export const fields = {
checkbox: Checkbox,
country: Country,
email: Email,
message: Message,
number: Number,
select: Select,
state: State,
text: Text,
textarea: Textarea,
}

View File

@@ -1,69 +0,0 @@
@use '../.../../../../css/queries.scss' as *;
.form {
display: flex;
flex-direction: column;
}
.hasSubmitted {
align-items: center;
justify-content: center;
height: 80vh;
@include small-break {
height: 100%;
}
}
.intro {
margin-bottom: var(--base);
@include mid-break {
margin-bottom: var(--base);
}
}
.confirmationMessage {
max-width: 800px;
text-align: center;
* {
margin: 0;
}
}
.fieldWrap {
position: relative;
z-index: 2;
display: flex;
flex-wrap: wrap;
margin-left: calc(var(--base) * -0.5);
margin-right: calc(var(--base) * -0.5);
width: calc(100% + #{var(--base)});
> * {
width: 100%;
}
}
.Select {
& label {
position: absolute;
top: calc(var(--base) * -0.5);
}
}
.sidebarContent {
@include mid-break {
display: none;
}
}
.mobileSidebar {
display: none;
@include mid-break {
display: block;
margin-bottom: calc(var(--base) * 2);
}
}

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