Compare commits

..

26 Commits

Author SHA1 Message Date
Elliot DeNolf
a8c60c1c02 chore(release): v3.0.0-beta.101 [skip ci] 2024-09-09 16:04:45 -04:00
James Mikrut
d44fb2db37 fix: #6800, graphql parallel queries with different fallback locales (#8140)
## Description

Fixes #6800 where parallel GraphQL queries with different locales /
fallbackLocales do not return their data properly.
2024-09-09 16:01:58 -04:00
Dan Ribbens
852f9fc1fd fix!: multiple preferences for the same user and entry (#8100)
fixes #7762

This change mitigates having multiple preferences for one user but not
awaiting the change to a preference and reduces querying by skipping the
access control. In the event that a user has multiple preferences with
the same key, only the one with the latest updatedAt will be returned.

BREAKING CHANGES:
- payload/preferences/operations are no longer default exports

## Description

<!-- Please include a summary of the pull request and any related issues
it fixes. Please also include relevant motivation and context. -->

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/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)
- [x] 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:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation

---------

Co-authored-by: Paul Popus <paul@nouance.io>
2024-09-09 14:00:51 -04:00
Dan Ribbens
e2d803800d fix: removes transactions wrapping auth strategies and login (#8137)
## Description

By default all api requests are creating transactions due to the
authentication stategy. This change removes transactions for auth and
login requests. This should only happen when the database needs to make
changes in which case the auth strategy or login lockout updates will
invoke their own transactions still.

This should improve performance without any sacrifice to database
consistency.

Fixes #8092 

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/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:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation
2024-09-09 13:27:21 -04:00
Germán Jabloñski
7fa68d17f5 fix(ui): wrong block indication when an error occurred (#7963) 2024-09-09 10:20:03 -04:00
Paul
9ec431a5bd fix(ui): bulk select checkbox being selected by default when in drawer (#8126) 2024-09-09 06:47:35 +00:00
Paul
cadf815ef6 fix(ui): thumbnails when serverURL config is provided (#8124) 2024-09-09 06:16:43 +00:00
Paul
638382e7fd feat: add validation for useAsTitle to throw an error if it's an invalid or nested field (#8122) 2024-09-08 18:53:12 -06:00
Elliot DeNolf
08fdbcacc0 chore: proper error log format (#8105)
Fix some error log formatting to use `{ msg, err }` properly
2024-09-07 02:48:59 +00:00
Paul
b27e42c484 fix(ui): various issues around documents lists, listQuery provider and search params (#8081)
This PR fixes and improves:
- ListQuery provider is now the source of truth for searchParams instead
of having components use the `useSearchParams` hook
- Various issues with search params and filters sticking around when
navigating between collections
- Pagination and limits not working inside DocumentDrawer
- Searching and filtering causing a flash of overlay in DocumentDrawer,
this now only shows for the first load and on slow networks
- Preferences are now respected in DocumentDrawer
- Changing the limit now resets your page back to 1 in case the current
page no longer exists

Fixes https://github.com/payloadcms/payload/issues/7085
Fixes https://github.com/payloadcms/payload/pull/8081
Fixes https://github.com/payloadcms/payload/issues/8086
2024-09-06 15:51:09 -06:00
Tylan Davis
32cc1a5761 fix(ui): missing thumbnail for non-image files in bulk upload sidebar (#8102)
## Description

Uses the `Thumbnail` component used in other places for the bulk upload
file rows. Closes #8099

In the future, we should consider adding different thumbnail icons based
on the `mimeType` to better describe the files being uploaded.

Before:
![Screenshot 2024-09-06 at 4 51
56 PM](https://github.com/user-attachments/assets/35cd528c-5086-465e-8d3c-7bb66d7c35da)


After:
![Screenshot 2024-09-06 at 4 50
12 PM](https://github.com/user-attachments/assets/54d2b98d-ac11-481e-abe5-4be071c3c8f2)


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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation
2024-09-06 21:28:50 +00:00
Tylan Davis
38be69b7d3 fix(ui): better responsiveness for upload fields in sidebar (#8101)
## Description

Adjusts the styling for the Dropzone component for upload fields with
`admin.position: sidebar`.

Before:
![Screenshot 2024-09-06 at 4 10
28 PM](https://github.com/user-attachments/assets/221d43f9-f426-4a44-ba58-29123050c775)

After:
![Screenshot 2024-09-06 at 4 09
32 PM](https://github.com/user-attachments/assets/c4369a65-d842-4e65-9153-19244fcf5600)


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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation
2024-09-06 20:37:38 +00:00
Elliot DeNolf
6b82196f01 chore(release): v3.0.0-beta.100 [skip ci] 2024-09-06 15:25:41 -04:00
Tylan Davis
ead12c8a49 fix(ui, next): adjust modal alignment and padding (#7931)
## Description

Updates styling on modals and auth forms for more consistent spacing and
alignment.

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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation
2024-09-06 14:54:39 -04:00
Jacob Fletcher
6253ec5d1a fix(ui): optimizes the relationship field by sharing a single document drawer across all values (#8094)
## Description

Currently, the relationship field's _value(s)_ each render and controls
its own document drawer. This has led to `hasMany` relationships
processing a potentially large number of drawers unnecessarily. But the
real problem is when attempting to perform side-effects as a result of a
drawer action. Currently, when you change the value of a relationship
field, all drawers within are (rightfully) unmounted because the
component representing the value was itself unmounted. This meant that
you could not update the title of a document, for example, then update
the underlying field's value, without also closing the document drawer
outright. This is needed in order to support things like creating and
duplicating documents within document drawers (#7679).

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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [x] Existing test suite passes locally with my changes
2024-09-06 14:00:53 -04:00
Jacob Fletcher
f9ae56ec88 fix(ui): handles falsey relationship options on reset (#8095) 2024-09-06 12:55:09 -04:00
Sasha
0688c2b79d fix(db-postgres): sanitize tab/group path for table name (#8009)
## Description

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

Example of table structures that lead to the problem with camelCased
group / tab names.
`group_field_array_localized` - `groupField` -> `array` (has a localized
field inside)
`group_field_array_nested_array` - `groupField` -> `array` ->
`nestedArray`

<!-- Please include a summary of the pull request and any related issues
it fixes. Please also include relevant motivation and context. -->

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

## Type of change

<!-- Please delete options that are not relevant. -->

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
2024-09-06 11:43:47 -04:00
Sasha
c6246618ba fix(cpa): detect package manager from command execution environment (#8087)
Previously, on some machines this command:
`pnpx create-payload-app@beta app` created a project using `npm`,
instead of `pnpm`, the same with `yarn`.

Also, the way we detected the package manager was always prioritizing
`pnpm`, even if they executed the command with `yarn` / `npm`. Now we
are relying only on from which package manager user executed
`create-payload-app`.

The code for detection is grabbed from create-next-app
https://github.com/vercel/next.js/blob/canary/packages/create-next-app/helpers/get-pkg-manager.ts
2024-09-06 08:57:20 -04:00
Alexander
b69826a81e feat(cpa): add support for bun package manager in v3 installer (#7709)
Adds support for bun package manger in v3, enabled with `--use-bun`
flag.

Related: #6932 (for v2)
2024-09-05 23:50:03 -04:00
Paul
e80da7cb75 chore: add jsdocs for authentication types and add missing config to docs (#8082) 2024-09-06 00:04:13 +00:00
Francisco Lourenço
6f512b6ca8 docs: fix TextFieldProps in client field component example (#8080)
## Description

Without using `React.FC<>`, the type needs to be placed on the right
side of the props object.

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

## Type of change

<!-- Please delete options that are not relevant. -->

- [x] Chore (non-breaking change which does not add functionality)

## Checklist:

- [ ] ~I have added tests that prove my fix is effective or that my
feature works~
- [ ] ~Existing test suite passes locally with my changes~
- [x] I have made corresponding changes to the documentation
2024-09-05 15:41:48 -06:00
Elliot DeNolf
22ee8bf383 chore(release): v3.0.0-beta.99 [skip ci] 2024-09-05 12:38:08 -04:00
Jacob Fletcher
308fad8a7a fix(ui): significantly optimizes relationship field (#8063)
## Description

Reduces the number of client-side requests made by the relationship
field component, and fixes the visual "blink" of the field's value on
initial load. Does so through a new `useIgnoredEffect` hook that allows
this component's effects to be precisely triggered based on whether a
only _subset_ of its dependencies have changed, which looks something
like this:

```tsx
// ...
useIgnoredEffect(() => {
  // Do something
}, [deps], [ignoredDeps])
```

"Ignored deps" are still treated as normal dependencies of the
underlying `useEffect` hook, but they do not cause the provided function
to execute. This is useful if you have a list of dependencies that
change often, but need to scope your effect's logic to explicit
dependencies within that list. This is a typical pattern in React using
refs, just standardized within a reusable hook.

This significantly reduces the overall number of re-renders and
duplicative API requests within the relationship field because the
`useEffect` hooks that control the fetching of these related documents
were running unnecessarily often. In the future, we really ought to
leverage the `RelationshipProvider` used in the List View so that we can
also reduce the number of duplicative requests across _unrelated fields_
within the same document.

Before:


https://github.com/user-attachments/assets/ece7c85e-20fb-49f6-b393-c5e9d5176192

After:


https://github.com/user-attachments/assets/9f0a871e-f10f-4fd6-a58b-8146ece288c4

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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
2024-09-04 21:37:00 -04:00
Jessica Chowdhury
6427b7eb29 fix: only show restore as draft option when drafts enabled (#8066)
## Description

In version comparison view, the `Restore as draft` button should only be
visible when `versions.drafts: true`.

Before:
<img width="1414" alt="Screenshot 2024-09-04 at 3 33 21 PM"
src="https://github.com/user-attachments/assets/1f96d804-46d7-443a-99ea-7b6481839b47">

After:
<img width="1307" alt="Screenshot 2024-09-04 at 3 38 42 PM"
src="https://github.com/user-attachments/assets/d2621ddd-2b14-4dab-936c-29a5521444de">


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

## Type of change

- [X] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [ ] I have added tests that prove my fix is effective or that my
feature works
- [X] Existing test suite passes locally with my changes
- [ ] I have made corresponding changes to the documentation
2024-09-04 19:54:34 +00:00
Sasha
3a657847f2 fix(db-postgres): query hasMany text/number in array/blocks (#8003)
## Description

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

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

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
## Checklist:

- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] Existing test suite passes locally with my changes
2024-09-04 11:53:43 -04:00
Elliot DeNolf
8212c0d65f chore(eslint): silence some warnings that always get auto-fixed 2024-09-04 11:26:36 -04:00
131 changed files with 2206 additions and 758 deletions

11
.vscode/settings.json vendored
View File

@@ -31,8 +31,15 @@
"editor.formatOnSave": true
},
"editor.formatOnSaveMode": "file",
// All ESLint rules to 'warn' to differentate from TypeScript's 'error' level
"eslint.rules.customizations": [{ "rule": "*", "severity": "warn" }],
"eslint.rules.customizations": [
// Defaultt all ESLint errors to 'warn' to differentate from TypeScript's 'error' level
{ "rule": "*", "severity": "warn" },
// Silence some warnings that will get auto-fixed
{ "rule": "perfectionist/*", "severity": "off", "fixable": true },
{ "rule": "curly", "severity": "off", "fixable": true },
{ "rule": "object-shorthand", "severity": "off", "fixable": true }
],
"typescript.tsdk": "node_modules/typescript/lib",
// Load .git-blame-ignore-revs file
"gitlens.advanced.blame.customArguments": ["--ignore-revs-file", ".git-blame-ignore-revs"],

View File

@@ -438,7 +438,7 @@ All [Field Components](./fields) automatically receive their respective Client F
import React from 'react'
import type { TextFieldProps } from 'payload'
export const MyClientFieldComponent: TextFieldProps = ({ field: { name } }) => {
export const MyClientFieldComponent = ({ field: { name } }: TextFieldProps) => {
return (
<p>
{`This field's name is ${name}`}

View File

@@ -85,6 +85,7 @@ The following options are available:
| **`lockTime`** | Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. |
| **`loginWithUsername`** | Ability to allow users to login with username/password. [More](/docs/authentication/overview#login-with-username) |
| **`maxLoginAttempts`** | Only allow a user to attempt logging in X amount of times. Automatically locks out a user from authenticating if this limit is passed. Set to `0` to disable. |
| **`removeTokenFromResponses`** | Set to true if you want to remove the token from the returned authentication API responses such as login or refresh. |
| **`strategies`** | Advanced - an array of custom authentification strategies to extend this collection's authentication with. [More details](./custom-strategies). |
| **`tokenExpiration`** | How long (in seconds) to keep the user logged in. JWTs and HTTP-only cookies will both expire at the same time. |
| **`useAPIKey`** | Payload Authentication provides for API keys to be set on each user within an Authentication-enabled Collection. [More details](./api-keys). |

View File

@@ -5,13 +5,13 @@ export const recordLastLoggedInTenant: AfterLoginHook = async ({ req, user }) =>
const relatedOrg = await req.payload
.find({
collection: 'tenants',
depth: 0,
limit: 1,
where: {
'domains.domain': {
in: [req.headers.host],
},
},
depth: 0,
limit: 1,
})
?.then((res) => res.docs?.[0])
@@ -24,7 +24,10 @@ export const recordLastLoggedInTenant: AfterLoginHook = async ({ req, user }) =>
req,
})
} catch (err: unknown) {
req.payload.logger.error(`Error recording last logged in tenant for user ${user.id}: ${err}`)
req.payload.logger.error({
err,
msg: `Error recording last logged in tenant for user ${user.id}`,
})
}
return user

View File

@@ -1,6 +1,6 @@
{
"name": "payload-monorepo",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"private": true,
"type": "module",
"scripts": {

View File

@@ -1,6 +1,6 @@
{
"name": "create-payload-app",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -37,6 +37,8 @@ async function installDeps(args: {
installCmd = 'yarn'
} else if (packageManager === 'pnpm') {
installCmd = 'pnpm install'
} else if (packageManager === 'bun') {
installCmd = 'bun install'
}
try {

View File

@@ -1,12 +1,8 @@
import execa from 'execa'
import fse from 'fs-extra'
import type { CliArgs, PackageManager } from '../types.js'
export async function getPackageManager(args: {
cliArgs?: CliArgs
projectDir: string
}): Promise<PackageManager> {
export function getPackageManager(args: { cliArgs?: CliArgs; projectDir: string }): PackageManager {
const { cliArgs, projectDir } = args
try {
@@ -18,15 +14,11 @@ export async function getPackageManager(args: {
detected = 'yarn'
} else if (cliArgs?.['--use-npm'] || fse.existsSync(`${projectDir}/package-lock.json`)) {
detected = 'npm'
} else if (cliArgs?.['--use-bun'] || fse.existsSync(`${projectDir}/bun.lockb`)) {
detected = 'bun'
} else {
// Otherwise check for existing commands
if (await commandExists('pnpm')) {
detected = 'pnpm'
} else if (await commandExists('yarn')) {
detected = 'yarn'
} else {
detected = 'npm'
}
// Otherwise check the execution environment
detected = getEnvironmentPackageManager()
}
return detected
@@ -35,11 +27,20 @@ export async function getPackageManager(args: {
}
}
async function commandExists(command: string): Promise<boolean> {
try {
await execa.command(`command -v ${command}`)
return true
} catch {
return false
function getEnvironmentPackageManager(): PackageManager {
const userAgent = process.env.npm_config_user_agent || ''
if (userAgent.startsWith('yarn')) {
return 'yarn'
}
if (userAgent.startsWith('pnpm')) {
return 'pnpm'
}
if (userAgent.startsWith('bun')) {
return 'bun'
}
return 'npm'
}

View File

@@ -49,6 +49,7 @@ export class Main {
// Package manager
'--no-deps': Boolean,
'--use-bun': Boolean,
'--use-npm': Boolean,
'--use-pnpm': Boolean,
'--use-yarn': Boolean,
@@ -132,7 +133,7 @@ export class Main {
? path.dirname(nextConfigPath)
: path.resolve(process.cwd(), slugify(projectName))
const packageManager = await getPackageManager({ cliArgs: this.args, projectDir })
const packageManager = getPackageManager({ cliArgs: this.args, projectDir })
if (nextConfigPath) {
p.log.step(

View File

@@ -16,6 +16,7 @@ export interface Args extends arg.Spec {
'--secret': StringConstructor
'--template': StringConstructor
'--template-branch': StringConstructor
'--use-bun': BooleanConstructor
'--use-npm': BooleanConstructor
'--use-pnpm': BooleanConstructor
'--use-yarn': BooleanConstructor

View File

@@ -40,6 +40,7 @@ export function helpMessage(): void {
--use-npm Use npm to install dependencies
--use-yarn Use yarn to install dependencies
--use-pnpm Use pnpm to install dependencies
--use-bun Use bun to install dependencies (experimental)
--no-deps Do not install any dependencies
-h Show help
`)

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-mongodb",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The officially supported MongoDB database adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-postgres",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The officially supported Postgres database adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -23,7 +23,7 @@ const connectWithReconnect = async function ({
} else {
try {
result = await adapter.pool.connect()
} catch (err) {
} catch (ignore) {
setTimeout(() => {
payload.logger.info('Reconnecting to postgres')
void connectWithReconnect({ adapter, payload, reconnect: true })
@@ -38,7 +38,7 @@ const connectWithReconnect = async function ({
if (err.code === 'ECONNRESET') {
void connectWithReconnect({ adapter, payload, reconnect: true })
}
} catch (err) {
} catch (ignore) {
// swallow error
}
})
@@ -76,7 +76,7 @@ export const connect: Connect = async function connect(
}
}
} catch (err) {
this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)
this.payload.logger.error({ err, msg: `Error: cannot connect to Postgres: ${err.message}` })
if (typeof this.rejectInitializing === 'function') {
this.rejectInitializing()
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-sqlite",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The officially supported SQLite database adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -37,7 +37,7 @@ export const connect: Connect = async function connect(
}
}
} catch (err) {
this.payload.logger.error(`Error: cannot connect to SQLite. Details: ${err.message}`, err)
this.payload.logger.error({ err, msg: `Error: cannot connect to SQLite: ${err.message}` })
if (typeof this.rejectInitializing === 'function') {
this.rejectInitializing()
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-vercel-postgres",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Vercel Postgres adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -39,7 +39,7 @@ export const connect: Connect = async function connect(
}
}
} catch (err) {
this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)
this.payload.logger.error({ err, msg: `Error: cannot connect to Postgres: ${err.message}` })
if (typeof this.rejectInitializing === 'function') {
this.rejectInitializing()
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/drizzle",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "A library of shared functions used by different payload database adapters",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -80,6 +80,7 @@ export const buildFindManyArgs = ({
depth,
fields,
path: '',
tablePath: '',
topLevelArgs: result,
topLevelTableName: tableName,
})

View File

@@ -14,6 +14,7 @@ type TraverseFieldArgs = {
depth?: number
fields: Field[]
path: string
tablePath: string
topLevelArgs: Record<string, unknown>
topLevelTableName: string
}
@@ -26,6 +27,7 @@ export const traverseFields = ({
depth,
fields,
path,
tablePath,
topLevelArgs,
topLevelTableName,
}: TraverseFieldArgs) => {
@@ -53,6 +55,7 @@ export const traverseFields = ({
depth,
fields: field.fields,
path,
tablePath,
topLevelArgs,
topLevelTableName,
})
@@ -63,6 +66,7 @@ export const traverseFields = ({
if (field.type === 'tabs') {
field.tabs.forEach((tab) => {
const tabPath = tabHasName(tab) ? `${path}${tab.name}_` : path
const tabTablePath = tabHasName(tab) ? `${tablePath}${toSnakeCase(tab.name)}_` : tablePath
traverseFields({
_locales,
@@ -72,6 +76,7 @@ export const traverseFields = ({
depth,
fields: tab.fields,
path: tabPath,
tablePath: tabTablePath,
topLevelArgs,
topLevelTableName,
})
@@ -92,7 +97,7 @@ export const traverseFields = ({
}
const arrayTableName = adapter.tableNameMap.get(
`${currentTableName}_${path}${toSnakeCase(field.name)}`,
`${currentTableName}_${tablePath}${toSnakeCase(field.name)}`,
)
const arrayTableNameWithLocales = `${arrayTableName}${adapter.localesSuffix}`
@@ -116,6 +121,7 @@ export const traverseFields = ({
depth,
fields: field.fields,
path: '',
tablePath: '',
topLevelArgs,
topLevelTableName,
})
@@ -172,6 +178,7 @@ export const traverseFields = ({
depth,
fields: block.fields,
path: '',
tablePath: '',
topLevelArgs,
topLevelTableName,
})
@@ -180,7 +187,7 @@ export const traverseFields = ({
break
case 'group':
case 'group': {
traverseFields({
_locales,
adapter,
@@ -189,11 +196,13 @@ export const traverseFields = ({
depth,
fields: field.fields,
path: `${path}${field.name}_`,
tablePath: `${tablePath}${toSnakeCase(field.name)}_`,
topLevelArgs,
topLevelTableName,
})
break
}
default: {
break

View File

@@ -257,10 +257,10 @@ export const getTableColumnFromPath = ({
tableType = 'numbers'
columnName = 'number'
}
newTableName = `${tableName}_${tableType}`
newTableName = `${rootTableName}_${tableType}`
const joinConstraints = [
eq(adapter.tables[tableName].id, adapter.tables[newTableName].parent),
eq(adapter.tables[newTableName].path, `${constraintPath}${field.name}`),
eq(adapter.tables[rootTableName].id, adapter.tables[newTableName].parent),
like(adapter.tables[newTableName].path, `${constraintPath}${field.name}`),
]
if (locale && field.localized && adapter.payload.config.localization) {

View File

@@ -37,6 +37,7 @@ export const beginTransaction: BeginTransaction = async function beginTransactio
return done
}
reject = () => {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
rej()
return done
}
@@ -57,7 +58,7 @@ export const beginTransaction: BeginTransaction = async function beginTransactio
resolve,
}
} catch (err) {
this.payload.logger.error(`Error: cannot begin transaction: ${err.message}`, err)
this.payload.logger.error({ err, msg: `Error: cannot begin transaction: ${err.message}` })
process.exit(1)
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/email-nodemailer",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload Nodemailer Email Adapter",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/email-resend",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload Resend Email Adapter",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/graphql",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/live-preview-react",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official React SDK for Payload Live Preview",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/live-preview-vue",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official Vue SDK for Payload Live Preview",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/live-preview",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official live preview JavaScript SDK for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/next",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -12,14 +12,14 @@
position: relative;
display: flex;
flex-direction: column;
gap: var(--base);
gap: base(0.8);
padding: base(2);
}
&__content {
display: flex;
flex-direction: column;
gap: var(--base);
gap: base(0.4);
> * {
margin: 0;
@@ -28,7 +28,7 @@
&__controls {
display: flex;
gap: var(--base);
gap: base(0.4);
.btn {
margin: 0;

View File

@@ -14,14 +14,14 @@
&--width-normal {
.template-minimal__wrap {
max-width: 500px;
max-width: base(24);
width: 100%;
}
}
&--width-wide {
.template-minimal__wrap {
max-width: 1024px;
max-width: base(48);
width: 100%;
}
}

View File

@@ -1,6 +1,16 @@
@import '../../scss/styles.scss';
.create-first-user {
display: flex;
flex-direction: column;
gap: base(0.4);
> form > .field-type {
margin-bottom: var(--base);
& .form-submit {
margin: 0;
}
}
}

View File

@@ -28,7 +28,6 @@ import {
useListQuery,
useModal,
useRouteCache,
useSearchParams,
useStepNav,
useTranslation,
useWindowInfo,
@@ -54,8 +53,7 @@ export const DefaultListView: React.FC = () => {
newDocumentURL,
} = useListInfo()
const { data, defaultLimit, handlePageChange, handlePerPageChange } = useListQuery()
const { searchParams } = useSearchParams()
const { data, defaultLimit, handlePageChange, handlePerPageChange, params } = useListQuery()
const { openModal } = useModal()
const { clearRouteCache } = useRouteCache()
const { setCollectionSlug, setOnSuccess } = useBulkUpload()
@@ -226,9 +224,7 @@ export const DefaultListView: React.FC = () => {
</div>
<PerPage
handleChange={(limit) => void handlePerPageChange(limit)}
limit={
isNumber(searchParams?.limit) ? Number(searchParams.limit) : defaultLimit
}
limit={isNumber(params?.limit) ? Number(params.limit) : defaultLimit}
limits={collectionConfig?.admin?.pagination?.limits}
resetPage={data.totalDocs <= data.pagingCounter}
/>

View File

@@ -4,6 +4,10 @@ import { formatAdminURL } from '@payloadcms/ui/shared'
import LinkImport from 'next/link.js'
import React, { Fragment, useEffect } from 'react'
import './index.scss'
const baseClass = 'logout'
const Link = (LinkImport.default || LinkImport) as unknown as typeof LinkImport.default
export const LogoutClient: React.FC<{
@@ -26,7 +30,7 @@ export const LogoutClient: React.FC<{
if (isLoggingOut) {
return (
<Fragment>
<div className={`${baseClass}__wrap`}>
{inactivity && <h2>{t('authentication:loggedOutInactivity')}</h2>}
{!inactivity && <h2>{t('authentication:loggedOutSuccessfully')}</h2>}
<Button
@@ -43,7 +47,7 @@ export const LogoutClient: React.FC<{
>
{t('authentication:logBackIn')}
</Button>
</Fragment>
</div>
)
}

View File

@@ -1,19 +1,22 @@
@import '../../scss/styles.scss';
.logout {
display: flex;
flex-direction: column;
align-items: center;
flex-wrap: wrap;
min-height: 100vh;
&__wrap {
& > *:first-child {
margin-top: 0;
}
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: base(0.8);
width: 100%;
max-width: base(36);
& > *:last-child {
margin-bottom: 0;
}
.btn {
& > * {
margin: 0;
}
}

View File

@@ -25,7 +25,7 @@ export const LogoutView: React.FC<
} = initPageResult
return (
<div className={`${baseClass}__wrap`}>
<div className={`${baseClass}`}>
<LogoutClient
adminRoute={adminRoute}
inactivity={inactivity}

View File

@@ -38,8 +38,10 @@ export const NotFoundClient: React.FC<{
.join(' ')}
>
<Gutter className={`${baseClass}__wrap`}>
<h1>{t('general:nothingFound')}</h1>
<p>{t('general:sorryNotFound')}</p>
<div className={`${baseClass}__content`}>
<h1>{t('general:nothingFound')}</h1>
<p>{t('general:sorryNotFound')}</p>
</div>
<Button
className={`${baseClass}__button`}
el="link"

View File

@@ -13,6 +13,24 @@
}
}
&__wrap {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: base(0.8);
max-width: base(36);
}
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__button {
margin: 0;
}

View File

@@ -75,21 +75,23 @@ export const ResetPasswordClient: React.FC<Args> = ({ token }) => {
method="POST"
onSuccess={onSuccess}
>
<PasswordField
field={{
name: 'password',
label: i18n.t('authentication:newPassword'),
required: true,
}}
/>
<ConfirmPasswordField />
<HiddenField
field={{
name: 'token',
}}
forceUsePathFromProps
value={token}
/>
<div className={'inputWrap'}>
<PasswordField
field={{
name: 'password',
label: i18n.t('authentication:newPassword'),
required: true,
}}
/>
<ConfirmPasswordField />
<HiddenField
field={{
name: 'token',
}}
forceUsePathFromProps
value={token}
/>
</div>
<FormSubmit size="large">{i18n.t('authentication:resetPassword')}</FormSubmit>
</Form>
)

View File

@@ -1,5 +1,31 @@
@import '../../scss/styles.scss';
.reset-password {
form > .field-type {
margin-bottom: var(--base);
&__wrap {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: base(0.8);
max-width: base(36);
& > form {
width: 100%;
& > .inputWrap {
display: flex;
flex-direction: column;
gap: base(0.8);
> * {
margin: 0;
}
}
}
& > .btn {
margin: 0;
}
}
}

View File

@@ -1,11 +1,10 @@
import type { AdminViewProps } from 'payload'
import { Button, Translation } from '@payloadcms/ui'
import { formatAdminURL } from '@payloadcms/ui/shared'
import { Button } from '@payloadcms/ui'
import { formatAdminURL, Translation } from '@payloadcms/ui/shared'
import LinkImport from 'next/link.js'
import React from 'react'
import { MinimalTemplate } from '../../templates/Minimal/index.js'
import { ResetPasswordClient } from './index.client.js'
import './index.scss'
@@ -37,42 +36,37 @@ export const ResetPassword: React.FC<AdminViewProps> = ({ initPageResult, params
if (user) {
return (
<MinimalTemplate className={resetPasswordBaseClass}>
<div className={`${resetPasswordBaseClass}__wrap`}>
<h1>{i18n.t('authentication:alreadyLoggedIn')}</h1>
<p>
<Translation
elements={{
'0': ({ children }) => (
<Link
href={formatAdminURL({
adminRoute,
path: accountRoute,
})}
>
{children}
</Link>
),
}}
i18nKey="authentication:loggedInChangePassword"
t={i18n.t}
/>
</p>
<br />
<Button buttonStyle="secondary" el="link" Link={Link} to={adminRoute}>
{i18n.t('general:backToDashboard')}
</Button>
</div>
</MinimalTemplate>
<div className={`${resetPasswordBaseClass}__wrap`}>
<h1>{i18n.t('authentication:alreadyLoggedIn')}</h1>
<p>
<Translation
elements={{
'0': ({ children }) => (
<Link
href={formatAdminURL({
adminRoute,
path: accountRoute,
})}
>
{children}
</Link>
),
}}
i18nKey="authentication:loggedInChangePassword"
t={i18n.t}
/>
</p>
<Button buttonStyle="secondary" el="link" Link={Link} size="large" to={adminRoute}>
{i18n.t('general:backToDashboard')}
</Button>
</div>
)
}
return (
<MinimalTemplate className={resetPasswordBaseClass}>
<div className={`${resetPasswordBaseClass}__wrap`}>
<h1>{i18n.t('authentication:resetPassword')}</h1>
<ResetPasswordClient token={token} />
</div>
</MinimalTemplate>
<div className={`${resetPasswordBaseClass}__wrap`}>
<h1>{i18n.t('authentication:resetPassword')}</h1>
<ResetPasswordClient token={token} />
</div>
)
}

View File

@@ -38,24 +38,40 @@
@include blur-bg;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
&__toggle {
@extend %btn-reset;
}
}
.btn {
[dir='ltr'] & {
margin-right: var(--base);
}
[dir='rtl'] & {
margin-left: var(--base);
}
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__modal-template {
position: relative;
z-index: 1;
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -18,7 +18,6 @@ import { toast } from 'sonner'
import type { Props } from './types.js'
import { MinimalTemplate } from '../../../templates/Minimal/index.js'
import './index.scss'
const baseClass = 'restore-version'
@@ -36,11 +35,14 @@ const Restore: React.FC<Props> = ({
}) => {
const {
config: {
collections,
routes: { admin: adminRoute, api: apiRoute },
serverURL,
},
} = useConfig()
const collectionConfig = collections.find((collection) => collection.slug === collectionSlug)
const { toggleModal } = useModal()
const [processing, setProcessing] = useState(false)
const router = useRouter()
@@ -54,7 +56,8 @@ const Restore: React.FC<Props> = ({
let fetchURL = `${serverURL}${apiRoute}`
let redirectURL: string
const canRestoreAsDraft = status !== 'draft'
const canRestoreAsDraft = status !== 'draft' && collectionConfig?.versions?.drafts
if (collectionSlug) {
fetchURL = `${fetchURL}/${collectionSlug}/versions/${versionID}?draft=${draft}`
@@ -119,20 +122,25 @@ const Restore: React.FC<Props> = ({
)}
</div>
<Modal className={`${baseClass}__modal`} slug={modalSlug}>
<MinimalTemplate className={`${baseClass}__modal-template`}>
<h1>{t('version:confirmVersionRestoration')}</h1>
<p>{restoreMessage}</p>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(modalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button onClick={processing ? undefined : () => void handleRestore()}>
{processing ? t('version:restoring') : t('general:confirm')}
</Button>
</MinimalTemplate>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('version:confirmVersionRestoration')}</h1>
<p>{restoreMessage}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button onClick={processing ? undefined : () => void handleRestore()}>
{processing ? t('version:restoring') : t('general:confirm')}
</Button>
</div>
</div>
</Modal>
</Fragment>
)

View File

@@ -1,6 +1,6 @@
{
"name": "payload",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Node, React, Headless CMS and Application Framework built on Next.js",
"keywords": [
"admin panel",

View File

@@ -2,8 +2,6 @@ import type { TypedUser } from '../../index.js'
import type { PayloadRequest } from '../../types/index.js'
import type { Permissions } from '../types.js'
import { commitTransaction } from '../../utilities/commitTransaction.js'
import { initTransaction } from '../../utilities/initTransaction.js'
import { killTransaction } from '../../utilities/killTransaction.js'
import { executeAuthStrategies } from '../executeAuthStrategies.js'
import { getAccessResults } from '../getAccessResults.js'
@@ -25,8 +23,6 @@ export const auth = async (args: Required<AuthArgs>): Promise<AuthResult> => {
const { payload } = req
try {
const shouldCommit = await initTransaction(req)
const { responseHeaders, user } = await executeAuthStrategies({
headers,
payload,
@@ -39,10 +35,6 @@ export const auth = async (args: Required<AuthArgs>): Promise<AuthResult> => {
req,
})
if (shouldCommit) {
await commitTransaction(req)
}
return {
permissions,
responseHeaders,

View File

@@ -12,8 +12,6 @@ import type { User } from '../types.js'
import { buildAfterOperation } from '../../collections/operations/utils.js'
import { AuthenticationError, LockedAuth, ValidationError } from '../../errors/index.js'
import { afterRead } from '../../fields/hooks/afterRead/index.js'
import { commitTransaction } from '../../utilities/commitTransaction.js'
import { initTransaction } from '../../utilities/initTransaction.js'
import { killTransaction } from '../../utilities/killTransaction.js'
import sanitizeInternalFields from '../../utilities/sanitizeInternalFields.js'
import { getFieldsToSign } from '../getFieldsToSign.js'
@@ -43,8 +41,6 @@ export const loginOperation = async <TSlug extends CollectionSlug>(
let args = incomingArgs
try {
const shouldCommit = await initTransaction(args.req)
// /////////////////////////////////////
// beforeOperation - Collection
// /////////////////////////////////////
@@ -202,10 +198,6 @@ export const loginOperation = async <TSlug extends CollectionSlug>(
})
}
if (shouldCommit) {
await commitTransaction(req)
}
throw new AuthenticationError(req.t)
}
@@ -334,10 +326,6 @@ export const loginOperation = async <TSlug extends CollectionSlug>(
// Return results
// /////////////////////////////////////
if (shouldCommit) {
await commitTransaction(req)
}
return result
} catch (error: unknown) {
await killTransaction(args.req)

View File

@@ -132,24 +132,70 @@ export type LoginWithUsernameOptions =
}
export interface IncomingAuthType {
/**
* Set cookie options, including secure, sameSite, and domain. For advanced users.
*/
cookies?: {
domain?: string
sameSite?: 'Lax' | 'None' | 'Strict' | boolean
secure?: boolean
}
/**
* How many levels deep a user document should be populated when creating the JWT and binding the user to the req. Defaults to 0 and should only be modified if absolutely necessary, as this will affect performance.
* @default 0
*/
depth?: number
/**
* Advanced - disable Payload's built-in local auth strategy. Only use this property if you have replaced Payload's auth mechanisms with your own.
*/
disableLocalStrategy?: true
/**
* Customize the way that the forgotPassword operation functions.
* @link https://payloadcms.com/docs/beta/authentication/email#forgot-password
*/
forgotPassword?: {
generateEmailHTML?: GenerateForgotPasswordEmailHTML
generateEmailSubject?: GenerateForgotPasswordEmailSubject
}
/**
* Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than maxLoginAttempts allows for.
*/
lockTime?: number
/**
* Ability to allow users to login with username/password.
*
* @link https://payloadcms.com/docs/beta/authentication/overview#login-with-username
*/
loginWithUsername?: boolean | LoginWithUsernameOptions
/**
* Only allow a user to attempt logging in X amount of times. Automatically locks out a user from authenticating if this limit is passed. Set to 0 to disable.
*/
maxLoginAttempts?: number
/***
* Set to true if you want to remove the token from the returned authentication API responses such as login or refresh.
*/
removeTokenFromResponses?: true
/**
* Advanced - an array of custom authentification strategies to extend this collection's authentication with.
* @link https://payloadcms.com/docs/beta/authentication/custom-strategies
*/
strategies?: AuthStrategy[]
/**
* Controls how many seconds the token will be valid for. Default is 2 hours.
* @default 7200
* @link https://payloadcms.com/docs/beta/authentication/overview#config-options
*/
tokenExpiration?: number
/**
* Payload Authentication provides for API keys to be set on each user within an Authentication-enabled Collection.
* @default false
* @link https://payloadcms.com/docs/beta/authentication/api-keys
*/
useAPIKey?: boolean
/**
* Set to true or pass an object with verification options to require users to verify by email before they are allowed to log into your app.
* @link https://payloadcms.com/docs/beta/authentication/email#email-verification
*/
verify?:
| {
generateEmailHTML?: GenerateVerifyEmailHTML

View File

@@ -14,6 +14,7 @@ import baseVersionFields from '../../versions/baseFields.js'
import { versionDefaults } from '../../versions/defaults.js'
import { authDefaults, defaults, loginWithUsernameDefaults } from './defaults.js'
import { sanitizeAuthFields, sanitizeUploadFields } from './reservedFieldNames.js'
import { validateUseAsTitle } from './useAsTitle.js'
export const sanitizeCollection = async (
config: Config,
@@ -44,6 +45,8 @@ export const sanitizeCollection = async (
validRelationships,
})
validateUseAsTitle(sanitized)
if (sanitized.timestamps !== false) {
// add default timestamps fields only as needed
let hasUpdatedAt = null

View File

@@ -0,0 +1,204 @@
import type { Config } from '../../config/types.js'
import type { CollectionConfig } from '../../index.js'
import { InvalidConfiguration } from '../../errors/InvalidConfiguration.js'
import { sanitizeCollection } from './sanitize.js'
describe('sanitize - collections -', () => {
const config = {
collections: [],
globals: [],
} as Partial<Config>
describe('validate useAsTitle -', () => {
const defaultCollection: CollectionConfig = {
slug: 'collection-with-defaults',
fields: [
{
name: 'title',
type: 'text',
},
],
}
it('should throw on invalid field', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'invalidField',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).rejects.toThrow(InvalidConfiguration)
})
it('should not throw on valid field', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'title',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).not.toThrow()
})
it('should not throw on valid field inside tabs', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'title',
},
fields: [
{
type: 'tabs',
tabs: [
{
label: 'General',
fields: [
{
name: 'title',
type: 'text',
},
],
},
],
},
],
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).not.toThrow()
})
it('should not throw on valid field inside collapsibles', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'title',
},
fields: [
{
type: 'collapsible',
label: 'Collapsible',
fields: [
{
name: 'title',
type: 'text',
},
],
},
],
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).not.toThrow()
})
it('should throw on nested useAsTitle', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'content.title',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).rejects.toThrow(InvalidConfiguration)
})
it('should not throw on default field: id', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'id',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).not.toThrow()
})
it('should not throw on default field: email if auth is enabled', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
auth: true,
admin: {
useAsTitle: 'email',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).not.toThrow()
})
it('should throw on default field: email if auth is not enabled', async () => {
const collectionConfig: CollectionConfig = {
...defaultCollection,
admin: {
useAsTitle: 'email',
},
}
await expect(async () => {
await sanitizeCollection(
// @ts-expect-error
{
...config,
collections: [collectionConfig],
},
collectionConfig,
)
}).rejects.toThrow(InvalidConfiguration)
})
})
})

View File

@@ -0,0 +1,43 @@
import type { CollectionConfig } from '../../index.js'
import { InvalidConfiguration } from '../../errors/InvalidConfiguration.js'
import { fieldAffectsData } from '../../fields/config/types.js'
import flattenFields from '../../utilities/flattenTopLevelFields.js'
/**
* Validate useAsTitle for collections.
*/
export const validateUseAsTitle = (config: CollectionConfig) => {
if (config.admin.useAsTitle.includes('.')) {
throw new InvalidConfiguration(
`"useAsTitle" cannot be a nested field. Please specify a top-level field in the collection "${config.slug}"`,
)
}
if (config?.admin && config.admin?.useAsTitle && config.admin.useAsTitle !== 'id') {
const fields = flattenFields(config.fields)
const useAsTitleField = fields.find((field) => {
if (fieldAffectsData(field) && config.admin) {
return field.name === config.admin.useAsTitle
}
return false
})
// If auth is enabled then we don't need to
if (config.auth) {
if (config.admin.useAsTitle !== 'email') {
if (!useAsTitleField) {
throw new InvalidConfiguration(
`The field "${config.admin.useAsTitle}" specified in "admin.useAsTitle" does not exist in the collection "${config.slug}"`,
)
}
}
} else {
if (!useAsTitleField) {
throw new InvalidConfiguration(
`The field "${config.admin.useAsTitle}" specified in "admin.useAsTitle" does not exist in the collection "${config.slug}"`,
)
}
}
}
}

View File

@@ -136,8 +136,8 @@ const batchAndLoadDocs =
depth,
docID: doc.id,
draft,
fallbackLocale: req.fallbackLocale,
locale: req.locale,
fallbackLocale,
locale,
overrideAccess,
showHiddenFields,
transactionID: req.transactionID,

View File

@@ -1,15 +1,12 @@
import type { Document, Where } from '../../types/index.js'
import type { PreferenceRequest } from '../types.js'
import defaultAccess from '../../auth/defaultAccess.js'
import executeAccess from '../../auth/executeAccess.js'
import { NotFound } from '../../errors/NotFound.js'
import { UnauthorizedError } from '../../errors/UnathorizedError.js'
async function deleteOperation(args: PreferenceRequest): Promise<Document> {
export async function deleteOperation(args: PreferenceRequest): Promise<Document> {
const {
key,
overrideAccess,
req: { payload },
req,
user,
@@ -19,10 +16,6 @@ async function deleteOperation(args: PreferenceRequest): Promise<Document> {
throw new UnauthorizedError(req.t)
}
if (!overrideAccess) {
await executeAccess({ req }, defaultAccess)
}
const where: Where = {
and: [
{ key: { equals: key } },
@@ -42,5 +35,3 @@ async function deleteOperation(args: PreferenceRequest): Promise<Document> {
}
throw new NotFound(req.t)
}
export default deleteOperation

View File

@@ -2,7 +2,7 @@ import type { TypedCollection } from '../../index.js'
import type { Where } from '../../types/index.js'
import type { PreferenceRequest } from '../types.js'
async function findOne(args: PreferenceRequest): Promise<TypedCollection['_preference']> {
export async function findOne(args: PreferenceRequest): Promise<TypedCollection['_preference']> {
const {
key,
req: { payload },
@@ -22,11 +22,14 @@ async function findOne(args: PreferenceRequest): Promise<TypedCollection['_prefe
],
}
return await payload.db.findOne({
const { docs } = await payload.db.find({
collection: 'payload-preferences',
limit: 1,
pagination: false,
req,
sort: '-updatedAt',
where,
})
}
export default findOne
return docs?.[0] || null
}

View File

@@ -1,13 +1,11 @@
import type { Where } from '../../types/index.js'
import type { PreferenceUpdateRequest } from '../types.js'
import defaultAccess from '../../auth/defaultAccess.js'
import executeAccess from '../../auth/executeAccess.js'
import { UnauthorizedError } from '../../errors/UnathorizedError.js'
async function update(args: PreferenceUpdateRequest) {
export async function update(args: PreferenceUpdateRequest) {
const {
key,
overrideAccess,
req: { payload },
req,
user,
@@ -20,10 +18,12 @@ async function update(args: PreferenceUpdateRequest) {
const collection = 'payload-preferences'
const filter = {
key: { equals: key },
'user.relationTo': { equals: user.collection },
'user.value': { equals: user.id },
const where: Where = {
and: [
{ key: { equals: key } },
{ 'user.value': { equals: user.id } },
{ 'user.relationTo': { equals: user.collection } },
],
}
const preference = {
@@ -35,27 +35,23 @@ async function update(args: PreferenceUpdateRequest) {
value,
}
if (!overrideAccess) {
await executeAccess({ req }, defaultAccess)
}
let result
try {
// try/catch because we attempt to update without first reading to check if it exists first to save on db calls
await payload.db.updateOne({
result = await payload.db.updateOne({
collection,
data: preference,
req,
where: filter,
where,
})
} catch (err: unknown) {
await payload.db.create({
result = await payload.db.create({
collection,
data: preference,
req,
})
}
return preference
return result
}
export default update

View File

@@ -3,7 +3,7 @@ import httpStatus from 'http-status'
import type { PayloadHandler } from '../../config/types.js'
import type { PayloadRequest } from '../../types/index.js'
import deleteOperation from '../operations/delete.js'
import { deleteOperation } from '../operations/delete.js'
export const deleteHandler: PayloadHandler = async (incomingReq): Promise<Response> => {
// We cannot import the addDataAndFileToRequest utility here from the 'next' package because of dependency issues

View File

@@ -3,7 +3,7 @@ import httpStatus from 'http-status'
import type { PayloadHandler } from '../../config/types.js'
import type { PayloadRequest } from '../../types/index.js'
import findOne from '../operations/findOne.js'
import { findOne } from '../operations/findOne.js'
export const findByIDHandler: PayloadHandler = async (incomingReq): Promise<Response> => {
// We cannot import the addDataAndFileToRequest utility here from the 'next' package because of dependency issues

View File

@@ -3,7 +3,7 @@ import httpStatus from 'http-status'
import type { PayloadHandler } from '../../config/types.js'
import type { PayloadRequest } from '../../types/index.js'
import update from '../operations/update.js'
import { update } from '../operations/update.js'
export const updateHandler: PayloadHandler = async (incomingReq) => {
// We cannot import the addDataAndFileToRequest utility here from the 'next' package because of dependency issues

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-cloud-storage",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official cloud storage plugin for Payload CMS",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-cloud",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official Payload Cloud plugin",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-form-builder",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Form builder plugin for Payload CMS",
"keywords": [
"payload",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-nested-docs",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The official Nested Docs plugin for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-redirects",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Redirects plugin for Payload",
"keywords": [
"payload",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-relationship-object-ids",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "A Payload plugin to store all relationship IDs as ObjectIDs",
"repository": {
"type": "git",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-search",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Search plugin for Payload",
"keywords": [
"payload",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-seo",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "SEO plugin for Payload",
"keywords": [
"payload",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/plugin-stripe",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Stripe plugin for Payload",
"keywords": [
"payload",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/richtext-lexical",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The officially supported Lexical richtext adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/richtext-slate",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "The officially supported Slate richtext adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/storage-azure",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload storage adapter for Azure Blob Storage",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/storage-gcs",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload storage adapter for Google Cloud Storage",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/storage-s3",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload storage adapter for Amazon S3",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/storage-uploadthing",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload storage adapter for uploadthing",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/storage-vercel-blob",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"description": "Payload storage adapter for Vercel Blob Storage",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/translations",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/ui",
"version": "3.0.0-beta.98",
"version": "3.0.0-beta.101",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -82,12 +82,12 @@
background-color: var(--theme-elevation-100);
}
img {
width: 25px;
height: 25px;
.thumbnail {
width: base(1.2);
height: base(1.2);
flex-shrink: 0;
object-fit: cover;
border-radius: var(--style-radius-m);
border-radius: var(--style-radius-s);
}
p {

View File

@@ -2,6 +2,7 @@
import { useModal } from '@faceless-ui/modal'
import { useWindowInfo } from '@faceless-ui/window-info'
import { isImage } from 'payload/shared'
import React from 'react'
import AnimateHeightImport from 'react-animate-height'
@@ -13,6 +14,7 @@ import { Drawer } from '../../Drawer/index.js'
import { ErrorPill } from '../../ErrorPill/index.js'
import { Pill } from '../../Pill/index.js'
import { ShimmerEffect } from '../../ShimmerEffect/index.js'
import { Thumbnail } from '../../Thumbnail/index.js'
import { Actions } from '../ActionsBar/index.js'
import { AddFilesView } from '../AddFilesView/index.js'
import { useFormsManager } from '../FormsManager/index.js'
@@ -144,7 +146,12 @@ export function FileSidebar() {
onClick={() => setActiveIndex(index)}
type="button"
>
<img alt={currentFile.name} src={URL.createObjectURL(currentFile)} />
<Thumbnail
className={`${baseClass}__thumbnail`}
fileSrc={
isImage(currentFile.type) ? URL.createObjectURL(currentFile) : undefined
}
/>
<div className={`${baseClass}__fileDetails`}>
<p className={`${baseClass}__fileName`} title={currentFile.name}>
{currentFile.name}

View File

@@ -4,26 +4,39 @@
@include blur-bg;
display: flex;
align-items: center;
height: 100%;
justify-content: center;
padding: base(2);
&__template {
z-index: 1;
position: relative;
}
height: 100%;
&__toggle {
@extend %btn-reset;
}
.btn {
margin: 0;
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
&__actions {
&__content {
display: flex;
flex-wrap: wrap;
gap: $baseline;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -129,31 +129,38 @@ export const DeleteDocument: React.FC<Props> = (props) => {
{t('general:delete')}
</PopupList.Button>
<Modal className={baseClass} slug={modalSlug}>
<div className={`${baseClass}__template`}>
<h1>{t('general:confirmDeletion')}</h1>
<p>
<Translation
elements={{
'1': ({ children }) => <strong>{children}</strong>,
}}
i18nKey="general:aboutToDelete"
t={t}
variables={{
label: getTranslation(singularLabel, i18n),
title: titleToRender,
}}
/>
</p>
<div className={`${baseClass}__actions`}>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('general:confirmDeletion')}</h1>
<p>
<Translation
elements={{
'1': ({ children }) => <strong>{children}</strong>,
}}
i18nKey="general:aboutToDelete"
t={t}
variables={{
label: getTranslation(singularLabel, i18n),
title: titleToRender,
}}
/>
</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={deleting ? undefined : () => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-delete" onClick={deleting ? undefined : handleDelete}>
<Button
id="confirm-delete"
onClick={deleting ? undefined : handleDelete}
size="large"
>
{deleting ? t('general:deleting') : t('general:confirm')}
</Button>
</div>

View File

@@ -4,16 +4,35 @@
@include blur-bg;
display: flex;
align-items: center;
height: 100%;
justify-content: center;
padding: base(2);
height: 100%;
&__template {
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
.btn {
margin-right: $baseline;
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -125,20 +125,25 @@ export const DeleteMany: React.FC<Props> = (props) => {
{t('general:delete')}
</Pill>
<Modal className={baseClass} slug={modalSlug}>
<div className={`${baseClass}__template`}>
<h1>{t('general:confirmDeletion')}</h1>
<p>{t('general:aboutToDeleteCount', { count, label: getTranslation(plural, i18n) })}</p>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={deleting ? undefined : () => toggleModal(modalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-delete" onClick={deleting ? undefined : handleDelete}>
{deleting ? t('general:deleting') : t('general:confirm')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('general:confirmDeletion')}</h1>
<p>{t('general:aboutToDeleteCount', { count, label: getTranslation(plural, i18n) })}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={deleting ? undefined : () => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-delete" onClick={deleting ? undefined : handleDelete} size="large">
{deleting ? t('general:deleting') : t('general:confirm')}
</Button>
</div>
</div>
</Modal>
</React.Fragment>

View File

@@ -5,16 +5,36 @@
@include blur-bg;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
padding: base(2);
}
.btn {
margin-right: $baseline;
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__modal-template {
z-index: 1;
position: relative;
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -118,20 +118,25 @@ export const DuplicateDocument: React.FC<Props> = ({ id, slug, singularLabel })
</PopupList.Button>
{modified && hasClicked && (
<Modal className={`${baseClass}__modal`} slug={modalSlug}>
<div className={`${baseClass}__modal-template`}>
<h1>{t('general:confirmDuplication')}</h1>
<p>{t('general:unsavedChangesDuplicate')}</p>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={() => toggleModal(modalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-duplicate" onClick={() => void confirm()}>
{t('general:duplicateWithoutSaving')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('general:confirmDuplication')}</h1>
<p>{t('general:unsavedChangesDuplicate')}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={() => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-duplicate" onClick={() => void confirm()} size="large">
{t('general:duplicateWithoutSaving')}
</Button>
</div>
</div>
</Modal>
)}

View File

@@ -6,14 +6,33 @@
align-items: center;
justify-content: center;
height: 100%;
padding: base(2);
&__template {
position: relative;
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
.btn {
margin-right: $baseline;
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -44,28 +44,32 @@ export const GenerateConfirmation: React.FC<GenerateConfirmationProps> = (props)
{t('authentication:generateNewAPIKey')}
</Button>
<Modal className={baseClass} slug={modalSlug}>
<div className={`${baseClass}__template`}>
<h1>{t('authentication:confirmGeneration')}</h1>
<p>
<Translation
elements={{
1: ({ children }) => <strong>{children}</strong>,
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('authentication:confirmGeneration')}</h1>
<p>
<Translation
elements={{
1: ({ children }) => <strong>{children}</strong>,
}}
i18nKey="authentication:generatingNewAPIKeyWillInvalidate"
t={t}
/>
</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
onClick={() => {
toggleModal(modalSlug)
}}
i18nKey="authentication:generatingNewAPIKeyWillInvalidate"
t={t}
/>
</p>
<Button
buttonStyle="secondary"
onClick={() => {
toggleModal(modalSlug)
}}
type="button"
>
{t('general:cancel')}
</Button>
<Button onClick={handleGenerate}>{t('authentication:generate')}</Button>
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button onClick={handleGenerate}>{t('authentication:generate')}</Button>
</div>
</div>
</Modal>
</React.Fragment>

View File

@@ -14,7 +14,6 @@ import { ChevronIcon } from '../../icons/Chevron/index.js'
import { SearchIcon } from '../../icons/Search/index.js'
import { useListInfo } from '../../providers/ListInfo/index.js'
import { useListQuery } from '../../providers/ListQuery/index.js'
import { useSearchParams } from '../../providers/SearchParams/index.js'
import { useTranslation } from '../../providers/Translation/index.js'
import { ColumnSelector } from '../ColumnSelector/index.js'
import { DeleteMany } from '../DeleteMany/index.js'
@@ -48,17 +47,13 @@ export type ListControlsProps = {
export const ListControls: React.FC<ListControlsProps> = (props) => {
const { collectionConfig, enableColumns = true, enableSort = false, fields } = props
const { handleSearchChange } = useListQuery()
const { handleSearchChange, params } = useListQuery()
const { beforeActions, collectionSlug, disableBulkDelete, disableBulkEdit } = useListInfo()
const { searchParams } = useSearchParams()
const titleField = useUseTitleField(collectionConfig, fields)
const { i18n, t } = useTranslation()
const {
breakpoints: { s: smallBreak },
} = useWindowInfo()
const [search, setSearch] = useState(
typeof searchParams?.search === 'string' ? searchParams?.search : '',
)
const searchLabel =
(titleField &&
@@ -81,21 +76,21 @@ export const ListControls: React.FC<ListControlsProps> = (props) => {
t('general:searchBy', { label: getTranslation(searchLabel, i18n) }),
)
const hasWhereParam = useRef(Boolean(searchParams?.where))
const hasWhereParam = useRef(Boolean(params?.where))
const shouldInitializeWhereOpened = validateWhereQuery(searchParams?.where)
const shouldInitializeWhereOpened = validateWhereQuery(params?.where)
const [visibleDrawer, setVisibleDrawer] = useState<'columns' | 'sort' | 'where'>(
shouldInitializeWhereOpened ? 'where' : undefined,
)
useEffect(() => {
if (hasWhereParam.current && !searchParams?.where) {
if (hasWhereParam.current && !params?.where) {
setVisibleDrawer(undefined)
hasWhereParam.current = false
} else if (searchParams?.where) {
} else if (params?.where) {
hasWhereParam.current = true
}
}, [setVisibleDrawer, searchParams?.where])
}, [setVisibleDrawer, params?.where])
useEffect(() => {
if (listSearchableFields?.length > 0) {
@@ -134,11 +129,10 @@ export const ListControls: React.FC<ListControlsProps> = (props) => {
handleChange={(search) => {
return void handleSearchChange(search)
}}
initialParams={searchParams}
// @ts-expect-error @todo: fix types
initialParams={params}
key={collectionSlug}
label={searchLabelTranslated.current}
setValue={setSearch}
value={search}
/>
<div className={`${baseClass}__buttons`}>
<div className={`${baseClass}__buttons-wrap`}>
@@ -216,7 +210,7 @@ export const ListControls: React.FC<ListControlsProps> = (props) => {
collectionPluralLabel={collectionConfig?.labels?.plural}
collectionSlug={collectionConfig.slug}
fields={fields}
key={String(hasWhereParam.current && !searchParams?.where)}
key={String(hasWhereParam.current && !params?.where)}
/>
</AnimateHeight>
{enableSort && (

View File

@@ -3,13 +3,14 @@ import type { ClientCollectionConfig, Where } from 'payload'
import { useModal } from '@faceless-ui/modal'
import { getTranslation } from '@payloadcms/translations'
import React, { useCallback, useEffect, useReducer, useState } from 'react'
import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react'
import type { ListDrawerProps } from './types.js'
import { SelectMany } from '../../elements/SelectMany/index.js'
import { FieldLabel } from '../../fields/FieldLabel/index.js'
import { usePayloadAPI } from '../../hooks/usePayloadAPI.js'
import { useThrottledEffect } from '../../hooks/useThrottledEffect.js'
import { XIcon } from '../../icons/X/index.js'
import { useAuth } from '../../providers/Auth/index.js'
import { useConfig } from '../../providers/Config/index.js'
@@ -54,13 +55,25 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
}) => {
const { i18n, t } = useTranslation()
const { permissions } = useAuth()
const { setPreference } = usePreferences()
const { getPreference, setPreference } = usePreferences()
const { closeModal, isModalOpen } = useModal()
const [limit, setLimit] = useState<number>()
// Track the page limit so we can reset the page number when it changes
const previousLimit = useRef<number>(limit || null)
const [sort, setSort] = useState<string>(null)
const [page, setPage] = useState<number>(1)
const [where, setWhere] = useState<Where>(null)
const [search, setSearch] = useState<string>('')
const [showLoadingOverlay, setShowLoadingOverlay] = useState<boolean>(true)
const hasInitialised = useRef(false)
const params = {
limit,
page,
search,
sort,
where,
}
const {
config: {
@@ -94,12 +107,6 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
: undefined,
)
// const [fields, setFields] = useState<Field[]>(() => formatFields(selectedCollectionConfig))
useEffect(() => {
// setFields(formatFields(selectedCollectionConfig))
}, [selectedCollectionConfig])
// allow external control of selected collection, same as the initial state logic above
useEffect(() => {
if (selectedCollection) {
@@ -111,7 +118,7 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
}
}, [selectedCollection, enabledCollectionConfigs, onSelect, t])
const preferenceKey = `${selectedCollectionConfig.slug}-list`
const preferencesKey = `${selectedCollectionConfig.slug}-list`
// this is the 'create new' drawer
const [DocumentDrawer, DocumentDrawerToggler, { drawerSlug: documentDrawerSlug }] =
@@ -147,6 +154,7 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
admin: { listSearchableFields, useAsTitle } = {},
versions,
} = selectedCollectionConfig
const params: {
cacheBust?: number
depth?: number
@@ -194,6 +202,17 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
if (cacheBust) {
params.cacheBust = cacheBust
}
if (limit) {
params.limit = limit
if (limit !== previousLimit.current) {
previousLimit.current = limit
// Reset page if limit changes
// eslint-disable-next-line @eslint-react/hooks-extra/no-direct-set-state-in-use-effect
setPage(1)
}
}
if (copyOfWhere) {
params.where = copyOfWhere
}
@@ -202,7 +221,18 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
}
setParams(params)
}, [page, sort, where, search, cacheBust, filterOptions, selectedCollectionConfig, t, setParams])
}, [
page,
sort,
where,
search,
limit,
cacheBust,
filterOptions,
selectedCollectionConfig,
t,
setParams,
])
useEffect(() => {
const newPreferences = {
@@ -210,8 +240,49 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
sort,
}
void setPreference(preferenceKey, newPreferences, true)
}, [sort, limit, setPreference, preferenceKey])
if (limit || sort) {
void setPreference(preferencesKey, newPreferences, true)
}
}, [sort, limit, setPreference, preferencesKey])
// Get existing preferences if they exist
useEffect(() => {
if (preferencesKey && !limit) {
const getInitialPref = async () => {
const existingPreferences = await getPreference<{ limit?: number }>(preferencesKey)
if (existingPreferences?.limit) {
setLimit(existingPreferences?.limit)
}
}
void getInitialPref()
}
}, [getPreference, limit, preferencesKey])
useThrottledEffect(
() => {
if (isLoadingList) {
setShowLoadingOverlay(true)
}
},
1750,
[isLoadingList, setShowLoadingOverlay],
)
useEffect(() => {
if (isOpen) {
hasInitialised.current = true
} else {
hasInitialised.current = false
}
}, [isOpen])
useEffect(() => {
if (!isLoadingList && showLoadingOverlay) {
// eslint-disable-next-line @eslint-react/hooks-extra/no-direct-set-state-in-use-effect
setShowLoadingOverlay(false)
}
}, [isLoadingList, showLoadingOverlay])
const onCreateNew = useCallback(
({ doc }) => {
@@ -232,108 +303,111 @@ export const ListDrawerContent: React.FC<ListDrawerProps> = ({
return null
}
if (isLoadingList) {
return <LoadingOverlay />
}
return (
<ListInfoProvider
beforeActions={
enableRowSelections ? [<SelectMany key="select-many" onClick={onBulkSelect} />] : undefined
}
collectionConfig={selectedCollectionConfig}
collectionSlug={selectedCollectionConfig.slug}
disableBulkDelete
disableBulkEdit
hasCreatePermission={hasCreatePermission}
Header={
<header className={`${baseClass}__header`}>
<div className={`${baseClass}__header-wrap`}>
<div className={`${baseClass}__header-content`}>
<h2 className={`${baseClass}__header-text`}>
{!customHeader
? getTranslation(selectedCollectionConfig?.labels?.plural, i18n)
: customHeader}
</h2>
{hasCreatePermission && (
<DocumentDrawerToggler className={`${baseClass}__create-new-button`}>
<Pill>{t('general:createNew')}</Pill>
</DocumentDrawerToggler>
)}
<>
{showLoadingOverlay && <LoadingOverlay />}
<ListInfoProvider
beforeActions={
enableRowSelections
? [<SelectMany key="select-many" onClick={onBulkSelect} />]
: undefined
}
collectionConfig={selectedCollectionConfig}
collectionSlug={selectedCollectionConfig.slug}
disableBulkDelete
disableBulkEdit
hasCreatePermission={hasCreatePermission}
Header={
<header className={`${baseClass}__header`}>
<div className={`${baseClass}__header-wrap`}>
<div className={`${baseClass}__header-content`}>
<h2 className={`${baseClass}__header-text`}>
{!customHeader
? getTranslation(selectedCollectionConfig?.labels?.plural, i18n)
: customHeader}
</h2>
{hasCreatePermission && (
<DocumentDrawerToggler className={`${baseClass}__create-new-button`}>
<Pill>{t('general:createNew')}</Pill>
</DocumentDrawerToggler>
)}
</div>
<button
aria-label={t('general:close')}
className={`${baseClass}__header-close`}
onClick={() => {
closeModal(drawerSlug)
}}
type="button"
>
<XIcon />
</button>
</div>
<button
aria-label={t('general:close')}
className={`${baseClass}__header-close`}
onClick={() => {
closeModal(drawerSlug)
}}
type="button"
>
<XIcon />
</button>
</div>
{(selectedCollectionConfig?.admin?.description ||
selectedCollectionConfig?.admin?.components?.Description) && (
<div className={`${baseClass}__sub-header`}>
<ViewDescription
Description={selectedCollectionConfig.admin?.components?.Description}
description={selectedCollectionConfig.admin?.description}
/>
</div>
)}
{moreThanOneAvailableCollection && (
<div className={`${baseClass}__select-collection-wrap`}>
<FieldLabel field={null} label={t('upload:selectCollectionToBrowse')} />
<ReactSelect
className={`${baseClass}__select-collection`}
onChange={setSelectedOption} // this is only changing the options which is not rerunning my effect
options={enabledCollectionConfigs.map((coll) => ({
label: getTranslation(coll.labels.singular, i18n),
value: coll.slug,
}))}
value={selectedOption}
/>
</div>
)}
</header>
}
newDocumentURL={null}
>
<ListQueryProvider
data={data}
defaultLimit={limit || selectedCollectionConfig?.admin?.pagination?.defaultLimit}
defaultSort={sort}
handlePageChange={setPage}
handlePerPageChange={setLimit}
handleSearchChange={setSearch}
handleSortChange={setSort}
handleWhereChange={setWhere}
modifySearchParams={false}
preferenceKey={preferenceKey}
{(selectedCollectionConfig?.admin?.description ||
selectedCollectionConfig?.admin?.components?.Description) && (
<div className={`${baseClass}__sub-header`}>
<ViewDescription
Description={selectedCollectionConfig.admin?.components?.Description}
description={selectedCollectionConfig.admin?.description}
/>
</div>
)}
{moreThanOneAvailableCollection && (
<div className={`${baseClass}__select-collection-wrap`}>
<FieldLabel field={null} label={t('upload:selectCollectionToBrowse')} />
<ReactSelect
className={`${baseClass}__select-collection`}
onChange={setSelectedOption} // this is only changing the options which is not rerunning my effect
options={enabledCollectionConfigs.map((coll) => ({
label: getTranslation(coll.labels.singular, i18n),
value: coll.slug,
}))}
value={selectedOption}
/>
</div>
)}
</header>
}
newDocumentURL={null}
>
<TableColumnsProvider
cellProps={[
{
className: `${baseClass}__first-cell`,
link: false,
onClick: ({ collectionSlug: rowColl, rowData }) => {
if (typeof onSelect === 'function') {
onSelect({
collectionSlug: rowColl,
docID: rowData.id as string,
})
}
},
},
]}
collectionSlug={selectedCollectionConfig.slug}
enableRowSelections={enableRowSelections}
preferenceKey={preferenceKey}
<ListQueryProvider
data={data}
defaultLimit={limit || selectedCollectionConfig?.admin?.pagination?.defaultLimit}
defaultSort={sort}
handlePageChange={setPage}
handlePerPageChange={setLimit}
handleSearchChange={setSearch}
handleSortChange={setSort}
handleWhereChange={setWhere}
modifySearchParams={false}
// @ts-expect-error todo: fix types
params={params}
preferenceKey={preferencesKey}
>
<RenderComponent mappedComponent={List} />
<DocumentDrawer onSave={onCreateNew} />
</TableColumnsProvider>
</ListQueryProvider>
</ListInfoProvider>
<TableColumnsProvider
cellProps={[
{
className: `${baseClass}__first-cell`,
link: false,
onClick: ({ collectionSlug: rowColl, rowData }) => {
if (typeof onSelect === 'function') {
onSelect({
collectionSlug: rowColl,
docID: rowData.id as string,
})
}
},
},
]}
collectionSlug={selectedCollectionConfig.slug}
enableRowSelections={enableRowSelections}
preferenceKey={preferencesKey}
>
<RenderComponent mappedComponent={List} />
<DocumentDrawer onSave={onCreateNew} />
</TableColumnsProvider>
</ListQueryProvider>
</ListInfoProvider>
</>
)
}

View File

@@ -4,15 +4,34 @@
@include blur-bg;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
padding: base(2);
&__template {
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
}
.btn {
margin-right: $baseline;
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -127,20 +127,29 @@ export const PublishMany: React.FC<PublishManyProps> = (props) => {
{t('version:publish')}
</Pill>
<Modal className={baseClass} slug={modalSlug}>
<div className={`${baseClass}__template`}>
<h1>{t('version:confirmPublish')}</h1>
<p>{t('version:aboutToPublishSelection', { label: getTranslation(plural, i18n) })}</p>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={submitted ? undefined : () => toggleModal(modalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-publish" onClick={submitted ? undefined : handlePublish}>
{submitted ? t('version:publishing') : t('general:confirm')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('version:confirmPublish')}</h1>
<p>{t('version:aboutToPublishSelection', { label: getTranslation(plural, i18n) })}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={submitted ? undefined : () => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button
id="confirm-publish"
onClick={submitted ? undefined : handlePublish}
size="large"
>
{submitted ? t('version:publishing') : t('general:confirm')}
</Button>
</div>
</div>
</Modal>
</React.Fragment>

View File

@@ -7,6 +7,11 @@ type CustomSelectProps = {
disableMouseDown?: boolean
draggableProps?: any
droppableRef?: React.RefObject<HTMLDivElement | null>
onDocumentDrawerOpen: (args: {
collectionSlug: string
hasReadPermission: boolean
id: number | string
}) => void
onSave?: DocumentDrawerProps['onSave']
setDrawerIsOpen?: (isOpen: boolean) => void
}

View File

@@ -1,5 +1,5 @@
'use client'
import React, { useEffect, useRef } from 'react'
import React, { useEffect, useRef, useState } from 'react'
export type SearchFilterProps = {
fieldName?: string
@@ -12,32 +12,53 @@ export type SearchFilterProps = {
import type { ParsedQs } from 'qs-esm'
import { usePathname } from 'next/navigation.js'
import { useDebounce } from '../../hooks/useDebounce.js'
import './index.scss'
const baseClass = 'search-filter'
export const SearchFilter: React.FC<SearchFilterProps> = (props) => {
const { handleChange, initialParams, label, setValue, value } = props
const previousSearch = useRef(
typeof initialParams?.search === 'string' ? initialParams?.search : '',
const { handleChange, initialParams, label } = props
const pathname = usePathname()
const [search, setSearch] = useState(
typeof initialParams?.search === 'string' ? initialParams?.search : undefined,
)
const debouncedSearch = useDebounce(value, 300)
/**
* Tracks whether the state should be updated based on the search value.
* If the value is updated from the URL, we don't want to update the state as it causes additional renders.
*/
const shouldUpdateState = useRef(true)
/**
* Tracks the previous search value to compare with the current debounced search value.
*/
const previousSearch = useRef(
typeof initialParams?.search === 'string' ? initialParams?.search : undefined,
)
const debouncedSearch = useDebounce(search, 300)
useEffect(() => {
if (debouncedSearch !== previousSearch.current) {
if (initialParams?.search !== previousSearch.current) {
shouldUpdateState.current = false
// eslint-disable-next-line @eslint-react/hooks-extra/no-direct-set-state-in-use-effect
setSearch(initialParams?.search as string)
previousSearch.current = initialParams?.search as string
}
}, [initialParams?.search, pathname])
useEffect(() => {
if (debouncedSearch !== previousSearch.current && shouldUpdateState.current) {
if (handleChange) {
handleChange(debouncedSearch)
}
previousSearch.current = debouncedSearch
}
}, [debouncedSearch, previousSearch, handleChange])
// Cleans up the search input when the component is unmounted
useEffect(() => () => setValue(''), [])
}, [debouncedSearch, handleChange])
return (
<div className={baseClass}>
@@ -45,10 +66,13 @@ export const SearchFilter: React.FC<SearchFilterProps> = (props) => {
aria-label={label}
className={`${baseClass}__input`}
id="search-filter-input"
onChange={(e) => setValue(e.target.value)}
onChange={(e) => {
shouldUpdateState.current = true
setSearch(e.target.value)
}}
placeholder={label}
type="text"
value={value || ''}
value={search || ''}
/>
</div>
)

View File

@@ -5,7 +5,6 @@ import React from 'react'
import { ChevronIcon } from '../../icons/Chevron/index.js'
import { useListQuery } from '../../providers/ListQuery/index.js'
import { useSearchParams } from '../../providers/SearchParams/index.js'
import { useTranslation } from '../../providers/Translation/index.js'
import './index.scss'
@@ -20,11 +19,10 @@ const baseClass = 'sort-column'
export const SortColumn: React.FC<SortColumnProps> = (props) => {
const { name, disable = false, Label, label } = props
const { searchParams } = useSearchParams()
const { handleSortChange } = useListQuery()
const { handleSortChange, params } = useListQuery()
const { t } = useTranslation()
const { sort } = searchParams
const { sort } = params
const desc = `-${name}`
const asc = name

View File

@@ -20,22 +20,41 @@
&__modal {
@include blur-bg;
display: flex;
justify-content: center;
align-items: center;
justify-content: center;
height: 100%;
padding: base(2);
&__toggle {
@extend %btn-reset;
}
}
.btn {
margin-right: $baseline;
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
max-width: base(36);
}
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__modal-template {
position: relative;
z-index: 1;
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -152,19 +152,27 @@ export const Status: React.FC = () => {
{t('version:unpublish')}
</Button>
<Modal className={`${baseClass}__modal`} slug={unPublishModalSlug}>
<div className={`${baseClass}__modal-template`}>
<h1>{t('version:confirmUnpublish')}</h1>
<p>{t('version:aboutToUnpublish')}</p>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(unPublishModalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button onClick={processing ? undefined : () => performAction('unpublish')}>
{t(processing ? 'version:unpublishing' : 'general:confirm')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('version:confirmUnpublish')}</h1>
<p>{t('version:aboutToUnpublish')}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(unPublishModalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button
onClick={processing ? undefined : () => performAction('unpublish')}
size="large"
>
{t(processing ? 'version:unpublishing' : 'general:confirm')}
</Button>
</div>
</div>
</Modal>
</React.Fragment>
@@ -181,22 +189,28 @@ export const Status: React.FC = () => {
{t('version:revertToPublished')}
</Button>
<Modal className={`${baseClass}__modal`} slug={revertModalSlug}>
<div className={`${baseClass}__modal-template`}>
<h1>{t('version:confirmRevertToSaved')}</h1>
<p>{t('version:aboutToRevertToPublished')}</p>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(revertModalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button
id="action-revert-to-published-confirm"
onClick={processing ? undefined : () => performAction('revert')}
>
{t(processing ? 'version:reverting' : 'general:confirm')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('version:confirmRevertToSaved')}</h1>
<p>{t('version:aboutToRevertToPublished')}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
onClick={processing ? undefined : () => toggleModal(revertModalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button
id="action-revert-to-published-confirm"
onClick={processing ? undefined : () => performAction('revert')}
size="large"
>
{t(processing ? 'version:reverting' : 'general:confirm')}
</Button>
</div>
</div>
</Modal>
</React.Fragment>

View File

@@ -1,4 +1,3 @@
'use client'
import type { ClientTranslationKeys, TFunction } from '@payloadcms/translations'
import * as React from 'react'

View File

@@ -4,15 +4,34 @@
@include blur-bg;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
padding: base(2);
&__template {
&__wrapper {
z-index: 1;
position: relative;
display: flex;
flex-direction: column;
gap: base(0.8);
padding: base(2);
}
.btn {
margin-right: $baseline;
&__content {
display: flex;
flex-direction: column;
gap: base(0.4);
> * {
margin: 0;
}
}
&__controls {
display: flex;
gap: base(0.4);
.btn {
margin: 0;
}
}
}

View File

@@ -124,20 +124,29 @@ export const UnpublishMany: React.FC<UnpublishManyProps> = (props) => {
{t('version:unpublish')}
</Pill>
<Modal className={baseClass} slug={modalSlug}>
<div className={`${baseClass}__template`}>
<h1>{t('version:confirmUnpublish')}</h1>
<p>{t('version:aboutToUnpublishSelection', { label: getTranslation(plural, i18n) })}</p>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={submitted ? undefined : () => toggleModal(modalSlug)}
type="button"
>
{t('general:cancel')}
</Button>
<Button id="confirm-unpublish" onClick={submitted ? undefined : handleUnpublish}>
{submitted ? t('version:unpublishing') : t('general:confirm')}
</Button>
<div className={`${baseClass}__wrapper`}>
<div className={`${baseClass}__content`}>
<h1>{t('version:confirmUnpublish')}</h1>
<p>{t('version:aboutToUnpublishSelection', { label: getTranslation(plural, i18n) })}</p>
</div>
<div className={`${baseClass}__controls`}>
<Button
buttonStyle="secondary"
id="confirm-cancel"
onClick={submitted ? undefined : () => toggleModal(modalSlug)}
size="large"
type="button"
>
{t('general:cancel')}
</Button>
<Button
id="confirm-unpublish"
onClick={submitted ? undefined : handleUnpublish}
size="large"
>
{submitted ? t('version:unpublishing') : t('general:confirm')}
</Button>
</div>
</div>
</Modal>
</React.Fragment>

View File

@@ -91,6 +91,8 @@
&__dropzoneContent {
display: flex;
flex-wrap: wrap;
gap: base(0.4);
justify-content: space-between;
width: 100%;
}
@@ -106,6 +108,7 @@
}
&__dragAndDropText {
flex-shrink: 0;
margin: 0;
text-transform: lowercase;
align-self: center;

View File

@@ -7,7 +7,6 @@ import React, { useEffect, useState } from 'react'
import type { WhereBuilderProps } from './types.js'
import { useListQuery } from '../../providers/ListQuery/index.js'
import { useSearchParams } from '../../providers/SearchParams/index.js'
import { useTranslation } from '../../providers/Translation/index.js'
import { Button } from '../Button/index.js'
import { Condition } from './Condition/index.js'
@@ -31,11 +30,11 @@ export const WhereBuilder: React.FC<WhereBuilderProps> = (props) => {
const [reducedFields, setReducedColumns] = useState(() => reduceClientFields({ fields, i18n }))
useEffect(() => {
// eslint-disable-next-line @eslint-react/hooks-extra/no-direct-set-state-in-use-effect
setReducedColumns(reduceClientFields({ fields, i18n }))
}, [fields, i18n])
const { searchParams } = useSearchParams()
const { handleWhereChange } = useListQuery()
const { handleWhereChange, params } = useListQuery()
const [shouldUpdateQuery, setShouldUpdateQuery] = React.useState(false)
// This handles initializing the where conditions from the search query (URL). That way, if you pass in
@@ -67,7 +66,7 @@ export const WhereBuilder: React.FC<WhereBuilderProps> = (props) => {
*/
const [conditions, setConditions] = React.useState(() => {
const whereFromSearch = searchParams.where
const whereFromSearch = params.where
if (whereFromSearch) {
if (validateWhereQuery(whereFromSearch)) {
return whereFromSearch.or

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