Compare commits

..

1 Commits

Author SHA1 Message Date
James
ae9ab04064 chore(release): v0.5.6 2021-04-13 13:09:45 -04:00
4713 changed files with 53023 additions and 449785 deletions

View File

@@ -19,11 +19,3 @@ indent_size = 2
[*.mdx]
indent_style = space
indent_size = 2
[*.json]
indent_style = space
indent_size = 2
[*.md]
indent_style = space
indent_size = 2

View File

@@ -1,10 +0,0 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp

View File

@@ -1,38 +1,63 @@
module.exports = {
extends: ['@payloadcms'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
plugins: [
'@typescript-eslint',
],
extends: [
'@trbl',
],
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
},
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
{
files: ['packages/eslint-config-payload/**'],
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
extends: [
'plugin:@typescript-eslint/recommended',
],
rules: {
'perfectionist/sort-objects': 'off',
},
},
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
'import/no-unresolved': [
2,
{
ignore: [
'payload-config',
],
},
],
}
},
],
root: true,
}
rules: {
"import/no-extraneous-dependencies": ["error", { "packageDir": "./" }],
'react/jsx-filename-extension': [2, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }],
'import/prefer-default-export': 'off',
'react/prop-types': 'off',
'react/require-default-props': 'off',
'react/no-unused-prop-types': 'off',
'no-underscore-dangle': 'off',
'import/extensions': [
'error',
'ignorePackages',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never',
},
],
},
};

View File

@@ -1,18 +0,0 @@
# lint and format
ae7d6f97d205491390f15850e5104c7abded1550
1fbda85cd04a774cb978778b0f813001664c53dd
# prettier all templates
75a428ddc4672903455998eaba7ae9f9d710bf85
# re-run prettier and eslint everywhere again
cdaa0acd61d3001407609915bd573b78565d5571
# prettier write again
dfac7395fed95fc5d8ebca21b786ce70821942bb
# lint and format plugin-cloud
fb7d1be2f3325d076b7c967b1730afcef37922c2
# lint and format create-payload-app
5fd3d430001efe86515262ded5e26f00c1451181

50
.github/CODEOWNERS vendored
View File

@@ -1,50 +0,0 @@
# Order matters. The last matching pattern takes precedence.
### Catch-all ###
* @denolfe @jmikrut @DanRibbens
.* @denolfe @jmikrut @DanRibbens
### Core ###
/packages/payload/ @denolfe @jmikrut @DanRibbens
/packages/payload/src/uploads/ @denolfe
/packages/payload/src/admin/ @jmikrut @jacobsfletch @JarrodMFlesch
### Adapters ###
/packages/bundler-*/ @denolfe @jmikrut @DanRibbens @JarrodMFlesch
/packages/db-*/ @denolfe @jmikrut @DanRibbens
/packages/richtext-*/ @denolfe @jmikrut @DanRibbens @AlessioGr
### Plugins ###
/packages/plugin-*/ @denolfe @jmikrut @DanRibbens @jacobsfletch @JarrodMFlesch @AlessioGr
/packages/plugin-cloud*/ @denolfe
/packages/plugin-form-builder/ @jacobsfletch
/packages/plugin-live-preview*/ @jacobsfletch
/packages/plugin-nested-docs/ @jacobsfletch
/packages/plugin-password-protection/ @jmikrut
/packages/plugin-redirects/ @jacobsfletch
/packages/plugin-search/ @jacobsfletch
/packages/plugin-sentry/ @JessChowdhury
/packages/plugin-seo/ @jacobsfletch
/packages/plugin-stripe/ @jacobsfletch
/packages/plugin-zapier/ @JarrodMFlesch
### Examples ###
/examples/ @jacobsfletch
/examples/testing/ @JarrodMFlesch
/examples/email/ @JessChowdhury
/examples/whitelabel/ @JessChowdhury
### Templates ###
/templates/ @jacobsfletch
/templates/blank/ @denolfe
### Misc ###
/packages/create-payload-app/ @denolfe
/packages/eslint-config-payload/ @denolfe
/packages/payload-admin-bar/ @jacobsfletch
### Root ###
/package.json @denolfe
/scripts/ @denolfe
/.github/ @denolfe
/.github/CODEOWNERS @denolfe

View File

