Commit Graph

5199 Commits

Author SHA1 Message Date
Elliot DeNolf
bb14cc9b41 chore(release): v3.30.0 [skip ci] 2025-03-24 09:59:42 -04:00
Sasha
1b2b6a1b15 fix: respect draft: true when querying docs for the join field (#11763)
Previously, if you were querying a collection that has a join field with
`draft: true`, and the join field's collection also has
`versions.drafts: true` our db adapter would still query the original
SQL table / mongodb collection instead of the versions one which isn't
quite right since we respect `draft: true` when populating relationships
2025-03-24 09:49:30 -04:00
Alessio Gravili
5f6bb92501 feat!: bump minimum next version to 15.2.3 (#11823)
**BREAKING CHANGE:**
This bumps the **minimum required Next.js** version from 15.0.0 to
15.2.3. This update is necessary due to a critical security
vulnerability found in earlier Next.js versions, which requires an
exception to our standard semantic versioning process.

Additionally, this bumps all templates to the latest Next.js and Payload
versions.
2025-03-24 09:41:33 -04:00
Jacob Fletcher
7532c4ab66 fix(ui): exclude fields lacking permissions from bulk edit (#11776)
Top-level fields that lack read or update permissions still appear as
options in the field selector within the bulk edit drawer.
2025-03-21 14:44:49 -04:00
Sasha
4081953c18 feat(db-mongodb): support sorting by fields in other collections through a relationship field (#11803)
This is already supported in Postgres / SQLite.
For example:
```
const result = await payload.find({
  collection: 'directors',
  depth: 0,
  sort: '-movies.name', // movies is a relationship field here
})
```

Removes the condition in tests:
```
 // no support for sort by relation in mongodb
 if (isMongoose(payload)) {
  return
}
```
2025-03-20 20:49:21 +00:00
Ivica Batinić
f9f53a65cb feat(next): add support for custom props on the html element (#11738)
This PR adds support for passing additional props to the HTML element of
Next.js `RootLayout`.

#### Context  
In our setup, we use several custom Chakra UI components. This change
enables us to add a custom font `className` to the HTML element,
following the official Chakra UI documentation:
[Using custom fonts in Chakra UI with
Next.js](https://v2.chakra-ui.com/getting-started/nextjs-app-guide#using-custom-font)

#### Example Usage  
With this update, we can now pass a `className` for custom fonts like
this:

```tsx
import { Rubik } from 'next/font/google'

const rubik = Rubik({
  subsets: ['latin'],
  variable: '--font-rubik',
})

const Layout = ({ children }: Args) => {
  return (
    <RootLayout htmlProps={{ className: rubik.variable }}>
      {children}
    </RootLayout>
  );
}
```
2025-03-20 16:25:33 -04:00
Elliot DeNolf
339226e62a chore(release): v3.29.0 [skip ci] 2025-03-20 13:59:33 -04:00
Jacob Fletcher
31211e9755 feat: pass i18n through field label and description functions (#11802)
Passes the `i18n` arg through field label and description functions.
This is to avoid using custom components when simply needing to
translate a `StaticLabel` object, such as collection labels.

Here's an example:

```ts
{
  labels: {
    singular: {
      en: 'My Collection'
    }
  },
  fields: [
   // ...
   {
     type: 'collapsible',
     label: ({ i18n }) => `Translate this: ${getTranslation(collectionConfig.labels.singular, i18n)}`
     // ...
    }
  ]
}
```
2025-03-20 13:43:17 -04:00
Alessio Gravili
032c424244 perf: use direct db calls in job-queue system (#11489)
Previously, our job queue system relied on `payload.*` operations, which
ran very frequently:
- whenever job execution starts, as all jobs need to be set to
`processing: true`
- every single time a task completes or fails, as the job log needs to
be updated
- whenever job execution stops, to mark it as completed and to delete it
(if `deleteJobOnComplete` is set)

This PR replaces these with direct `payload.db.*` calls, which are
significantly faster than payload operations. Given how often the job
queue system communicates with the database, this should be a massive
performance improvement.

## How it affects running hooks

To generate the task status, we previously used an `afterRead` hook.
Since direct db adapter calls no longer execute hooks, this PR
introduces new `updateJob` and `updateJobs` helpers to handle task
status generation outside the normal payload hook lifecycle.

Additionally, a new `runHooks` property has been added to the global job
configuration. While setting this to `true` can be useful if custom
hooks were added to the `payload-jobs` collection config, this will
revert the job system to use normal payload operations.
This should be avoided as it degrades performance. In most cases, the
`onSuccess` or `onFail` properties in the job config will be sufficient
and much faster.

Furthermore, if the `depth` property is set in the global job
configuration, the job queue system will also fall back to the slower,
normal payload operations.

---------

Co-authored-by: Dan Ribbens <DanRibbens@users.noreply.github.com>
2025-03-20 13:31:14 -04:00
Alessio Gravili
43cdccdef0 feat(richtext-lexical): support escaping markdown characters (#11784)
Fixes https://github.com/payloadcms/payload/issues/10289 and
https://github.com/payloadcms/payload/issues/11772

This adds support for escaping markdown characters. For example,` \*` is
supposed to be imported as `*` and exported back to `\*`.

Equivalent PR in lexical repo:
https://github.com/facebook/lexical/pull/7353
2025-03-20 10:29:45 -06:00
Ainsley Clark
7d9d067faf fix(ui): adding guard check for populate docs in upload field (#11800)
### What?

When a user lands on an edit page that has a relationship to an `Upload`
field (which is `HasMany`). The UI will make a request with `limit=0` to
the backend providing there is no IDs populated already.

When a media collection is large, it will try and load all media items
into memory which causes OOM crashes.

### Why?

Fixes: https://github.com/payloadcms/payload/issues/11655 causing OOM
issues.

### How?

Adding guard check on the `populate` to ensure that it doesn't make a
request if not needed.


https://github.com/user-attachments/assets/f195025f-3e31-423e-b13e-6faf8db40129
2025-03-20 12:21:05 -04:00
Anders Semb Hermansen
b85727367c fix(richtext-lexical): error in admin panel when block collapsed preference is not an array (#11771)
### What?

Got an error in the admin panel when opening a document with richtext
and block. The error is:
`TypeError: collapsedArray.includes is not a function`

Screenshot of the error:
 

![collapsedArray_includes_error](https://github.com/user-attachments/assets/99c25810-0a10-4d23-a735-127edf7e87d6)

After reseting the preferences the error is gone. I did not take a copy
of the database before using reset settings, so I'm not sure what the
preferences where set to. So not sure how it got that way.

### Why?

Make the reading of preferences more robust against wrong data type to
avoid error.

### How?

Make sure collapsedArray is actually an array before using it as such.
2025-03-20 12:24:17 -03:00
Nacho Martin
39ad31a276 fix: add locale support to relationship filter options in WhereBuilder (#11783)
### What?

This PR fixes a bug in the relationship filter UI where no options are
displayed when working in a non-default locale with localized
collections. The query to fetch relationship options wasn't including
the current locale parameter, causing the select dropdown to appear
empty.

### Why?

When using localized collections with relationship fields:
1. If you create entries (e.g., Categories) only in a non-default locale
2. Set the global locale to that non-default locale
3. Try to filter another collection by its relationship to those
Categories

The filter dropdown would be empty, despite Categories existing in that
locale. This was happening because the `loadOptions` method in the
RelationshipFilter component didn't include the current locale in its
query.

### How?

The fix is implemented in
`packages/ui/src/elements/WhereBuilder/Condition/Relationship/index.tsx`
by:
1. Adding the `useLocale` hook to get the current locale in the
RelationshipFilter component
2. Including this locale in the query parameters when fetching
relationship options

![Before: Dropdown showing relationship options as empty
options](https://github.com/user-attachments/assets/b796840b-9001-4f38-98c4-7b37ee4121d7)

![After: Dropdown properly showing relationship options in non-default
locale](https://github.com/user-attachments/assets/a2f58d52-881e-49f7-b4dd-4b4ec7d07f10)

Fixes #11782 
Discussion:
https://discord.com/channels/967097582721572934/1350888604150534164
2025-03-20 10:35:25 -04:00
Jarrod Flesch
1d25b16a4a fix(db-mongodb): spread version schema options correctly (#11793) 2025-03-20 10:22:51 -04:00
Patrik
7bc75e244f fix: save button styles in edit-many modal (#11780)
### What?

This PR updates the styles of the form submit buttons in the edit-many
modal.

### Why?

Previously, the styles on the submit buttons caused a wrapping issue on
the Publish Document button when editing many documents with versions
enabled.

### How?

Adjusts the styles to prevent text wrapping of the Publish Document
button

#### Before:
![Screenshot 2025-03-19 at 3 17
42 PM](https://github.com/user-attachments/assets/911b77c1-98ac-4b58-8f1f-026273af7550)


#### After:
![Screenshot 2025-03-19 at 3 18
13 PM](https://github.com/user-attachments/assets/efcfe543-1329-4ee7-8ebe-25352a9bf388)
2025-03-19 17:08:36 -04:00
Jacob Fletcher
b5fc8c6573 fix(ui): bulk edit subfields (#10035)
Fixes #10019. When bulk editing subfields, such as a field within a
group, changes are not persisted to the database. Not only this, but
nested fields with the same name as another selected field are
controlled by the same input. E.g. typing into one fields changes the
value of both.

The root problem is that field paths are incorrect.

When opening the bulk edit drawer, fields are flattened into options for
the field selector. This is so that fields in a tab, for example, aren't
hidden behind their tab when bulk editing. The problem is that
`RenderFields` is not set up to receive pre-determined field paths. It
attempts to build up its own field paths, but are never correct because
`getFieldPaths` receives the wrong arguments.

The fix is to just render the top-level fields directly, bypassing
`RenderFields` altogether.

Fields with subfields will still recurse through this function, but at
the top-level, fields can be sent directly to `RenderField` (singular)
since their paths have already been already formatted in the flattening
step.
2025-03-19 21:01:59 +00:00
Patrik
a02e4762d0 fix: wrap login redirect routes with encodeURIComponent (#11778)
### What

This PR updates the `login` flow by wrapping redirect routes with
`encodeURIComponent`. This ensures that special characters in URLs (such
as ?, &, #) are properly encoded, preventing potential issues with
navigation and redirection.
2025-03-19 16:17:01 -04:00
Alessio Gravili
240730fdf2 feat(richtext-lexical): upgrade lexical from 0.27.2 to 0.28.0 (#11764)
This upgrades lexical from 0.27.2 to 0.28.0, and ports over relevant
changes from the lexical playground.
2025-03-19 16:11:15 -04:00
Alessio Gravili
20e975b7c6 feat: sort support for payload.update operation (#11769)
Continuation of https://github.com/payloadcms/payload/pull/11768. This
adds support for `sort` in `payload.update`.

## Example

```ts
const { docs } = await payload.update({
  collection: 'posts',
  data: {
    title: 'updated',
  },
  limit: 5,
  sort: '-numberField', // <= new
  where: {
    id: {
      exists: true,
    },
  },
})
```
2025-03-19 17:22:13 +00:00
Alessio Gravili
e96d3c87e2 feat(db-*): support sort in db.updateMany (#11768)
This adds support for `sort` in `payload.db.updateMany`.

## Example

```ts
const updatedDocs = await payload.db.updateMany({
  collection: 'posts',
  data: {
    title: 'updated',
  },
  limit: 5,
  sort: '-numberField', // <= new
  where: {
    id: {
      exists: true,
    },
  },
})
```
2025-03-19 10:47:58 -06:00
Patrik
afe443267d fix: email format validation with hyphens (#11761)
This PR updates the email validation regex to better handle use cases
with hyphens.

Changes:

- Disallows domains starting or ending with a hyphen
(`user@-example.com`, `user@example-.com`).
- Allows domains with consecutive hyphens inside (`user@ex--ample.com`).
- Allows multiple subdomains (`user@sub.domain.example.com`).
- Adds `int test` coverage for multiple domain use case scenarios.
2025-03-19 09:24:45 -04:00
Germán Jabloñski
ef527fe2d4 fix(richtext-lexical): error in admin panel when setting a richtext field in useAsTitle (#11707)
If the `useAsTitle` property is defined referencing a richtext field,
the admin panel throws errors in several places.

I noticed this in the email builder plugin, where we're making the
subject field (which is the title) a single-paragraph richtext field
instead of a text field for technical reasons.

In this PR, for the lexical richtext case, I'm converting the first
child of the RootNode (usually a paragraph or heading) to plain text.

Additionally, I am verifying that if the resulting title is not of type
string, fallback to "untitled" so that this does not happen again in the
future (perhaps with slate, or with other fields).
2025-03-18 16:02:23 -06:00
Germán Jabloñski
dd80f5250b fix(richtext-lexical): make the toolbar indent button consider the disabledNodes property on IndentFeature (#11739)
Fixes #11677
2025-03-18 15:59:05 -06:00
Dan Ribbens
975bbb756f feat: add find to payloadDataLoader to cache local API queries (#11685)
### What?
Extends our dataloader to add a momiozed payload find function. This way
it will cache the query for the same find request using a cacheKey from
find operation args.

### Why?
This was needed internally for `filterOptions` that exist in an array or
other sitautions where you have the same exact query being made and
awaited many times.

### How?

- Added `find` to payloadDataLoader. Marked `@experimental` in case it
needs to change.
- Created a cache key from the args
- Validate filterOptions changed from `payload.find` to
`payloadDataLoader.find`
- Made `payloadDataLoader` no longer optional on `PayloadRequest`, since
other args are required which are created from createLocalReq (context
for example), I don't see a reason why dataLoader shouldn't be required
also.

Example usage: 
```ts
const result = await req.payloadDataLoader.find({
    collection,
    req,
    where,
  })
```
2025-03-18 21:14:33 +00:00
Dan Ribbens
67a7358de1 fix(plugin-import-export): export with draft true (#11762)
### What?

- GraphQL was broken because of an error with the enum for the drafts
input which cannot be 'true'.
- Selecting Draft was not doing anything as it wasn't being passed
through to the find arguments.

### Why?

This was causing any graphql calls to error.

### How?

- Changed draft options to Yes/No instead of True/False
- Correctly pass the drafts arg to `draft`

Fixes #
2025-03-18 16:32:10 -04:00
Dan Ribbens
e83f452d09 fix(plugin-import-export): translated preview labels (#11758)
### What?

The import-export preview UI component does not handle localized fields
and crash the UI when they are used. This fixes that issue.

### Why?

We were not properly handling the label translated object notation that
field.label can have.

### How?

Now we call `getTranslation` with the field label to handle language
keyed labels.

Fixes # https://github.com/payloadcms/payload/issues/11668
2025-03-18 16:30:48 -04:00
Dan Ribbens
f31e5e675d chore: export type FieldAccessArgs (#11749)
### What?

Export FieldAccessArgs type.

### Why?

Prevent projects from needing to recreate this type manually and keep it
in sync with changes in payload releases.

### How?

Exports a new type called FieldAccessArg that is then referenced in the
FieldAccess function argument.
2025-03-18 16:30:24 -04:00
Patrik
875afccec4 fix: improves email validation format rules (#11757)
This PR updates the email validation regex to enforce stricter rules.

- Disallows emails containing double quotes (e.g., `"user"@example.com`,
`user@"example.com"`, `"user@example.com"`).
- Rejects spaces anywhere in the email (e.g., `user @example.com`).
- Prevents consecutive dots in both local and domain parts (e.g.,
`user..name@example.com`, `user@example..com`).
- Allows standard formats like `user@example.com` and
`user.name+alias@example.co.uk`.

Fixes #11755
2025-03-18 15:12:06 -04:00
Said Akhrarov
fd99a30bb6 feat: distinct error for unverified email login (#11647)
<!--

Thank you for the PR! Please go through the checklist below and make
sure you've completed all the steps.

Please review the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository if you haven't already.

The following items will ensure that your PR is handled as smoothly as
possible:

- PR Title must follow conventional commits format. For example, `feat:
my new feature`, `fix(plugin-seo): my fix`.
- Minimal description explained as if explained to someone not
immediately familiar with the code.
- Provide before/after screenshots or code diffs if applicable.
- Link any related issues/discussions from GitHub or Discord.
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Fixes #

-->
### What?
This PR adds a new error to be thrown when logging in while having
`verify: true` set but no email has been verified for the user yet.

### Why?
To have a more descriptive, actionable error thrown in this case as
opposed to the generic "Invalid email or password." This gives users
more insight into why the login failed.

### How?
Introducing a new error: `UnverifiedEmail` and adjusting the check to be
separate from `if (!user) { ... }`.

Fixes #11358

Notes:
- In terms of account enumeration: this should not be a concern here as
the check for throwing this error comes _after_ the check for valid args
as well as the find for the user. This means that credentials must be on
hand, both an email and password, before seeing this error.
- I have an int test written in `/test/auth/int.spec.ts` for this,
however whenever I try to commit it I get an error stating that the
`eslint@9.14.0` module was not found during `lint-staged`.

<details>
  <summary>Int test</summary>
  
  ```ts
it('should respond with unverifiedEmail if email is unverified on
login', async () => {
    await payload.create({
      collection: publicUsersSlug,
      data: {
        email: 'user@example.com',
        password: 'test',
      },
    })

const response = await restClient.POST(`/${publicUsersSlug}/login`, {
      body: JSON.stringify({
        email: 'user@example.com',
        password: 'test',
      }),
    })

    expect(response.status).toBe(403)

    const responseData = await response.json()
expect(responseData.errors[0].message).toBe('Please verify your email
before logging in.')
  })
  ```
  
</details>

Demo of toast:

![Login-Payload-03-11-2025_11_52_PM-unverified-after](https://github.com/user-attachments/assets/55112f61-1d1f-41b9-93e6-8a4d66365b81)
2025-03-18 15:52:51 -03:00
Alessio Gravili
3f23160a96 fix(richtext-lexical): unchecked list items were rendered as checked in html converter (#11747)
Previously, unchecked list items had the `checked="false"` attribute,
which is not valid in HTML and renders them as checked.

This PR omits the `checked` attribute if the list item is unchecked,
which is the correct behavior.
2025-03-18 17:30:52 +00:00
Germán Jabloñski
aa3737ca39 fix(richtext-lexical): remove undefined rel and target attributes in link HTML converter (#11754)
When converting lexical to HTML, links without "open in new tab" checked
were incorrectly rendering with rel=undefined and target=undefined
attributes. This fix ensures those attributes are only added when newTab
is true.

Fixes: #11752
2025-03-18 10:55:29 -06:00
Jarrod Flesch
06aa940747 fix(plugin-multi-tenant): ensures redirect route is correctly formatted (#11753) 2025-03-18 12:31:26 -04:00
Jessica Chowdhury
74996fd511 fix: field appending on duplicate should ignore non string values (#11621)
### What?
When duplicating a document with `unique` fields, we append `- Copy` to
the field value.
The issue is that this is happening when the field is empty resulting in
values being added that look like: `undefined - Copy` or `null - Copy`.

### Why?
We are not checking the incoming value in all cases.

### How?
Checks the value exists, is a string, and is not just an empty space
before appending `- Copy`.

At first glance it looks incorrect to return required fields with
`undefined` - however when duplicating a document, the new document is
always created as a `draft` so it is not an issue to return `undefined`.

Closes #11373
2025-03-18 16:01:08 +00:00
Jessica Chowdhury
4a712e1d2c fix: passes id and data to read access func when accessing upload URLs (#11684)
### What?
When accessing an upload directly from the generated URL, the `read`
access runs but returns undefined `id` and `data`. As a result, any
access conditions that rely on `id` or `data` will fail and users cannot
accurately determine whether or not to grant access.

### Why?
Accessing the file URL runs
`packages/payload/src/uploads/endpoints/getFile.ts`.
In this endpoint, we use `checkFileAccess()` from
`packages/payload/src/uploads/checkFileAccess.ts`.
Within the `checkFileAccess` function we are only passing the `req` to
`executeAccess()`.

### How?
Passes `filename` to the `executeAccess()` function from
`uploads/checkFileAccess`, this is the available data within the file
and will provide a way for users to make a request to get the full data.

Fixes #11263
2025-03-18 15:34:04 +00:00
Patrik
ea66e2167c fix: bulk upload validation when files are missing (#11744)
### What?

This PR ensures that bulk uploads fail if any file is missing, rather
than skipping missing files and proceeding with the upload.

### Why?

This fixes unintended behavior where missing files were skipped,
allowing partial uploads when they shouldn't be allowed.

### How?

- Prevents submission if any file is missing by checking `req.status ===
400`.
- Updates `FileSidebar` to correctly handle cases where a file is
`null`.
2025-03-18 10:26:17 -04:00
Jessica Chowdhury
0fe922e214 fix(ui): excess error css coming from group fields (#11700) 2025-03-18 08:42:35 -04:00
Sasha
f442d22237 feat(db-*): allow to thread id to create operation data without custom IDs (#11709)
Fixes https://github.com/payloadcms/payload/issues/6884

Adds a new flag `acceptIDOnCreate` that allows you to thread your own
`id` to `payload.create` `data`, for example:

```ts
// doc created with id 1
const doc = await payload.create({ collection: 'posts', data: {id: 1, title: "my title"}})
```

```ts
import { Types } from 'mongoose'
const id = new Types.ObjectId().toHexString()
const doc = await payload.create({ collection: 'posts', data: {id, title: "my title"}})
```
2025-03-17 23:48:35 -04:00
Jacob Fletcher
d8bfb227b7 perf(ui): implements select in bulk edit (#11708)
Bulk edit can now request a partial form state thanks to #11689. This
means that we only need to build form state (and send it through the
network) for the currently selected fields, as opposed to the entire
field schema.

Not only this, but there is no longer a need to filter out unselected
fields before submitting the form, as the form state will only ever
include the currently selected fields. This is unnecessary processing
and causes an excessive amount of rendering, especially since we were
dispatching actions within a `for` loop to remove each field. React may
have batched these updates, but is bad practice regardless.

Related: stripping unselected fields was also error prone. This is
because the `overrides` function we were using to do this receives
`FormState` (shallow) as an argument, but was being treated as `Data`
(not shallow, what the create and update operations expect).

E.g. `{ myGroup.myTitle: { value: 'myValue' }}` → `{ myGroup: { myTitle:
'myValue' }}`.
 
This led to the `sanitizeUnselectedFields` function improperly
formatting data sent to the server and would throw an API error upon
submission. This is only evident when sanitizing nested fields. Instead
of converting this data _again_, the select API takes care of this by
ensuring only selected fields exist in form state.

Related: bulk upload was not hitting form state on change. This means
that no field-level validation was occurring on type.
2025-03-17 23:06:58 -04:00
Sasha
11d74871ef feat(db-postgres): add vector raw column type (#10422)
Example how you can add a vector column, enable the `vector` extension
and query your embeddings in the included test -

https://github.com/payloadcms/payload/compare/feat/more-types?expand=1#diff-7d876370487cb625eb42ff1ad7cffa78e8327367af3de2930837ed123f5e3ae6R1-R117
2025-03-17 20:50:00 +00:00
Alessio Gravili
82840aa09b refactor(richtext-lexical): new plaintext and markdown converters, restructure converter docs (#11675)
- Introduces a new lexical => plaintext converter
- Introduces a new lexical <=> markdown converter
- Restructures converter docs. Each conversion type gets its own docs
pag
2025-03-17 20:36:10 +00:00
Germán Jabloñski
013b515d3c feat(richtext-lexical): allow disabling TabNode (#11656)
Similar to https://github.com/payloadcms/payload/pull/11631.

IndentFeature causes pressing Tab in the middle of a block such as a
paragraph or heading to insert a TabNode. This property allows you to
disable this behavior, and indentation will occur instead if the block
allows it.

Usage: 
```ts
editor: lexicalEditor({
  features: ({ defaultFeatures }) => [
    ...defaultFeatures,
    IndentFeature({
      disableTabNode: true,
    }),
  ],
}),
```
2025-03-17 17:11:17 -03:00
Jarrod Flesch
ebfb0eb014 fix(ui): fallback localization data was appearing in document (#11743) 2025-03-17 16:09:01 -04:00
Jarrod Flesch
8a51fe1a17 feat: aligns user _strategy returned from API (#11701) 2025-03-17 16:04:43 -04:00
Alessio Gravili
adb42cbe19 feat(richtext-lexical): upgrade lexical from 0.27.1 to 0.27.2 (#11706)
This upgrades lexical from 0.27.1 to 0.27.2, and ports over some
relevant changes to the table feature from the lexical playground.
2025-03-17 15:17:40 -04:00
Paul
e0bf505836 fix(ui): scheduled publish not displaying the timezone's label and timezones being reset when scheduling a publish, brisbane is now a default timezone (#11699)
Fixes a problem where we would reset the value of the timezone field on
submission of a new scheduled publish.

Timezones in the table now match with a label if possible.

![image](https://github.com/user-attachments/assets/19a28075-e929-4548-a8db-7ed3a81d57ec)

`Australia/Brisbane` is now part of the default list of timezones
2025-03-17 18:52:42 +00:00
DriesCruyskens
bb39c870c1 fix(plugin-cloud-storage): s3Storage client uploads working with more than 2 instances of the plugin (#11732)
Fixes
https://github.com/payloadcms/payload/issues/11731#issue-2923088087

Only 2 s3Storage() instances with `clientUploads: true` are currently
working. If you add a 3rd instance, uploading files errors with
"Collection credit-certificates was not found in S3 options".

There is already an implementation that changes the
`/storage-s3-generate-signed-url` URL for each new s3Storage plugin
instance so that multiple instances don't break each other. Currently
the code looks like this:

```ts
/**
 * Tracks how many times the same handler was already applied.
 * This allows to apply the same plugin multiple times, for example
 * to use different buckets for different collections.
 */
let handlerCount = 0

for (const endpoint of config.endpoints) {
  if (endpoint.path === serverHandlerPath) {
    handlerCount++
  }
}

if (handlerCount) {
  serverHandlerPath = `${serverHandlerPath}-${handlerCount}`
}
```

When we print the endpoints generated by this code we get:

```ts
 {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url'
  },
  {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url-1'
  },
  {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url-1'
  }
```
As you can see, the path or the 3rd instance is the same as the 2nd
instance. Presumably this functionality was originally tested with 2
instances and not more, allowing this bug to slip through. This
completely breaks uploads for the 3rd instance.

We need to change the conditional that checks whether the plugin exists
already to use `.startsWith()`:

```ts
/**
 * Tracks how many times the same handler was already applied.
 * This allows to apply the same plugin multiple times, for example
 * to use different buckets for different collections.
 */
let handlerCount = 0

for (const endpoint of config.endpoints) {
  // We want to match on 'path', 'path-1', 'path-2', etc.
  if (endpoint.path?.startsWith(serverHandlerPath)) {
    handlerCount++
  }
}

if (handlerCount) {
  serverHandlerPath = `${serverHandlerPath}-${handlerCount}`
}
```

With the fix we can see that the endpoints increment correctly, allowing
for a true arbitrary number of s3Storage plugins with client uploads.
```ts
 {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url'
  },
  {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url-1'
  },
  {
    handler: [AsyncFunction (anonymous)],
    method: 'post',
    path: '/storage-s3-generate-signed-url-2'
  }
```
2025-03-17 20:12:41 +02:00
Jacob Fletcher
0b1a1b585b fix(ui): processing and initializing form does not disable standalone fields (#11714)
The form component's `initializing` and `processing` states do not
disable fields that are rendered outside of `DocumentFields`. Fields
currently rely on the `readOnly` prop provided by `DocumentFields` and
do not subscribe to these states for themselves. This means that fields
that are rendered outright, such as within the bulk edit drawer, they do
not receive a `readOnly` prop and are therefore never disabled.

The fix is add a `disabled` property to the `useField` hook. This
subscribes to the `initializing` and `processing` states in the same way
as `DocumentFields`, however, now each field can determine its own
disabled state instead of relying solely on the `readOnly` prop. Adding
this new prop has no overhead as `processing` and `initializing` is
already being subscribed to within `useField`.
2025-03-17 10:27:21 -04:00
Jarrod Flesch
3d129e822d fix(plugin-multi-tenant): missing key console message (#11693) 2025-03-17 10:03:51 -04:00
Said Akhrarov
6270d735a8 perf: download only images and optimize image selection for upload list view, prioritize best-fit size (#11696)
### What?

This PR optimizes how images are selected for display in the upload list
view. It ensures that only image files are processed and selects the
most appropriate size to minimize unnecessary downloads and improve
performance.

#### Previously:

- Non-image files were being processed unnecessarily, despite not
generating thumbnails.
- Images without a `thumbnailURL` defaulted to their original full size,
even when smaller, optimized versions were available.

#### Now:

- **Only images** are processed for thumbnails, avoiding redundant
requests for non-images.
- **The smallest available image within a target range** (`40px -
180px`) is prioritized for display.
- **If no images fit within this range**, the logic selects:
  - The next smallest larger image (if available).
- The **original** image if it is smaller than the next available larger
size.
  - The largest **smaller** image if no better fit exists.

### Why?

Prevents unnecessary downloads of non-image files, reduces bandwidth
usage by selecting more efficient image sizes and improves load times
and performance in the list view.

### How?
- **Filters out non-image files** when determining which assets to
display.
- Uses a more precise selection algorithm to find the best-fit image
size:
  - Prefers the smallest image within `40px - 180px`.
- Falls back to the closest match above or below the range if no
in-range image exists.
- Ensures the original image is only used when it provides a better fit.

Fixes #11690

Before (4.7mb transfer):

![chrome_2025-03-14_02-39-16](https://github.com/user-attachments/assets/4d87b0ae-164e-47c5-a426-43bd2083b725)

After (129kb transfer):

![chrome_2025-03-14_01-01-19](https://github.com/user-attachments/assets/1cdab4ec-f3ad-40ae-9099-c8b789588ac7)
2025-03-17 09:56:56 -04:00
AoiYamada
427a5f123b feat(plugin-form-builder): radio field (#11716)
### What?

A field for input radio

Demo:

<img width="1320" alt="Screenshot 2025-03-15 at 6 54 51 AM"
src="https://github.com/user-attachments/assets/47744e3f-e1ca-4596-bc7c-09f7b2d42c5b"
/>

---

UI code example, using shadcn/ui:

```tsx
import type { SelectField } from '@payloadcms/plugin-form-builder/types'
import type { Control, FieldErrorsImpl } from 'react-hook-form'

import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import React from 'react'
import { Controller } from 'react-hook-form'

import { Error } from '../Error'
import { Width } from '../Width'

export const Radio: React.FC<
  SelectField & {
    control: Control
    errors: Partial<FieldErrorsImpl>
  }
> = ({ name, control, errors, label, options, required, width, defaultValue }) => {
  return (
    <Width width={width}>
      <Label htmlFor={name}>{label}</Label>
      <Controller
        control={control}
        defaultValue={defaultValue}
        name={name}
        render={({ field: { onChange, value } }) => {
          return (
            <RadioGroup onValueChange={(val) => onChange(val)} value={value} className="space-y-2">
              {options.map(({ label, value }) => {
                const id = `${name}-${value}`

                return (
                  <div key={value} className="flex items-center space-x-2">
                    <RadioGroupItem value={value} id={id} />
                    <Label htmlFor={id}>{label}</Label>
                  </div>
                )
              })}
            </RadioGroup>
          )
        }}
        rules={{ required }}
      />
      {required && errors[name] && <Error />}
    </Width>
  )
}

```

UI demo:

<img width="651" alt="Screenshot 2025-03-15 at 7 04 37 AM"
src="https://github.com/user-attachments/assets/f3922489-8e62-4464-b48c-8425735421f5"
/>

Co-authored-by: Pan <kpkong@hk01.com>
2025-03-15 11:52:05 +00:00