@@ -1,47 +0,0 @@
name: Bug Report
description: Create a bug report for Payload
labels: ['possible-bug']
body:
- type: markdown
attributes:
value: |
*Note:* Feature requests should be opened as [discussions](https://github.com/payloadcms/payload/discussions/new?category=feature-requests-ideas).
- type: input
id: reproduction-link
attributes:
label: Link to reproduction
description: Want us to look into your issue faster? Follow the [reproduction-guide](https://github.com/payloadcms/payload/blob/main/.github/reproduction-guide.md) for more information.
validations:
required: false
- type: textarea
attributes:
label: Describe the Bug
validations:
required: true
- type: textarea
attributes:
label: To Reproduce
description: Steps to reproduce the behavior, please provide a clear description of how to reproduce the issue, based on the linked minimal reproduction. Screenshots can be provided in the issue body below. If using code blocks, make sure that [syntax highlighting is correct](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks#syntax-highlighting) and double check that the rendered preview is not broken.
validations:
required: true
- type: input
id: version
attributes:
label: Payload Version
description: What version of Payload are you running?
validations:
required: true
- type: input
id: adapters-plugins
attributes:
label: Adapters and Plugins
description: What adapters and plugins are you using? ie. db-mongodb, db-postgres, bundler-webpack, etc.
- type: markdown
attributes:
value: Before submitting the issue, go through the steps you've written down to make sure the steps provided are detailed and clear.
- type: markdown
attributes:
value: Contributors should be able to follow the steps provided in order to reproduce the bug.
- type: markdown
attributes:
value: These steps are used to add integration tests to ensure the same issue does not happen again. Thanks in advance!

33
.github/ISSUE_TEMPLATE/BUG_REPORT.md vendored Normal file
View File

@@ -0,0 +1,33 @@
---
name: Bug Report
about: Create a bug report for Payload
labels: 'bug'
---
# Bug Report
<!--- Provide a general summary of the issue in the Title above -->
## Expected Behavior
<!--- Tell us what should happen -->
## Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
## Steps to Reproduce
<!--- Steps to reproduce this bug. Include any code, if relevant -->
1.
2.
3.
4.
## Detailed Description
<!--- Provide any other additional details -->
<!--- Payload version, browser, etc -->

View File

@@ -2,18 +2,15 @@
<!-- Please include a summary of the pull request and any related issues it fixes. Please also include relevant motivation and context. -->
- [ ] I have read and understand the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository.
- [ ] I have read and understand the CONTRIBUTING.md document in this repository
## Type of change
<!-- Please delete options that are not relevant. -->
- [ ] Chore (non-breaking change which does not add functionality)
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Change to the [templates](https://github.com/payloadcms/payload/tree/main/templates) directory (does not affect core functionality)
- [ ] Change to the [examples](https://github.com/payloadcms/payload/tree/main/examples) directory (does not affect core functionality)
- [ ] This change requires a documentation update
## Checklist:

View File

@@ -1,64 +0,0 @@
# Reproduction Guide
1. [Fork](https://github.com/payloadcms/payload/fork) this repo
2. Optionally, create a new branch for your reproduction
3. Run `pnpm install` to install dependencies
4. Open up the `test/_community` directory
5. Add any necessary `collections/globals/fields` in this directory to recreate the issue you are experiencing
6. Run `pnpm dev _community` to start the admin panel
**NOTE:** The goal is to isolate the problem by reducing the number of `collections/globals/fields` you add to the `test/_community` folder. This folder is _not_ meant for you to copy your project into, but rather recreate the issue you are experiencing with minimal config.
## Example test directory file tree
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
- `config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
- `int.spec.ts` [Optional] - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
- `e2e.spec.ts` [Optional] - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests.
- `payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types _community`.
The directory split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config. You should modify the files in `test/_community` to get started.
<br />
## Testing is optional but encouraged
An issue does not need to have failing tests — reproduction steps with your forked repo are enough at this point. Some people like to dive deeper and we want to give you the guidance/tools to do so. Read more below:
### Running integration tests (Payload API tests)
First install [Jest Runner for VSVode](https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner).
There are a couple ways run integration tests:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/int-debug.png" />
- **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command:
```bash
pnpm test:int _community
```
### Running E2E tests (Admin Panel UI tests)
The easiest way to run E2E tests is to install
- [Playwright Test for VSCode](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright)
- [Playwright Runner](https://marketplace.visualstudio.com/items?itemName=ortoni.ortoni)
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/e2e-debug.png" />
#### Notes
The default credentials are `dev@payloadcms.com` as email and `test` as password. They can be found in `test/credentials.ts`. By default, these will be autofilled, so no log-in is required.

View File

@@ -1,315 +0,0 @@
name: build
on:
pull_request:
types: [opened, reopened, synchronize]
push:
branches: ['main']
jobs:
changes:
runs-on: ubuntu-latest
permissions:
pull-requests: read
outputs:
needs_build: ${{ steps.filter.outputs.needs_build }}
templates: ${{ steps.filter.outputs.templates }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 25
- uses: dorny/paths-filter@v2
id: filter
with:
filters: |
needs_build:
- '.github/workflows/**'
- 'packages/**'
- 'test/**'
- 'pnpm-lock.yaml'
- 'package.json'
templates:
- 'templates/**'
- name: Log all filter results
run: |
echo "needs_build: ${{ steps.filter.outputs.needs_build }}"
echo "templates: ${{ steps.filter.outputs.templates }}"
core-build:
needs: changes
if: ${{ needs.changes.outputs.needs_build == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 25
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
- run: pnpm install
- run: pnpm run build
- name: Cache build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
tests:
runs-on: ubuntu-latest
needs: core-build
strategy:
fail-fast: false
matrix:
database: [mongoose, postgres]
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: payloadtests
steps:
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Restore build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
- name: Start PostgreSQL
uses: CasperWA/postgresql-action@v1.2
with:
postgresql version: '14' # See https://hub.docker.com/_/postgres for available versions
postgresql db: ${{ env.POSTGRES_DB }}
postgresql user: ${{ env.POSTGRES_USER }}
postgresql password: ${{ env.POSTGRES_PASSWORD }}
if: matrix.database == 'postgres'
- run: sleep 30
- name: Configure PostgreSQL
run: |
psql "postgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@localhost:5432/$POSTGRES_DB" -c "CREATE ROLE runner SUPERUSER LOGIN;"
psql "postgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@localhost:5432/$POSTGRES_DB" -c "SELECT version();"
echo "POSTGRES_URL=postgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@localhost:5432/$POSTGRES_DB" >> $GITHUB_ENV
if: matrix.database == 'postgres'
- name: Component Tests
run: pnpm test:components
- name: Integration Tests
run: pnpm test:int
env:
NODE_OPTIONS: --max-old-space-size=8096
PAYLOAD_DATABASE: ${{ matrix.database }}
POSTGRES_URL: ${{ env.POSTGRES_URL }}
tests-e2e:
runs-on: ubuntu-latest
needs: core-build
strategy:
fail-fast: false
matrix:
part: [1/8, 2/8, 3/8, 4/8, 5/8, 6/8, 7/8, 8/8]
steps:
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Restore build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
- name: E2E Tests
uses: nick-fields/retry@v2
with:
retry_on: error
max_attempts: 2
timeout_minutes: 15
command: pnpm test:e2e --part ${{ matrix.part }} --bail
- uses: actions/upload-artifact@v3
if: always()
with:
name: test-results
path: test-results/
retention-days: 1
tests-type-generation:
runs-on: ubuntu-latest
needs: core-build
steps:
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Restore build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
- name: Generate Payload Types
run: pnpm dev:generate-types fields
- name: Generate GraphQL schema file
run: pnpm dev:generate-graphql-schema graphql-schema-gen
build-packages:
runs-on: ubuntu-latest
needs: core-build
strategy:
fail-fast: false
matrix:
pkg:
- db-mongodb
- db-postgres
- bundler-webpack
- bundler-vite
- richtext-slate
- richtext-lexical
- live-preview
- live-preview-react
steps:
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Restore build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
- name: Build ${{ matrix.pkg }}
run: pnpm turbo run build --filter=${{ matrix.pkg }}
plugins:
runs-on: ubuntu-latest
needs: core-build
strategy:
fail-fast: false
matrix:
pkg:
- create-payload-app
- plugin-cloud
- plugin-cloud-storage
- plugin-form-builder
- plugin-nested-docs
- plugin-search
- plugin-sentry
steps:
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install pnpm
uses: pnpm/action-setup@v2
with:
version: 8
run_install: false
- name: Restore build
uses: actions/cache@v3
with:
path: ./*
key: ${{ github.sha }}-${{ github.run_number }}
- name: Build ${{ matrix.pkg }}
run: pnpm turbo run build --filter=${{ matrix.pkg }}
- name: Test ${{ matrix.pkg }}
run: pnpm --filter ${{ matrix.pkg }} run test
if: matrix.pkg != 'create-payload-app' # degit doesn't work within GitHub Actions
templates:
needs: changes
if: ${{ needs.changes.outputs.templates == 'true' }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
template: [blank, website, ecommerce]
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 25
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
- name: Start MongoDB
uses: supercharge/mongodb-github-action@1.10.0
with:
mongodb-version: 6.0
- name: Build Template
run: |
cd templates/${{ matrix.template }}
cp .env.example .env
yarn install
yarn build
yarn generate:types

37
.github/workflows/tests.yml vendored Normal file
View File

@@ -0,0 +1,37 @@
name: build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 14.x, 15.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
registry-url: https://registry.npmjs.org
scope: '@payloadcms'
always-auth: true
- name: Cache node modules
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- run: yarn
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: yarn build
- run: yarn test:client
- run: yarn test:int # In-memory db + api tests
env:
CI: true

203
.gitignore vendored
View File

@@ -1,19 +1,12 @@
coverage
package-lock.json
dist
/.idea/*
!/.idea/runConfigurations
.idea
test-results
.devcontainer
/migrations
# 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
# Created by https://www.gitignore.io/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
### macOS ###
# General
.DS_Store
*.DS_Store
.AppleDouble
.LSOverride
@@ -36,10 +29,6 @@ Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Node ###
# Logs
logs
@@ -47,11 +36,6 @@ logs
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
@@ -64,12 +48,11 @@ 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 intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
@@ -78,18 +61,15 @@ bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
@@ -97,15 +77,6 @@ web_modules/
# 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
@@ -115,87 +86,25 @@ web_modules/
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
# dotenv environment variables file
.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
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
# 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
# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project
# SFTP configuration file
# sftp configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
@@ -215,53 +124,84 @@ 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 and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-*/
cmake-build-debug/
# File-based project format
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Ruby plugin and RubyMine
/.rakeTasks
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### WebStorm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
@@ -269,13 +209,22 @@ $RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
# End of https://www.gitignore.io/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
/build
# Ignore all uploads
demo/upload
demo/media
demo/files
# Ignore build folder
build
# Ignore built components
components/index.js
components/styles.css

View File

@@ -1,4 +0,0 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm run lint-staged --quiet

View File

@@ -1,5 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Dev Fields" type="NodeJSConfigurationType" application-parameters="fields" path-to-js-file="node_modules/.pnpm/nodemon@3.0.1/node_modules/nodemon/bin/nodemon.js" working-dir="$PROJECT_DIR$">
<method v="2" />
</configuration>
</component>

View File

@@ -1,5 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Dev _community" type="NodeJSConfigurationType" application-parameters="_community" path-to-js-file="node_modules/.pnpm/nodemon@3.0.1/node_modules/nodemon/bin/nodemon.js" working-dir="$PROJECT_DIR$">
<method v="2" />
</configuration>
</component>

View File

@@ -1 +0,0 @@
v18.17.1

2
.npmrc
View File

@@ -1,2 +0,0 @@
symlink=true
node-linker=isolated # due to a typescript bug, isolated mode requires @types/express-serve-static-core, terser and monaco-editor to be installed https://github.com/microsoft/TypeScript/issues/47663#issuecomment-1519138189 along with two other changes in the code which I've marked with (tsbugisolatedmode) in the code

1
.nvmrc
View File

@@ -1 +0,0 @@
v18.17.1

View File

@@ -1,11 +0,0 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp
**/docs/**

View File

@@ -1,6 +0,0 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"semi": false
}

21
.release-it.json Normal file
View File

@@ -0,0 +1,21 @@
{
"git": {
"commitMessage": "chore(release): v${version}",
"requireCleanWorkingDir": true
},
"github": {
"release": true
},
"npm": {
"skipChecks": true
},
"hooks": {
"before:init": ["yarn", "yarn clean", "yarn test"]
},
"plugins": {
"@release-it/conventional-changelog": {
"preset": "angular",
"infile": "CHANGELOG.md"
}
}
}

View File

@@ -1,16 +0,0 @@
module.exports = {
verbose: true,
git: {
requireCleanWorkingDir: false,
commit: false,
push: false,
tag: false,
},
npm: {
skipChecks: true,
tag: 'beta',
},
hooks: {
'before:init': ['pnpm install', 'pnpm clean', 'pnpm build'],
},
}

View File

@@ -1,3 +0,0 @@
{
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
}

215
.vscode/launch.json vendored
View File

@@ -1,184 +1,69 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"command": "pnpm run dev _community",
"cwd": "${workspaceFolder}",
"name": "Run Dev Community",
"name": "Debug Jest Tests",
"type": "node",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run dev plugin-cloud-storage",
"cwd": "${workspaceFolder}",
"name": "Run Dev - plugin-cloud-storage",
"request": "launch",
"type": "node-terminal",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/node_modules/.bin/jest",
"--runInBand"
],
"env": {
"PAYLOAD_PUBLIC_CLOUD_STORAGE_ADAPTER": "s3"
}
},
{
"command": "pnpm run dev fields",
"cwd": "${workspaceFolder}",
"name": "Run Dev Fields",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run dev:postgres fields",
"cwd": "${workspaceFolder}",
"name": "Run Dev Postgres",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run dev versions",
"cwd": "${workspaceFolder}",
"name": "Run Dev Versions",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run dev localization",
"cwd": "${workspaceFolder}",
"name": "Run Dev Localization",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run dev uploads",
"cwd": "${workspaceFolder}",
"name": "Run Dev Uploads",
"request": "launch",
"type": "node-terminal"
},
{
"command": "PAYLOAD_BUNDLER=vite pnpm run dev fields",
"cwd": "${workspaceFolder}",
"name": "Run Dev Fields (Vite)",
"request": "launch",
"type": "node-terminal",
"env": {
"NODE_ENV": "production"
}
},
{
"command": "pnpm run test:int live-preview",
"cwd": "${workspaceFolder}",
"name": "Live Preview Int Tests",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run test:int plugin-search",
"cwd": "${workspaceFolder}",
"name": "Search Plugin Int Tests",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts build",
"env": {
"PAYLOAD_CONFIG_PATH": "test/fields/config.ts",
"PAYLOAD_BUNDLER": "vite",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
"PAYLOAD_CONFIG_PATH": "demo/payload.config.ts"
},
"name": "Build CLI - Vite",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"port": 9229,
"skipFiles": [
"<node_internals>/**"
]
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts build",
"env": {
"PAYLOAD_CONFIG_PATH": "test/fields/config.ts",
"PAYLOAD_ANALYZE_BUNDLE": "true",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
},
"name": "Build CLI - Webpack",
"outputCapture": "std",
"type": "node",
"request": "launch",
"type": "node-terminal"
"name": "Launch Program",
"env": {
"PAYLOAD_CONFIG_PATH": "demo/payload.config.ts",
"BABEL_ENV": "development"
},
"program": "${workspaceFolder}/demo/index.js",
"skipFiles": [
"<node_internals>/**"
],
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
"runtimeArgs": [
"--nolazy"
],
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts generate:types",
"env": {
"PAYLOAD_CONFIG_PATH": "test/_community/config.ts",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
},
"name": "Generate Types CLI",
"outputCapture": "std",
"type": "node",
"request": "launch",
"type": "node-terminal"
"name": "Launch Program - Production",
"env": {
"PAYLOAD_CONFIG_PATH": "demo/payload.config.ts",
"NODE_ENV": "production",
"BABEL_ENV": "development"
},
"program": "${workspaceFolder}/demo/index.js",
"skipFiles": [
"<node_internals>/**"
],
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
"runtimeArgs": [
"--nolazy"
],
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:status",
"env": {
"PAYLOAD_CONFIG_PATH": "test/migrations-cli/config.ts",
"PAYLOAD_DATABASE": "postgres",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
// "PAYLOAD_DROP_DATABASE": "true",
},
"name": "Migrate CLI - status",
"outputCapture": "std",
"type": "chrome",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:create yass",
"env": {
"PAYLOAD_CONFIG_PATH": "test/migrations-cli/config.ts",
"PAYLOAD_DATABASE": "postgres",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
// "PAYLOAD_DROP_DATABASE": "true",
},
"name": "Migrate CLI - create",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:down",
"env": {
"PAYLOAD_CONFIG_PATH": "test/migrations-cli/config.ts",
"PAYLOAD_DATABASE": "mongoose",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
// "PAYLOAD_DROP_DATABASE": "true",
},
"name": "Migrate CLI - down",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:reset",
"env": {
"PAYLOAD_CONFIG_PATH": "test/migrations-cli/config.ts",
"PAYLOAD_DATABASE": "mongoose",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
// "PAYLOAD_DROP_DATABASE": "true",
},
"name": "Migrate CLI - reset",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:refresh",
"env": {
"PAYLOAD_CONFIG_PATH": "test/migrations-cli/config.ts",
"PAYLOAD_DATABASE": "mongoose",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
// "PAYLOAD_DROP_DATABASE": "true",
},
"name": "Migrate CLI - refresh",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
"name": "Launch Chrome against Localhost",
"url": "http://localhost:3000/admin",
"webRoot": "${workspaceFolder}"
}
],
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0"
]
}

39
.vscode/settings.json vendored
View File

@@ -1,39 +0,0 @@
{
"npm.packageManager": "pnpm",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"editor.formatOnSaveMode": "file",
// All ESLint rules to 'warn' to differentate from TypeScript's 'error' level
"eslint.rules.customizations": [{ "rule": "*", "severity": "warn" }],
"typescript.tsdk": "node_modules/typescript/lib",
// Load .git-blame-ignore-revs file
"gitlens.advanced.blame.customArguments": ["--ignore-revs-file", ".git-blame-ignore-revs"]
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,124 +0,0 @@
# Contributing to Payload
Below you'll find a set of guidelines for how to contribute to Payload.
## Opening issues
Before you submit an issue, please check all existing [open and closed issues](https://github.com/payloadcms/payload/issues) to see if your issue has previously been resolved or is already known. If there is already an issue logged, feel free to upvote it by adding a :thumbsup: [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). If you would like to submit a new issue, please fill out our Issue Template to the best of your ability so we can accurately understand your report.
## Security issues & vulnerabilities
If you come across an issue related to security, or a potential attack vector within Payload or one of its dependencies, please DO NOT create a publicly viewable issue. Instead, please contact us directly at [`dev@payloadcms.com`](mailto:dev@payloadcms.com). We will do everything we can to respond to the issue as soon as possible.
If you find a vulnerability within the core Payload repository, and we determine that it is remediable and of significant nature, we will be happy to pay you a reward for your findings and diligence. [`Contact us`](mailto:dev@payloadcms.com) to find out more.
## Documentation edits
Payload documentation can be found directly within its codebase, and you can feel free to make changes / improvements to any of it through opening a PR. We utilize these files directly in our website and will periodically deploy documentation updates as necessary.
## Building additional features
If you're an incredibly awesome person and want to help us make Payload even better through new features or additions, we would be thrilled to work with you.
## Design Contributions
When it comes to design-related changes or additions, it's crucial for us to ensure a cohesive user experience and alignment with our broader design vision. Before embarking on any implementation that would affect the design or UI/UX, we ask that you **first share your design proposal** with us for review and approval.
Our design review ensures that proposed changes fit seamlessly with other components, both existing and planned. This step is meant to prevent unintentional design inconsistencies and to save you from investing time in implementing features that might need significant design alterations later.
### Before Starting
To help us work on new features, you can create a new feature request post in [GitHub Discussion](https://github.com/payloadcms/payload/discussions) or discuss it in our [Discord](https://discord.com/invite/payload). New functionality often has large implications across the entire Payload repo, so it is best to discuss the architecture and approach before starting work on a pull request.
### Installation & Requirements
Payload is structured as a Monorepo, encompassing not only the core Payload platform but also various plugins and packages. To install all required dependencies, you have to run `pnpm install` once in the root directory. **PNPM IS REQUIRED!** Yarn or npm will not work - you will have to use pnpm to develop in the core repository. In most systems, the easiest way to install pnpm is to run `corepack enable` in your terminal.
If you're coming from a very outdated version of payload, it is recommended to nuke the node_modules folder before running pnpm install. On UNIX systems, you can easily do that using the `pnpm clean:unix` command, which will delete all node_modules folders and build artefacts.
It is also recommended to use at least Node v18 or higher. You can check your current node version by typing `node --version` in your terminal. The easiest way to switch between different node versions is to use [nvm](https://github.com/nvm-sh/nvm#intro).
### Code
Most new functionality should keep testing in mind. All top-level directories within the `test/` directory are for testing a specific category: `fields`, `collections`, etc.
If it makes sense to add your feature to an existing test directory, please do so.
A typical directory with `test/` will be structured like this:
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
- `config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
- `int.spec.ts` - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
- `e2e.spec.ts` - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests. These tests are typically only needed if a large change is being made to the Admin UI.
- `payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types my-test-dir`. Replace `my-test-dir` with the name of your testing directory.
Each test directory is split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config.
The following command will start Payload with your config: `pnpm dev my-test-dir`. Example: `pnpm dev fields` for the test/`fields` test suite. This command will start up Payload using your config and refresh a test database on every restart. If you're using VS Code, the most common run configs are automatically added to your editor - you should be able to find them in your VS Code launch tab.
By default, payload will [automatically log you in](https://payloadcms.com/docs/authentication/config#admin-autologin) with the default credentials. To disable that, you can either pass in the --no-auto-login flag (example: `pnpm dev my-test-dir --no-auto-login`) or set the `PAYLOAD_PUBLIC_DISABLE_AUTO_LOGIN` environment variable to `false`.
The default credentials are `dev@payloadcms.com` as E-Mail and `test` as password. These are used in the auto-login.
### Testing with your own MongoDB database
If you wish to use your own MongoDB database for the `test` directory instead of using the in memory database, all you need to do is add the following env vars to the `test/dev.ts` file:
- `process.env.NODE_ENV`
- `process.env.PAYLOAD_TEST_MONGO_URL`
- Simply set `process.env.NODE_ENV` to `test` and set `process.env.PAYLOAD_TEST_MONGO_URL` to your MongoDB URL e.g. `mongodb://127.0.0.1/your-test-db`.
### Using Postgres
If you have postgres installed on your system, you can also run the test suites using postgres. By default, mongodb is used.
To do that, simply set the `PAYLOAD_DATABASE` environment variable to `postgres`.
### Running the e2e and int tests
You can run the entire test suite using `pnpm test`. If you wish to only run e2e tests, you can use `pnpm test:e2e`. If you wish to only run int tests, you can use `pnpm test:int`.
By default, `pnpm test:int` will only run int test against MongoDB. To run int tests against postgres, you can use `pnpm test:int:postgres`. You will have to have postgres installed on your system for this to work.
### Commits
We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for our commit messages. Please follow this format when creating commits. Here are some examples:
- `feat: adds new feature`
- `fix: fixes bug`
- `docs: adds documentation`
- `chore: does chore`
Here's a breakdown of the format. At the top-level, we use the following types to categorize our commits:
- `feat`: new feature that adds functionality. These are automatically added to the changelog when creating new releases.
- `fix`: a fix to an existing feature. These are automatically added to the changelog when creating new releases.
- `docs`: changes to [docs](./docs) only. These do not appear in the changelog.
- `chore`: changes to code that is neither a fix nor a feature (e.g. refactoring, adding tests, etc.). These do not appear in the changelog.
If you are committing to [templates](./templates) or [examples](./examples), use the `chore` type with the proper scope, like this:
- `chore(templates): adds feature to template`
- `chore(examples): fixes bug in example`
## Pull Requests
For all Pull Requests, you should be extremely descriptive about both your problem and proposed solution. If there are any affected open or closed issues, please leave the issue number in your PR message.
## Previewing docs
This is how you can preview changes you made locally to the docs:
1. Clone our [website repository](https://github.com/payloadcms/website)
2. Run `yarn install`
3. Duplicate the `.env.example` file and rename it to `.env`
4. Add a `DOCS_DIR` environment variable to the `.env` file which points to the absolute path of your modified docs folder. For example `DOCS_DIR=/Users/yourname/Documents/GitHub/payload/docs`
5. Run `yarn run fetchDocs:local`. If this was successful, you should see no error messages and the following output: *Docs successfully written to /.../website/src/app/docs.json*. There could be error messages if you have incorrect markdown in your local docs folder. In this case, it will tell you how you can fix it
6. You're done! Now you can start the website locally using `yarn run dev` and preview the docs under [http://localhost:3000/docs/](http://localhost:3000/docs/)

View File

@@ -1,69 +0,0 @@
# Reporting an issue
To report an issue, please follow the steps below:
1. Fork this repository
2. Add necessary collections/globals/fields to the `test/_community` directory to recreate the issue you are experiencing
3. Create an issue and add a link to your forked repo
**The goal is to isolate the problem by reducing the number of fields/collections you add to the test/\_community folder. This folder is not meant for you to copy your project into, but to recreate the issue you are experiencing with minimal config.**
## Test directory file tree explanation
```text
.
├── config.ts
├── int.spec.ts
├── e2e.spec.ts
└── payload-types.ts
```
- `config.ts` - This is the _granular_ Payload config for testing. It should be as lightweight as possible. Reference existing configs for an example
- `int.spec.ts` [Optional] - This is the test file run by jest. Any test file must have a `*int.spec.ts` suffix.
- `e2e.spec.ts` [Optional] - This is the end-to-end test file that will load up the admin UI using the above config and run Playwright tests.
- `payload-types.ts` - Generated types from `config.ts`. Generate this file by running `pnpm dev:generate-types _community`.
The directory split up in this way specifically to reduce friction when creating tests and to add the ability to boot up Payload with that specific config. You should modify the files in `test/_community` to get started.
## How to start test collection admin UI
To start the admin panel so you can manually recreate your issue, you can run the following command:
```bash
# This command will start up Payload using your config
# NOTE: it will wipe the test database on restart
pnpm dev _community
```
## Testing is optional but encouraged
An issue does not need to have failing tests — reproduction steps with your forked repo are enough at this point. Some people like to dive deeper and we want to give you the guidance/tools to do so. Read more below.
### How to run integration tests (Payload API tests)
There are a couple ways to do this:
- **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points.
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/int-debug.png" />
- **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command:
```bash
pnpm test:int _community
```
### How to run E2E tests (Admin Panel UI tests)
The easiest way to run E2E tests is to install
- [Playwright Test for VSCode](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright)
- [Playwright Runner](https://marketplace.visualstudio.com/items?itemName=ortoni.ortoni)
Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts`
<img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/e2e-debug.png" />
#### Notes
- It is recommended to add the test credentials (located in `test/credentials.ts`) to your autofill for `localhost:3000/admin` as this will be required on every nodemon restart. The default credentials are `dev@payloadcms.com` as email and `test` as password.

129
README.md
View File

@@ -1,77 +1,41 @@
<a href="https://payloadcms.com"><img width="100%" src="https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/assets/images/github-banner-alt.jpg?raw=true" alt="Payload headless CMS Admin panel built with React" /></a>
<br />
<br />
<p align="left">
<a href="https://github.com/payloadcms/payload/actions"><img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/payloadcms/payload/main.yml?style=flat-square"></a>
&nbsp;
<a href="https://discord.gg/payload"><img alt="Discord" src="https://img.shields.io/discord/967097582721572934?label=Discord&color=7289da&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>
<h1 align="center">Payload</h1>
<p align="center">A self-hosted, JavaScript headless CMS & application framework built with Express, MongoDB and React.</p>
<p align="center">
<a href="https://github.com/payloadcms/payload/actions">
<img src="https://github.com/payloadcms/payload/workflows/build/badge.svg">
</a>
<a href="https://www.npmjs.com/package/payload">
<img alt="npm" src="https://img.shields.io/npm/v/payload">
</a>
<a href="https://twitter.com/intent/tweet?text=Payload%20-%20A%20self-hosted%2C%20headless%20JavaScript%20CMS%20%26%20application%20framework&url=https%3A%2F%2Fgithub.com%2Fpayloadcms%2Fpayload">
<img alt="Tweet Payload" src="https://img.shields.io/twitter/url/http/shields.io.svg?style=social">
</a>
</p>
<hr/>
<h4>
<a target="_blank" href="https://payloadcms.com/docs/getting-started/what-is-payload" rel="dofollow"><strong>Explore the Docs</strong></a>&nbsp;·&nbsp;<a target="_blank" href="https://payloadcms.com/community-help" rel="dofollow"><strong>Community Help</strong></a>&nbsp;·&nbsp;<a target="_blank" href="https://demo.payloadcms.com/" rel="dofollow"><strong>Try Live Demo</strong></a>&nbsp;·&nbsp;<a target="_blank" href="https://github.com/payloadcms/payload/discussions/1539" rel="dofollow"><strong>Roadmap</strong></a>&nbsp;·&nbsp;<a target="_blank" href="https://www.g2.com/products/payload-cms/reviews#reviews" rel="dofollow"><strong>View G2 Reviews</strong></a>
</h4>
<hr/>
> [!IMPORTANT]
> 🎉 <strong>Payload 2.0 is now available!</strong> Read more in the <a target="_blank" href="https://payloadcms.com/blog/payload-2-0" rel="dofollow"><strong>announcement post</strong></a>.
<a href="https://payloadcms.com">
<img src="https://payloadcms.com/images/og-image.jpg" alt="Payload headless CMS Admin panel built with React" />
</a>
<h3>Benefits over a regular CMS</h3>
<ul>
<li>Dont hit some third-party SaaS API, hit your own API</li>
<li>Use your own database and own your data</li>
<li>It's just Express - do what you want outside of Payload</li>
<li>No need to learn how Payload works - if you know JS, you know Payload</li>
<li>No vendor lock-in</li>
<li>Avoid microservices hell - get everything (even auth) in one place</li>
<li>Never touch ancient WP code again</li>
<li>Build faster, never hit a roadblock</li>
<li>Both admin and backend are 100% extensible</li>
</ul>
### Quick Start
## ☁️ Deploy instantly with Payload Cloud.
Create a cloud account, connect your GitHub, and [deploy in minutes](https://payloadcms.com/new).
## 🚀 Get started by self-hosting completely free, forever.
Before beginning to work with Payload, make sure you have all of the [required software](https://payloadcms.com/docs/getting-started/installation).
```text
npx create-payload-app@latest
```
npx create-payload-app
```
Alternatively, it only takes about five minutes to [create an app from scratch](https://payloadcms.com/docs/getting-started/installation#from-scratch).
## 🖱️ One-click templates
### Documentation
Jumpstart your next project by starting with a pre-made template. These are production-ready, end-to-end solutions designed to get you to market as fast as possible.
Check out the [Payload website](https://payloadcms.com/docs/getting-started/what-is-payload) to find in-depth documentation for everything that Payload offers.
### [🛒 E-Commerce](https://github.com/payloadcms/payload/tree/main/templates/ecommerce)
### Features
Eliminate the need to combine Shopify and a CMS, and instead do it all with Payload + Stripe. Comes with a beautiful, fully functional front-end complete with shopping cart, checkout, orders, and much more.
### [🌐 Website](https://github.com/payloadcms/payload/tree/main/templates/website)
Build any kind of website, blog, or portfolio from small to enterprise. Comes with a beautiful, fully functional front-end complete with posts, projects, comments, and much more.
We're constantly adding more templates to our [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates). If you maintain your own template, consider adding the `payload-template` topic to your GitHub repository for others to find.
- [Official Templates](https://github.com/payloadcms/payload/tree/main/templates)
- [Community Templates](https://github.com/topics/payload-template)
## ✨ Features
- Completely free and open-source
- [GraphQL](https://payloadcms.com/docs/graphql/overview), [REST](https://payloadcms.com/docs/rest-api/overview), and [Local](https://payloadcms.com/docs/local-api/overview) APIs
- [Easily customizable ReactJS Admin](https://payloadcms.com/docs/admin/overview)
- [Fully self-hosted](https://payloadcms.com/docs/production/deployment)
- [Extensible Authentication](https://payloadcms.com/docs/authentication/overview)
- [Local file storage & upload](https://payloadcms.com/docs/upload/overview)
- [Version History and Drafts](https://payloadcms.com/docs/versions/overview)
- [Field-based Localization](https://payloadcms.com/docs/configuration/localization)
- [Block-based Layout Builder](https://payloadcms.com/docs/fields/blocks)
- [Extensible SlateJS rich text editor](https://payloadcms.com/docs/fields/rich-text)
@@ -83,46 +47,31 @@ We're constantly adding more templates to our [Templates Directory](https://gith
- Intensely fast API
- Highly secure thanks to HTTP-only cookies, CSRF protection, and more
<a target="_blank" href="https://github.com/payloadcms/payload/discussions"><strong>Request Feature</strong></a>
### Code-first
## 🗒️ Documentation
If you know JavaScript, you know Payload. Payload is a _code-first_ CMS, which allows us to do a lot of things right:
Check out the [Payload website](https://payloadcms.com/docs/getting-started/what-is-payload) to find in-depth documentation for everything that Payload offers.
- Payload gives you everything you need, but then steps back and lets you build what you want in JavaScript or TypeScript - with no unnecessary complexity brought by GUIs. You'll understand how your CMS works, because you will have written it exactly how you want it.
- Bring your own Express server and do whatever you need on top of Payload. Payload doesn't impose anything on you or your app.
- Completely control the Admin panel by using your own React components. Swap out fields or even entire views with ease.
- Use your data however and wherever you need thanks to auto-generated, yet fully extensible REST, GraphQL and Local Node APIs.
Migrating from v1 to v2? Check out the [2.0 Release Notes](https://github.com/payloadcms/payload/releases/tag/v2.0.0) on how to do it.
### Free forever for personal use and small projects
## 🙋 Contributing
Payload is 100% free for personal projects or small use cases where only one admin user is required. You can also get started without an account whatsoever while running on `localhost`.
If you want to add contributions to this repository, please follow the instructions in [contributing.md](./CONTRIBUTING.md).
## Installation
## 📚 Examples
Before beginning to work with Payload, make sure you have all of the [required software](https://payloadcms.com/docs/getting-started/installation).
The [Examples Directory](./examples) is a great resource for learning how to setup Payload in a variety of different ways, but you can also find great examples in our blog and throughout our social media.
From there, the easiest way to get started with Payload is to use the `create-payload-app` package:
- [Examples Directory](./examples)
- [Payload Blog](https://payloadcms.com/blog)
- [Payload YouTube](https://www.youtube.com/@payloadcms)
```
npx create-payload-app
```
## 🔌 Plugins
Alternatively, it only takes about five minutes to [write out your own app from scratch](https://payloadcms.com/docs/getting-started/installation#from-scratch).
Payload is highly extensible and allows you to install or distribute plugins that add or remove functionality. There are both officially-supported and community-supported plugins available. If you maintain your own plugin, consider adding the `payload-plugin` topic to your GitHub repository for others to find.
## License
- [Official Plugins](https://github.com/orgs/payloadcms/repositories?q=topic%3Apayload-plugin)
- [Community Plugins](https://github.com/topics/payload-plugin)
## 🚨 Need help?
There are lots of good conversations and resources in our Github Discussions board and our Discord Server. If you're struggling with something, chances are, someone's already solved what you're up against. :point_down:
- [GitHub Discussions](https://github.com/payloadcms/payload/discussions)
- [GitHub Issues](https://github.com/payloadcms/payload/issues)
- [Discord](https://t.co/30APlsQUPB)
- [Community Help](https://payloadcms.com/community-help)
## ⭐ Like what we're doing? Give us a star
![payload-github-star](https://cms.payloadcms.com/media/payload-github-star.gif)
## 👏 Thanks to all our contributors
<img align="left" src="https://contributors-img.web.app/image?repo=payloadcms/payload"/>
Find the Payload license [here](https://github.com/payloadcms/payload/blob/master/license.md).

View File

@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
Please report any security issues or concerns to [info@payloadcms.com](mailto:info@payloadcms.com).

1
auth.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
export * from './dist/auth';

1
auth.js Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/auth');

3
babel.config.js Normal file
View File

@@ -0,0 +1,3 @@
const config = require('./src/babel.config');
module.exports = config;

2
bin.js Executable file
View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./dist/bin');

View File

@@ -1,39 +0,0 @@
module.exports = {
// gitRawCommitsOpts: {
// from: 'v2.0.9',
// path: 'packages/payload',
// },
// infile: 'CHANGELOG.md',
options: {
preset: {
name: 'conventionalcommits',
types: [
{ section: 'Features', type: 'feat' },
{ section: 'Features', type: 'feature' },
{ section: 'Bug Fixes', type: 'fix' },
{ section: 'Documentation', type: 'docs' },
],
},
},
// outfile: 'NEW.md',
writerOpts: {
commitGroupsSort: (a, b) => {
const groupOrder = ['Features', 'Bug Fixes', 'Documentation']
return groupOrder.indexOf(a.title) - groupOrder.indexOf(b.title)
},
// Scoped commits at the end, alphabetical sort
commitsSort: (a, b) => {
if (a.scope || b.scope) {
if (!a.scope) return -1
if (!b.scope) return 1
return a.scope === b.scope
? a.subject.localeCompare(b.subject)
: a.scope.localeCompare(b.scope)
}
// Alphabetical sort
return a.subject.localeCompare(b.subject)
},
},
}

19
components/forms.js Normal file
View File

@@ -0,0 +1,19 @@
export {
useForm,
useWatchForm,
useFormSubmitted,
useFormProcessing,
useFormModified,
} from '../dist/admin/components/forms/Form/context';
export { default as useFieldType } from '../dist/admin/components/forms/useFieldType';
export { default as Form } from '../dist/admin/components/forms/Form';
export { default as Text } from '../dist/admin/components/forms/field-types/Text';
export { default as Group } from '../dist/admin/components/forms/field-types/Group';
export { default as Select } from '../dist/admin/components/forms/field-types/Select';
export { default as Checkbox } from '../dist/admin/components/forms/field-types/Checkbox';
export { default as Submit } from '../dist/admin/components/forms/Submit';
export { default as reduceFieldsToValues } from '../dist/admin/components/forms/Form/reduceFieldsToValues';

3
components/rich-text.js Normal file
View File

@@ -0,0 +1,3 @@
export { default as LeafButton } from '../dist/admin/components/forms/field-types/RichText/leaves/Button';
export { default as ElementButton } from '../dist/admin/components/forms/field-types/RichText/elements/Button';
export { default as toggleElement } from '../dist/admin/components/forms/field-types/RichText/elements/toggle';

2
components/views.js Normal file
View File

@@ -0,0 +1,2 @@
export { default as Edit } from '../dist/admin/components/views/collections/Edit/Default';
export { default as List } from '../dist/admin/components/views/collections/List/Default';

2
config.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
export { buildConfig } from './dist/config/build';
export * from './dist/config/types';

1
config.js Normal file
View File

@@ -0,0 +1 @@
exports.buildConfig = require('./dist/config/build').buildConfig;

33
contributing.md Normal file
View File

@@ -0,0 +1,33 @@
# Contributing to Payload CMS
Below you'll find a set of guidelines for how to contribute to Payload CMS.
## Payload is proprietary software
Even though you can read Payload's source code, it's technically not "open source". Payload requires an active license to be used in all production purposes. That said, we do not expect PRs from the public, but we still welcome pull requests of any kind.
## Opening issues
Before you submit an issue, please check all existing [open and closed issues](https://github.com/payloadcms/payload/issues) to see if your issue has previously been resolved or is already known. If there is already an issue logged, feel free to upvote it by adding a :thumbsup: [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). If you would like to submit a new issue, please fill out our Issue Template to the best of your ability so we can accurately understand your report.
## Security issues & vulnerabilities
If you come across an issue related to security, or a potential attack vector within Payload or one of its dependencies, please DO NOT create a publicly viewable issue. Instead, please contact us directly at [`dev@payloadcms.com`](mailto:dev@payloadcms.com). We will do everything we can to respond to the issue as soon as possible.
If you find a vulnerability within the core Payload repository, and we determine that it is remediable and of significant nature, we will be happy to pay you a reward for your findings and diligence. [`Contact us`](mailto:dev@payloadcms.com) to find out more.
## Documentation edits
Payload documentation can be found directly within its codebase and you can feel free to make changes / improvements to any of it through opening a PR. We utilize these files directly in our website and will periodically deploy documentation updates as necessary.
## Building additional features
If you're an incredibly awesome person and want to help us make Payload even better through new features or additions, we would be thrilled to work with you. If your proposed feature is accepted by our team and is significant enough, pending our discretion, we'd be happy to hook you up with a pro-bono license.
To help us work on new features, you can reach out to our Development team at [`dev@payloadcms.com`](mailto:dev@payloadcms.com). Be as complete and descriptive as possible regarding your vision and we'll go from there!
## Pull Requests
For all Pull Requests, you should be extremely descriptive about both your problem and proposed solution. If there are any affected open or closed issues, please leave the issue number in your PR message.
By opening a Pull Request against Payload's codebase, you automatically give the entirety of the contribution within your PR to Payload CMS, LLC and retain no personal ownership whatsoever afterward. For more information, please read the full [Payload license](https://github.com/payloadcms/payload/blob/master/license.md).

17
demo/access/checkRole.ts Normal file
View File

@@ -0,0 +1,17 @@
/**
* authorize a request by comparing the current user with one or more roles
* @param allRoles
* @param user
* @returns {Function}
*/
const checkRole = (allRoles, user) => {
if (user) {
if (allRoles.some((role) => user.roles && user.roles.some((individualRole) => individualRole === role))) {
return true;
}
}
return false;
};
export default checkRole;

7
demo/access/roles.ts Normal file
View File

@@ -0,0 +1,7 @@
export default [
'admin',
'editor',
'moderator',
'user',
'viewer',
];

View File

@@ -0,0 +1,26 @@
import { Block } from '../../src/fields/config/types';
const CTA: Block = {
slug: 'cta',
labels: {
singular: 'Call to Action',
plural: 'Calls to Action',
},
fields: [
{
name: 'label',
label: 'Label',
type: 'text',
maxLength: 100,
required: true,
},
{
name: 'url',
label: 'URL',
type: 'text',
required: true,
},
],
};
export default CTA;

19
demo/blocks/Email.ts Normal file
View File

@@ -0,0 +1,19 @@
import { Block } from '../../src/fields/config/types';
const Email: Block = {
slug: 'email',
labels: {
singular: 'Email',
plural: 'Emails',
},
fields: [
{
name: 'testEmail',
label: 'Test Email Field',
type: 'email',
required: true,
},
],
};
export default Email;

20
demo/blocks/Number.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Block } from '../../src/fields/config/types';
const NumberBlock: Block = {
slug: 'number',
labels: {
singular: 'Number',
plural: 'Numbers',
},
fields: [
{
name: 'testNumber',
label: 'Test Number Field',
type: 'number',
max: 100,
required: true,
},
],
};
export default NumberBlock;

34
demo/blocks/Quote.ts Normal file
View File

@@ -0,0 +1,34 @@
import { Block } from '../../src/fields/config/types';
const Quote: Block = {
imageURL: '/static/assets/images/generic-block-image.svg',
slug: 'quote',
labels: {
singular: 'Quote',
plural: 'Quotes',
},
fields: [
{
name: 'author',
label: 'Author',
type: 'relationship',
relationTo: 'public-users',
required: true,
},
{
name: 'quote',
label: 'Quote',
type: 'textarea',
required: true,
},
{
name: 'color',
label: 'Color',
type: 'text',
maxLength: 7,
required: true,
},
],
};
export default Quote;

View File

@@ -0,0 +1,33 @@
@import '../../../../../../../scss/vars.scss';
.button-rich-text-button {
.btn {
margin-right: base(1);
}
&__modal {
display: flex;
align-items: center;
height: 100%;
&.payload__modal-item--enterDone {
@include blur-bg;
}
}
&__header {
width: 100%;
margin-bottom: $baseline;
display: flex;
justify-content: space-between;
h3 {
margin: 0;
}
svg {
width: base(1.5);
height: base(1.5);
}
}
}

View File

@@ -0,0 +1,124 @@
import React, { Fragment, useCallback } from 'react';
import { Modal, useModal } from '@faceless-ui/modal';
import { Transforms } from 'slate';
import { useSlate, ReactEditor } from 'slate-react';
import MinimalTemplate from '../../../../../../../src/admin/components/templates/Minimal';
import { ElementButton } from '../../../../../../../components/rich-text';
import X from '../../../../../../../src/admin/components/icons/X';
import Button from '../../../../../../../src/admin/components/elements/Button';
import { Form, Text, Checkbox, Select, Submit, reduceFieldsToValues } from '../../../../../../../components/forms';
import './index.scss';
const baseClass = 'button-rich-text-button';
const initialFormData = {
style: 'primary',
};
const insertButton = (editor, { href, label, style, newTab = false }: any) => {
const text = { text: ' ' };
const button = {
type: 'button',
href,
style,
newTab,
label,
children: [
text,
],
};
const nodes = [button, { children: [{ text: '' }] }];
if (editor.blurSelection) {
Transforms.select(editor, editor.blurSelection);
}
Transforms.insertNodes(editor, nodes);
const currentPath = editor.selection.anchor.path[0];
const newSelection = { anchor: { path: [currentPath + 1, 0], offset: 0 }, focus: { path: [currentPath + 1, 0], offset: 0 } };
Transforms.select(editor, newSelection);
ReactEditor.focus(editor);
};
const ToolbarButton: React.FC<{path: string}> = ({ path }) => {
const { open, closeAll } = useModal();
const editor = useSlate();
const handleAddButton = useCallback((fields) => {
const data = reduceFieldsToValues(fields);
insertButton(editor, data);
closeAll();
}, [editor, closeAll]);
const modalSlug = `${path}-add-button`;
return (
<Fragment>
<ElementButton
className={baseClass}
format="button"
onClick={() => open(modalSlug)}
>
Button
</ElementButton>
<Modal
slug={modalSlug}
className={`${baseClass}__modal`}
>
<MinimalTemplate>
<header className={`${baseClass}__header`}>
<h3>Add button</h3>
<Button
buttonStyle="none"
onClick={closeAll}
>
<X />
</Button>
</header>
<Form
onSubmit={handleAddButton}
initialData={initialFormData}
>
<Text
label="Label"
name="label"
required
/>
<Text
label="URL"
name="href"
required
/>
<Select
label="Style"
name="style"
options={[
{
label: 'Primary',
value: 'primary',
},
{
label: 'Secondary',
value: 'secondary',
},
]}
/>
<Checkbox
label="Open in new tab"
name="newTab"
/>
<Submit>
Add button
</Submit>
</Form>
</MinimalTemplate>
</Modal>
</Fragment>
);
};
export default ToolbarButton;

View File

@@ -0,0 +1,19 @@
@import '../../../../../../../scss/vars.scss';
.rich-text-button {
margin: $baseline 0;
}
.rich-text-button__button {
padding: base(.5) base(1.5);
border-radius: $style-radius-s;
&--primary {
background-color: $color-dark-gray;
color: white;
}
&--secondary {
background-color: $color-light-gray;
}
}

View File

@@ -0,0 +1,44 @@
import React from 'react';
import PropTypes from 'prop-types';
import './index.scss';
const baseClass = 'rich-text-button';
const ButtonElement: React.FC = ({ attributes, children, element }) => {
const { style = 'primary', label } = element;
return (
<div
className={baseClass}
contentEditable={false}
>
<span
{...attributes}
className={[
`${baseClass}__button`,
`${baseClass}__button--${style}`,
].join(' ')}
>
{label}
{children}
</span>
</div>
);
};
ButtonElement.defaultProps = {
attributes: {},
children: null,
};
ButtonElement.propTypes = {
attributes: PropTypes.shape({}),
children: PropTypes.node,
element: PropTypes.shape({
style: PropTypes.oneOf(['primary', 'secondary']),
label: PropTypes.string,
}).isRequired,
};
export default ButtonElement;

View File

@@ -0,0 +1,12 @@
import Button from './Button';
import Element from './Element';
import plugin from './plugin';
export default {
name: 'button',
Button,
Element,
plugins: [
plugin,
],
};

View File

@@ -0,0 +1,12 @@
import { Editor } from 'slate';
const withButton = (incomingEditor: Editor): Editor => {
const editor = incomingEditor;
const { isVoid } = editor;
editor.isVoid = (element) => (element.type === 'button' ? true : isVoid(element));
return editor;
};
export default withButton;

View File

@@ -0,0 +1,10 @@
import React from 'react';
import { LeafButton } from '../../../../../../../components/rich-text';
const Button = () => (
<LeafButton format="purple-background">
Purple Background
</LeafButton>
);
export default Button;

View File

@@ -0,0 +1,23 @@
import React from 'react';
import PropTypes from 'prop-types';
const PurpleBackground: React.FC<any> = ({ attributes, children }) => (
<span
{...attributes}
style={{ backgroundColor: 'purple' }}
>
{children}
</span>
);
PurpleBackground.defaultProps = {
attributes: {},
children: null,
};
PurpleBackground.propTypes = {
attributes: PropTypes.shape({}),
children: PropTypes.node,
};
export default PurpleBackground;

View File

@@ -0,0 +1,8 @@
import Button from './Button';
import Leaf from './Leaf';
export default {
name: 'purple-background',
Button,
Leaf,
};

14
demo/client/index.html Normal file
View File

@@ -0,0 +1,14 @@
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div id="app"></div>
<div id="portal"></div>
</body>
</html>

View File

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

73
demo/collections/Admin.ts Normal file
View File

@@ -0,0 +1,73 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import roles from '../access/roles';
import checkRole from '../access/checkRole';
const access = ({ req: { user } }) => {
const result = checkRole(['admin'], user);
return result;
};
const Admin: PayloadCollectionConfig = {
slug: 'admins',
labels: {
singular: 'Admin',
plural: 'Admins',
},
access: {
create: access,
read: access,
update: access,
delete: access,
admin: () => true,
},
auth: {
tokenExpiration: 7200, // 2 hours
verify: false,
maxLoginAttempts: 5,
lockTime: 600 * 1000, // lock time in ms
useAPIKey: true,
depth: 0,
cookies: {
secure: false,
sameSite: 'lax',
domain: undefined,
},
},
fields: [
{
name: 'roles',
label: 'Role',
type: 'select',
options: roles,
defaultValue: 'user',
required: true,
saveToJWT: true,
hasMany: true,
},
{
name: 'apiKey',
type: 'text',
access: {
read: ({ req: { user } }) => {
if (checkRole(['admin'], user)) {
return true;
}
if (user) {
return {
email: user.email,
};
}
return false;
},
},
},
],
timestamps: true,
admin: {
useAsTitle: 'email',
},
};
export default Admin;

View File

@@ -0,0 +1,305 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import checkRole from '../access/checkRole';
import Email from '../blocks/Email';
import Quote from '../blocks/Quote';
import NumberBlock from '../blocks/Number';
import CallToAction from '../blocks/CallToAction';
const AllFields: PayloadCollectionConfig = {
slug: 'all-fields',
labels: {
singular: 'All Fields',
plural: 'All Fields',
},
admin: {
useAsTitle: 'text',
preview: (doc, token) => {
if (doc && doc.text) {
return `http://localhost:3000/previewable-posts/${doc.text}?preview=true&token=${token}`;
}
return null;
},
},
access: {
read: () => true,
},
fields: [
{
name: 'text',
type: 'text',
label: 'Text',
required: true,
defaultValue: 'Default Value',
unique: true,
access: {
create: ({ req: { user } }) => checkRole(['admin'], user),
update: ({ req: { user } }) => checkRole(['admin'], user),
read: ({ req: { user } }) => Boolean(user),
},
},
{
name: 'image',
type: 'upload',
label: 'Image',
relationTo: 'media',
},
{
name: 'select',
label: 'Select',
type: 'select',
options: [{
value: 'option-1',
label: 'Option 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}, {
value: 'option-4',
label: 'Option 4 Label',
}],
defaultValue: 'option-1',
required: true,
},
{
name: 'selectMany',
label: 'Select w/ hasMany',
type: 'select',
options: [{
value: 'option-1',
label: 'Option 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}, {
value: 'option-4',
label: 'Option 4 Label',
}],
defaultValue: 'option-1',
required: true,
hasMany: true,
},
{
name: 'dateFieldExample',
label: 'Day and Time',
type: 'date',
admin: {
date: {
timeIntervals: 30,
},
},
},
{
name: 'dayOnlyDateFieldExample',
label: 'Day Only',
type: 'date',
admin: {
date: {
pickerAppearance: 'dayOnly',
monthsToShow: 2,
},
},
},
{
name: 'timeOnlyDateFieldExample',
label: 'Time Only',
type: 'date',
admin: {
date: {
pickerAppearance: 'timeOnly',
},
},
},
{
name: 'radioGroupExample',
label: 'Radio Group Example',
type: 'radio',
options: [{
value: 'option-1',
label: 'Options 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}],
defaultValue: 'option-2',
required: true,
admin: {
readOnly: true,
},
},
{
type: 'row',
fields: [
{
name: 'email',
label: 'Email',
type: 'email',
}, {
name: 'number',
label: 'Number',
type: 'number',
},
],
},
{
type: 'group',
label: 'Group',
name: 'group',
fields: [
{
type: 'row',
fields: [
{
name: 'nestedText1',
label: 'Nested Text 1',
type: 'text',
}, {
name: 'nestedText2',
label: 'Nested Text 2',
type: 'text',
},
],
},
],
},
{
type: 'array',
label: 'Array',
name: 'array',
minRows: 2,
maxRows: 4,
fields: [
{
type: 'row',
fields: [
{
name: 'arrayText1',
label: 'Array Text 1',
type: 'text',
required: true,
admin: {
width: '50%',
},
},
{
name: 'arrayText2',
label: 'Array Text 2',
type: 'text',
required: true,
admin: {
width: '50%',
},
access: {
read: ({ req: { user } }) => Boolean(user),
update: ({ req: { user } }) => checkRole(['admin'], user),
},
},
],
},
{
type: 'text',
name: 'arrayText3',
label: 'Array Text 3',
admin: {
readOnly: true,
},
},
{
name: 'checkbox',
label: 'Checkbox',
type: 'checkbox',
},
],
},
{
type: 'blocks',
label: 'Blocks Content',
name: 'blocks',
minRows: 2,
blocks: [Email, NumberBlock, Quote, CallToAction],
localized: true,
required: true,
},
{
type: 'relationship',
label: 'Relationship to One Collection',
name: 'relationship',
relationTo: 'conditions',
},
{
type: 'relationship',
label: 'Relationship hasMany',
name: 'relationshipHasMany',
relationTo: 'localized-posts',
hasMany: true,
},
{
type: 'relationship',
label: 'Relationship to Multiple Collections',
name: 'relationshipMultipleCollections',
relationTo: ['localized-posts', 'conditions'],
},
{
type: 'textarea',
label: 'Textarea',
name: 'textarea',
},
{
name: 'slug',
type: 'text',
label: 'Slug',
admin: {
position: 'sidebar',
},
localized: true,
unique: true,
required: true,
},
{
name: 'checkbox',
type: 'checkbox',
label: 'Checkbox',
admin: {
position: 'sidebar',
},
},
{
name: 'richText',
type: 'richText',
label: 'Rich Text',
required: true,
admin: {
elements: [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'ul',
'ol',
'link',
],
leaves: [
'bold',
'italic',
'underline',
'strikethrough',
],
},
},
],
timestamps: true,
};
export default AllFields;

View File

@@ -0,0 +1,12 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const AutoLabel: PayloadCollectionConfig = {
slug: 'auto-label',
fields: [{
name: 'text',
type: 'text',
label: 'Text',
}],
};
export default AutoLabel;

View File

@@ -0,0 +1,43 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import Email from '../blocks/Email';
import Quote from '../blocks/Quote';
import NumberBlock from '../blocks/Number';
import CallToAction from '../blocks/CallToAction';
const Blocks: PayloadCollectionConfig = {
slug: 'blocks',
labels: {
singular: 'Blocks',
plural: 'Blocks',
},
access: {
read: () => true,
},
fields: [
{
name: 'layout',
label: 'Layout Blocks',
labels: {
singular: 'Block',
plural: 'Blocks',
},
type: 'blocks',
blocks: [Email, NumberBlock, Quote, CallToAction],
localized: true,
required: true,
},
{
name: 'nonLocalizedLayout',
label: 'Non Localized Layout',
labels: {
singular: 'Layout',
plural: 'Layouts',
},
type: 'blocks',
blocks: [Email, NumberBlock, Quote, CallToAction],
required: true,
},
],
};
export default Blocks;

22
demo/collections/Code.ts Normal file
View File

@@ -0,0 +1,22 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Code: PayloadCollectionConfig = {
slug: 'code',
labels: {
singular: 'Code',
plural: 'Codes',
},
fields: [
{
name: 'code',
type: 'code',
label: 'Code',
required: true,
admin: {
language: 'js',
},
},
],
};
export default Code;

View File

@@ -0,0 +1,73 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import Email from '../blocks/Email';
import Quote from '../blocks/Quote';
import NumberBlock from '../blocks/Number';
import CallToAction from '../blocks/CallToAction';
const Conditions: PayloadCollectionConfig = {
slug: 'conditions',
labels: {
singular: 'Conditions',
plural: 'Conditions',
},
fields: [
{
name: 'title',
type: 'text',
label: 'Title',
required: true,
},
{
name: 'enableTest',
type: 'checkbox',
label: 'Enable Test',
},
{
name: 'number',
type: 'number',
label: 'Number Field',
},
{
name: 'simpleCondition',
type: 'text',
label: 'Enable Test is checked',
required: true,
admin: {
condition: (_, siblings) => siblings.enableTest === true,
},
},
{
name: 'orCondition',
type: 'text',
label: 'Number is greater than 20 OR enableTest is checked',
required: true,
admin: {
condition: (_, siblings) => siblings.number > 20 || siblings.enableTest === true,
},
},
{
name: 'nestedConditions',
type: 'text',
label: 'Number is either greater than 20 AND enableTest is checked, OR number is less than 20 and enableTest is NOT checked',
admin: {
condition: (_, siblings) => (siblings.number > 20 && siblings.enableTest === true) || (siblings.number < 20 && siblings.enableTest === false),
},
},
{
name: 'blocks',
label: 'Blocks',
labels: {
singular: 'Block',
plural: 'Blocks',
},
type: 'blocks',
blocks: [Email, NumberBlock, Quote, CallToAction],
required: true,
admin: {
condition: (_, siblings) => siblings?.enableTest === true,
},
},
],
};
export default Conditions;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const Cell: React.FC = () => <div className="description">fake description cell</div>;
export default Cell;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const Description: React.FC = () => <div className="description">fake description field</div>;
export default Description;

View File

@@ -0,0 +1,3 @@
.custom-description-filter {
background: lightgray;
}

View File

@@ -0,0 +1,15 @@
import React from 'react';
import { Props } from './types';
import './index.scss';
const Filter: React.FC<Props> = ({ onChange, value }) => (
<input
className="custom-description-filter"
type="text"
onChange={(e) => onChange(e.target.value)}
value={value}
/>
);
export default Filter;

View File

@@ -0,0 +1,4 @@
export type Props = {
value?: string
onChange?: (value: string) => void
}

View File

@@ -0,0 +1,19 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Group } from '../../../../../../../components/forms';
const CustomGroup: React.FC = (props) => (
<div className="custom-group">
<Group {...props} />
</div>
);
CustomGroup.defaultProps = {
value: '',
};
CustomGroup.propTypes = {
value: PropTypes.string,
};
export default CustomGroup;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const NestedArrayCustomField = () => <div className="nested-array-custom-field">Nested array custom field</div>;
export default NestedArrayCustomField;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const NestedGroupCustomField = () => <div className="nested-group-custom-field">Nested group custom field</div>;
export default NestedGroupCustomField;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const NestedText1 = () => <div className="nested-text-1">Nested Text 1</div>;
export default NestedText1;

View File

@@ -0,0 +1,5 @@
$color: purple;
.custom-list {
color: $color;
}

View File

@@ -0,0 +1,14 @@
import React from 'react';
import DefaultList from '../../../../../../src/admin/components/views/collections/List/Default';
import './index.scss';
const CustomListView: React.FC = (props) => (
<div className="custom-list">
<p>This is a custom Pages list view</p>
<p>Sup</p>
<DefaultList {...props} />
</div>
);
export default CustomListView;

View File

@@ -0,0 +1,111 @@
import { PayloadCollectionConfig } from '../../../src/collections/config/types';
import DescriptionField from './components/fields/Description/Field';
import DescriptionCell from './components/fields/Description/Cell';
import DescriptionFilter from './components/fields/Description/Filter';
import NestedArrayField from './components/fields/NestedArrayCustomField/Field';
import GroupField from './components/fields/Group/Field';
import NestedGroupField from './components/fields/NestedGroupCustomField/Field';
import NestedText1Field from './components/fields/NestedText1/Field';
import ListView from './components/views/List';
const CustomComponents: PayloadCollectionConfig = {
slug: 'custom-components',
labels: {
singular: 'Custom Component',
plural: 'Custom Components',
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
maxLength: 100,
required: true,
unique: true,
localized: true,
},
{
name: 'description',
label: 'Description',
type: 'textarea',
required: true,
localized: true,
admin: {
components: {
Field: DescriptionField,
Cell: DescriptionCell,
Filter: DescriptionFilter,
},
},
},
{
name: 'array',
label: 'Array',
type: 'array',
fields: [
{
type: 'text',
name: 'nestedArrayCustomField',
label: 'Nested Array Custom Field',
admin: {
components: {
Field: NestedArrayField,
},
},
},
],
},
{
name: 'group',
label: 'Group',
type: 'group',
admin: {
components: {
Field: GroupField,
},
},
fields: [
{
type: 'text',
name: 'nestedGroupCustomField',
label: 'Nested Group Custom Field',
admin: {
components: {
Field: NestedGroupField,
},
},
},
],
},
{
type: 'row',
fields: [
{
name: 'nestedText1',
label: 'Nested Text 1',
type: 'text',
admin: {
components: {
Field: NestedText1Field,
},
},
}, {
name: 'nestedText2',
label: 'Nested Text 2',
type: 'text',
},
],
},
],
timestamps: true,
admin: {
useAsTitle: 'title',
components: {
views: {
List: ListView,
},
},
},
};
export default CustomComponents;

View File

@@ -0,0 +1,287 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import checkRole from '../access/checkRole';
import Email from '../blocks/Email';
import Quote from '../blocks/Quote';
import NumberBlock from '../blocks/Number';
import CallToAction from '../blocks/CallToAction';
const DefaultValues: PayloadCollectionConfig = {
slug: 'default-values',
labels: {
singular: 'Default Value Test',
plural: 'Default Value Tests',
},
admin: {
useAsTitle: 'text',
},
access: {
read: () => true,
},
fields: [
{
name: 'text',
type: 'text',
label: 'Text',
defaultValue: 'Default Value',
unique: true,
access: {
create: ({ req: { user } }) => checkRole(['admin'], user),
update: ({ req: { user } }) => checkRole(['admin'], user),
read: ({ req: { user } }) => Boolean(user),
},
},
{
name: 'image',
type: 'upload',
label: 'Image',
relationTo: 'media',
},
{
name: 'select',
label: 'Select',
type: 'select',
options: [{
value: 'option-1',
label: 'Option 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}, {
value: 'option-4',
label: 'Option 4 Label',
}],
defaultValue: 'option-1',
},
{
name: 'selectMany',
label: 'Select w/ hasMany',
type: 'select',
options: [{
value: 'option-1',
label: 'Option 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}, {
value: 'option-4',
label: 'Option 4 Label',
}],
defaultValue: ['option-1', 'option-4'],
hasMany: true,
},
{
name: 'radioGroupExample',
label: 'Radio Group Example',
type: 'radio',
options: [{
value: 'option-1',
label: 'Options 1 Label',
}, {
value: 'option-2',
label: 'Option 2 Label',
}, {
value: 'option-3',
label: 'Option 3 Label',
}],
defaultValue: 'option-2',
},
{
type: 'row',
fields: [
{
name: 'email',
label: 'Email',
type: 'email',
defaultValue: 'some@email.com',
}, {
name: 'number',
label: 'Number',
type: 'number',
defaultValue: 5,
},
],
},
{
type: 'group',
label: 'Group',
name: 'group',
defaultValue: {
nestedText1: 'neat',
},
fields: [
{
type: 'row',
fields: [
{
name: 'nestedText1',
label: 'Nested Text 1',
type: 'text',
defaultValue: 'nested default text 1',
}, {
name: 'nestedText2',
label: 'Nested Text 2',
type: 'text',
defaultValue: 'nested default text 2',
},
],
},
],
},
{
type: 'array',
label: 'Array',
name: 'array',
admin: {
readOnly: true,
},
defaultValue: [
{
arrayText1: 'Get out',
},
],
fields: [
{
type: 'row',
fields: [
{
name: 'arrayText1',
label: 'Array Text 1',
type: 'text',
admin: {
width: '50%',
},
defaultValue: 'default array text',
},
{
name: 'arrayText2',
label: 'Array Text 2',
type: 'text',
admin: {
width: '50%',
},
access: {
read: ({ req: { user } }) => Boolean(user),
update: ({ req: { user } }) => checkRole(['admin'], user),
},
},
],
},
{
type: 'text',
name: 'arrayText3',
label: 'Array Text 3',
admin: {
readOnly: true,
},
},
{
name: 'checkbox',
label: 'Checkbox',
type: 'checkbox',
defaultValue: true,
},
],
},
{
type: 'blocks',
label: 'Blocks Content',
name: 'blocks',
labels: {
singular: 'Block',
plural: 'Blocks',
},
blocks: [Email, NumberBlock, Quote, CallToAction],
localized: true,
admin: {
readOnly: true,
},
defaultValue: [
{
blockType: 'email',
testEmail: 'dev@payloadcms.com',
},
],
},
{
type: 'relationship',
label: 'Relationship to One Collection',
name: 'relationship',
relationTo: 'conditions',
},
{
type: 'relationship',
label: 'Relationship hasMany',
name: 'relationshipHasMany',
relationTo: 'localized-posts',
hasMany: true,
},
{
type: 'relationship',
label: 'Relationship to Multiple Collections',
name: 'relationshipMultipleCollections',
relationTo: ['localized-posts', 'conditions'],
},
{
type: 'textarea',
label: 'Textarea',
name: 'textarea',
defaultValue: 'my textarea text',
},
{
name: 'slug',
type: 'text',
label: 'Slug',
admin: {
position: 'sidebar',
},
localized: true,
unique: true,
defaultValue: 'my-slug',
},
{
name: 'checkbox',
type: 'checkbox',
label: 'Checkbox',
admin: {
position: 'sidebar',
},
defaultValue: true,
},
{
name: 'richText',
type: 'richText',
label: 'Rich Text',
admin: {
elements: [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'ul',
'ol',
'link',
],
leaves: [
'bold',
'italic',
'underline',
'strikethrough',
],
},
defaultValue: [{
children: [{ text: 'Cookin now' }],
}],
},
],
timestamps: true,
};
export default DefaultValues;

70
demo/collections/File.ts Normal file
View File

@@ -0,0 +1,70 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import checkRole from '../access/checkRole';
const access = ({ req: { user } }) => {
const isAdmin = checkRole(['admin'], user);
if (isAdmin) {
return true;
}
if (user) {
return {
owner: {
equals: user.id,
},
};
}
return false;
};
const Files: PayloadCollectionConfig = {
slug: 'files',
labels: {
singular: 'File',
plural: 'Files',
},
upload: {
staticURL: '/files',
staticDir: './files',
},
access: {
create: () => true,
read: access,
update: access,
delete: access,
},
fields: [
{
name: 'type',
label: 'Type',
type: 'select',
options: [{
value: 'Type 1',
label: 'Type 1 Label',
}, {
value: 'Type 2',
label: 'Type 2 Label',
}, {
value: 'Type 3',
label: 'Type 3 Label',
}],
defaultValue: 'Type 1',
required: true,
},
{
name: 'owner',
label: 'Owner',
type: 'relationship',
relationTo: 'admins',
required: true,
},
],
timestamps: true,
admin: {
useAsTitle: 'filename',
},
};
export default Files;

View File

@@ -0,0 +1,35 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const HiddenFields: PayloadCollectionConfig = {
slug: 'hidden-fields',
labels: {
singular: 'Hidden Fields',
plural: 'Hidden Fields',
},
fields: [
{
name: 'title',
type: 'text',
label: 'Title - Not Hidden',
required: true,
},
{
name: 'hiddenAdmin',
type: 'text',
label: 'Hidden on Admin',
admin: {
hidden: true,
},
required: true,
},
{
name: 'hiddenAPI',
type: 'text',
label: 'Hidden on API',
hidden: true,
required: true, // this should not matter
},
],
};
export default HiddenFields;

95
demo/collections/Hooks.ts Normal file
View File

@@ -0,0 +1,95 @@
/* eslint-disable no-param-reassign */
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Hooks: PayloadCollectionConfig = {
slug: 'hooks',
labels: {
singular: 'Hook',
plural: 'Hooks',
},
admin: {
useAsTitle: 'title',
},
access: {
create: () => true,
read: () => true,
update: () => true,
delete: () => true,
},
hooks: {
beforeRead: [
(operation) => {
if (operation.req.headers.hook === 'beforeRead') {
console.log('before reading Hooks document');
}
},
],
beforeChange: [
(operation) => {
if (operation.req.headers.hook === 'beforeChange') {
operation.data.description += '-beforeChangeSuffix';
}
return operation.data;
},
],
beforeDelete: [
(operation) => {
if (operation.req.headers.hook === 'beforeDelete') {
// TODO: Find a better hook operation to assert against in tests
operation.req.headers.hook = 'afterDelete';
}
},
],
afterRead: [
(operation) => {
const { doc } = operation;
doc.afterReadHook = true;
return doc;
},
],
afterChange: [
(operation) => {
if (operation.req.headers.hook === 'afterChange') {
operation.doc.afterChangeHook = true;
}
return operation.doc;
},
],
afterDelete: [
(operation) => {
if (operation.req.headers.hook === 'afterDelete') {
operation.doc.afterDeleteHook = true;
}
return operation.doc;
},
],
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
maxLength: 100,
required: true,
unique: true,
localized: true,
hooks: {
afterRead: [
({ value }) => (value ? value.toUpperCase() : null),
],
},
},
{
name: 'description',
label: 'Description',
type: 'textarea',
required: true,
localized: true,
},
],
timestamps: true,
};
export default Hooks;

View File

@@ -0,0 +1,38 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const LocalOperations: PayloadCollectionConfig = {
slug: 'local-operations',
labels: {
singular: 'Local Operation',
plural: 'Local Operations',
},
hooks: {
afterRead: [
async ({ req, doc }) => {
const formattedData = { ...doc };
const localizedPosts = await req.payload.find({
collection: 'localized-posts',
});
const blocksGlobal = await req.payload.findGlobal({
global: 'blocks-global',
});
formattedData.localizedPosts = localizedPosts;
formattedData.blocksGlobal = blocksGlobal;
return formattedData;
},
],
},
fields: [
{
name: 'title',
type: 'text',
label: 'title',
required: true,
},
],
};
export default LocalOperations;

View File

@@ -0,0 +1,124 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import { Block } from '../../src/fields/config/types';
const RichTextBlock: Block = {
slug: 'richTextBlock',
labels: {
singular: 'Rich Text Block',
plural: 'Rich Text Blocks',
},
fields: [
{
name: 'content',
localized: true,
type: 'richText',
},
],
};
const LocalizedPosts: PayloadCollectionConfig = {
slug: 'localized-posts',
labels: {
singular: 'Localized Post',
plural: 'Localized Posts',
},
admin: {
useAsTitle: 'title',
defaultColumns: [
'title',
'priority',
'createdAt',
],
enableRichTextRelationship: true,
},
access: {
read: () => true,
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
maxLength: 100,
required: true,
unique: true,
localized: true,
},
{
name: 'summary',
label: 'Summary',
type: 'text',
index: true,
},
{
name: 'description',
label: 'Description',
type: 'textarea',
required: true,
localized: true,
},
{
type: 'richText',
name: 'richText',
label: 'Rich Text',
},
{
name: 'priority',
label: 'Priority',
type: 'number',
required: true,
localized: true,
},
{
name: 'localizedGroup',
label: 'Localized Group',
type: 'group',
localized: true,
fields: [
{
type: 'text',
name: 'text',
label: 'Text',
},
],
},
{
name: 'nonLocalizedGroup',
label: 'Non-Localized Group',
type: 'group',
fields: [
{
type: 'text',
name: 'text',
label: 'Text',
localized: true,
},
],
},
{
type: 'array',
label: 'Non-Localized Array',
name: 'nonLocalizedArray',
maxRows: 3,
fields: [
{
type: 'text',
name: 'localizedEmbeddedText',
label: 'Localized Embedded Text',
localized: true,
},
],
},
{
label: 'Blocks',
name: 'richTextBlocks',
type: 'blocks',
blocks: [
RichTextBlock,
],
},
],
timestamps: true,
};
export default LocalizedPosts;

View File

@@ -0,0 +1,79 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import { FieldAccess } from '../../src/fields/config/types';
import checkRole from '../access/checkRole';
const PublicReadabilityAccess: FieldAccess = ({ req: { user }, siblingData }) => {
if (checkRole(['admin'], user)) {
return true;
}
if (siblingData?.allowPublicReadability) return true;
return false;
};
const LocalizedArrays: PayloadCollectionConfig = {
slug: 'localized-arrays',
labels: {
singular: 'Localized Array',
plural: 'Localized Arrays',
},
access: {
read: () => true,
},
fields: [
{
type: 'array',
label: 'Array',
name: 'array',
localized: true,
required: true,
minRows: 2,
maxRows: 4,
fields: [
{
type: 'row',
fields: [
{
name: 'allowPublicReadability',
label: 'Allow Public Readability',
type: 'checkbox',
},
{
name: 'arrayText1',
label: 'Array Text 1',
type: 'text',
required: true,
admin: {
width: '50%',
},
access: {
read: PublicReadabilityAccess,
},
},
{
name: 'arrayText2',
label: 'Array Text 2',
type: 'text',
required: true,
admin: {
width: '50%',
},
},
],
},
{
type: 'text',
name: 'arrayText3',
label: 'Array Text 3',
admin: {
readOnly: true,
},
},
],
},
],
timestamps: true,
};
export default LocalizedArrays;

51
demo/collections/Media.ts Normal file
View File

@@ -0,0 +1,51 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Media: PayloadCollectionConfig = {
slug: 'media',
labels: {
singular: 'Media',
plural: 'Media',
},
access: {
read: () => true,
},
admin: {
enableRichTextRelationship: true,
},
upload: {
staticURL: '/media',
staticDir: './media',
adminThumbnail: ({ doc }) => `/media/${doc.filename}`,
imageSizes: [
{
name: 'tablet',
width: 640,
height: 480,
crop: 'left top',
},
{
name: 'mobile',
width: 320,
height: 240,
crop: 'left top',
},
{
name: 'icon',
width: 16,
height: 16,
},
],
},
fields: [
{
name: 'alt',
label: 'Alt Text',
type: 'text',
required: true,
localized: true,
},
],
timestamps: true,
};
export default Media;

View File

@@ -0,0 +1,71 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const NestedArray: PayloadCollectionConfig = {
slug: 'nested-arrays',
labels: {
singular: 'Nested Array',
plural: 'Nested Arrays',
},
access: {
read: () => true,
},
fields: [
{
type: 'array',
label: 'Array',
name: 'array',
labels: {
singular: 'Parent Row',
plural: 'Parent Rows',
},
required: true,
minRows: 2,
maxRows: 4,
fields: [
{
name: 'parentIdentifier',
label: 'Parent Identifier',
defaultValue: ' ',
type: 'text',
required: true,
},
{
type: 'array',
name: 'nestedArray',
labels: {
singular: 'Child Row',
plural: 'Child Rows',
},
required: true,
fields: [
{
name: 'childIdentifier',
label: 'Child Identifier',
type: 'text',
required: true,
},
{
type: 'array',
name: 'deeplyNestedArray',
labels: {
singular: 'Grandchild Row',
plural: 'Grandchild Rows',
},
required: true,
fields: [
{
name: 'grandchildIdentifier',
label: 'Grandchild Identifier',
type: 'text',
},
],
},
],
},
],
},
],
timestamps: true,
};
export default NestedArray;

View File

@@ -0,0 +1,33 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Preview: PayloadCollectionConfig = {
slug: 'previewable-post',
labels: {
singular: 'Previewable Post',
plural: 'Previewable Posts',
},
admin: {
useAsTitle: 'title',
preview: (doc, token) => {
if (doc.title) {
return `http://localhost:3000/previewable-posts/${doc.title}?preview=true&token=${token}`;
}
return null;
},
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
maxLength: 100,
required: true,
unique: true,
localized: true,
},
],
timestamps: true,
};
export default Preview;

View File

@@ -0,0 +1,61 @@
import checkRole from '../access/checkRole';
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const access = ({ req: { user } }) => checkRole(['admin'], user);
const PublicUsers: PayloadCollectionConfig = {
slug: 'public-users',
labels: {
singular: 'Public User',
plural: 'Public Users',
},
admin: {
useAsTitle: 'email',
},
access: {
admin: () => false,
create: () => true,
read: () => true,
update: ({ req: { user } }) => {
if (checkRole(['admin'], user)) {
return true;
}
if (user) {
return {
id: user.id,
};
}
return false;
},
delete: ({ req: { user } }) => checkRole(['admin'], user),
},
auth: {
tokenExpiration: 300,
verify: true,
maxLoginAttempts: 5,
lockTime: 600 * 1000, // lock time in ms
cookies: {
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
domain: undefined,
},
},
fields: [
{
name: 'adminOnly',
label: 'This field should only be readable and editable by Admins with "admin" role',
type: 'text',
defaultValue: 'test',
access: {
create: access,
read: access,
update: access,
},
},
],
timestamps: true,
};
export default PublicUsers;

View File

@@ -0,0 +1,48 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const RelationshipA: PayloadCollectionConfig = {
slug: 'relationship-a',
access: {
read: () => true,
},
labels: {
singular: 'Relationship A',
plural: 'Relationship A',
},
fields: [
{
name: 'post',
label: 'Post',
type: 'relationship',
relationTo: 'relationship-b',
localized: true,
},
{
name: 'LocalizedPost',
label: 'Localized Post',
type: 'relationship',
relationTo: 'localized-posts',
hasMany: true,
localized: true,
},
{
name: 'postLocalizedMultiple',
label: 'Localized Post Multiple',
type: 'relationship',
relationTo: ['localized-posts', 'all-fields'],
hasMany: true,
localized: true,
},
{
name: 'postManyRelationships',
label: 'Post Many Relationships',
type: 'relationship',
relationTo: ['relationship-b'],
localized: true,
hasMany: false,
},
],
timestamps: true,
};
export default RelationshipA;

View File

@@ -0,0 +1,33 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const RelationshipB: PayloadCollectionConfig = {
slug: 'relationship-b',
access: {
read: () => true,
},
labels: {
singular: 'Relationship B',
plural: 'Relationship B',
},
fields: [
{
name: 'post',
label: 'Post',
type: 'relationship',
relationTo: 'relationship-a',
localized: false,
hasMany: true,
},
{
name: 'postManyRelationships',
label: 'Post Many Relationships',
type: 'relationship',
relationTo: ['relationship-a'],
localized: true,
hasMany: false,
},
],
timestamps: true,
};
export default RelationshipB;

View File

@@ -0,0 +1,38 @@
import Button from '../client/components/richText/elements/Button';
import PurpleBackground from '../client/components/richText/leaves/PurpleBackground';
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const RichText: PayloadCollectionConfig = {
slug: 'rich-text',
labels: {
singular: 'Rich Text',
plural: 'Rich Texts',
},
fields: [
{
name: 'defaultRichText',
type: 'richText',
label: 'Default Rich Text',
required: true,
},
{
name: 'customRichText',
type: 'richText',
label: 'Customized Rich Text',
required: true,
admin: {
elements: [
'h2',
'h3',
Button,
],
leaves: [
'bold',
PurpleBackground,
],
},
},
],
};
export default RichText;

View File

@@ -0,0 +1,45 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Select: PayloadCollectionConfig = {
slug: 'select',
labels: {
singular: 'Select',
plural: 'Selects',
},
fields: [
{
name: 'Select',
type: 'select',
options: [{
value: 'one',
label: 'One',
}, {
value: 'two',
label: 'Two',
}, {
value: 'three',
label: 'Three',
}],
label: 'Select From',
required: true,
},
{
name: 'Radio',
type: 'radio',
options: [{
value: 'one',
label: 'One',
}, {
value: 'two',
label: 'Two',
}, {
value: 'three',
label: 'Three',
}],
label: 'Choose From',
required: true,
},
],
};
export default Select;

View File

@@ -0,0 +1,76 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
import checkRole from '../access/checkRole';
const StrictAccess: PayloadCollectionConfig = {
slug: 'strict-access',
labels: {
singular: 'Strict Access',
plural: 'Strict Access',
},
admin: {
useAsTitle: 'email',
},
access: {
create: () => true,
read: ({ req: { user } }) => {
if (checkRole(['admin'], user)) {
return true;
}
if (user) {
return {
owner: {
equals: user.id,
},
};
}
return false;
},
update: ({ req: { user } }) => {
if (checkRole(['admin'], user)) {
return true;
}
if (user) {
return {
owner: {
equals: user.id,
},
};
}
return false;
},
delete: ({ req: { user } }) => checkRole(['admin'], user),
},
fields: [
{
name: 'address',
type: 'text',
label: 'Address',
required: true,
},
{
name: 'city',
type: 'text',
label: 'City',
required: true,
},
{
name: 'state',
type: 'text',
label: 'State',
required: true,
},
{
name: 'zip',
type: 'number',
label: 'ZIP Code',
required: true,
},
],
timestamps: true,
};
export default StrictAccess;

View File

@@ -0,0 +1,25 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Uniques: PayloadCollectionConfig = {
slug: 'uniques',
labels: {
singular: 'Unique',
plural: 'Uniques',
},
fields: [
{
name: 'title',
type: 'text',
label: 'Title',
required: true,
unique: true,
},
{
name: 'description',
type: 'textarea',
label: 'Description',
},
],
};
export default Uniques;

View File

@@ -0,0 +1,113 @@
import { PayloadCollectionConfig } from '../../src/collections/config/types';
const Validations: PayloadCollectionConfig = {
slug: 'validations',
labels: {
singular: 'Validation',
plural: 'Validations',
},
access: {
read: () => true,
},
fields: [
{
name: 'text',
type: 'text',
label: 'Text',
required: true,
validate: (value) => {
const result = value === 'test';
if (!result) {
return 'The only accepted value of this field is "test".';
}
return true;
},
},
{
type: 'row',
fields: [
{
name: 'lessThan10',
label: 'Less than 10',
type: 'number',
required: true,
validate: (value) => {
const result = parseInt(value, 10) < 10;
if (!result) {
return 'The value of this field needs to be less than 10.';
}
return true;
},
}, {
name: 'greaterThan10LessThan50',
label: 'Greater than 10, Less than 50',
type: 'number',
required: true,
min: 10,
max: 50,
},
],
},
{
type: 'array',
label: 'Should have at least 3 rows',
name: 'atLeast3Rows',
required: true,
validate: (value) => {
const result = value && value.length >= 3;
if (!result) {
return 'This array needs to have at least 3 rows.';
}
return true;
},
fields: [
{
type: 'number',
name: 'greaterThan30',
label: 'Number should be greater than 30',
required: true,
validate: (value) => {
const result = value > 30;
if (!result) {
return 'This value of this field needs to be greater than 30.';
}
return true;
},
},
],
},
{
type: 'array',
label: 'Default array validation',
name: 'array',
required: true,
fields: [
{
type: 'number',
name: 'lessThan20',
label: 'Number should be less than 20',
required: true,
validate: (value) => {
const result = value < 30;
if (!result) {
return 'This value of this field needs to be less than 20.';
}
return true;
},
},
],
},
],
};
export default Validations;

15
demo/custom-index.html Normal file
View File

@@ -0,0 +1,15 @@
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="application-name" content="My Payload Application" />
</head>
<body>
<div id="app"></div>
<div id="portal"></div>
</body>
</html>

View File

@@ -0,0 +1,5 @@
import React from 'react';
const CustomAccountView: React.FC = () => <div>fake account view</div>;
export default CustomAccountView;

View File

@@ -0,0 +1,5 @@
import React from 'react';
const CustomDashboardView: React.FC = () => <div>fake dashboard view</div>;
export default CustomDashboardView;

View File

@@ -0,0 +1,22 @@
import checkRole from '../access/checkRole';
import Quote from '../blocks/Quote';
import CallToAction from '../blocks/CallToAction';
import { PayloadGlobalConfig } from '../../src/globals/config/types';
export default {
slug: 'blocks-global',
label: 'Blocks Global',
access: {
update: ({ req: { user } }) => checkRole(['admin'], user),
read: () => true,
},
fields: [
{
name: 'blocks',
label: 'Blocks',
type: 'blocks',
blocks: [Quote, CallToAction],
localized: true,
},
],
} as PayloadGlobalConfig;

View File

@@ -0,0 +1,35 @@
import { PayloadGlobalConfig } from '../../src/globals/config/types';
import checkRole from '../access/checkRole';
export default {
slug: 'global-with-access',
label: 'Global with Strict Access',
access: {
update: ({ req: { user } }) => checkRole(['admin'], user),
read: ({ req: { user } }) => checkRole(['admin'], user),
},
fields: [
{
name: 'title',
label: 'Site Title',
type: 'text',
maxLength: 100,
required: true,
},
{
name: 'relationship',
label: 'Test Relationship',
type: 'relationship',
relationTo: 'localized-posts',
hasMany: true,
required: true,
},
{
name: 'singleRelationship',
label: 'Test Single Relationship',
type: 'relationship',
relationTo: 'localized-posts',
required: true,
},
],
} as PayloadGlobalConfig;

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