feat(ui): adds filtering config option and implementation for filtering a… (#11007)

Adds the ability to filter what locales should be available per request.

This means that you can determine what locales are visible in the
localizer selection menu at the top of the admin panel. You could do
this per user, or implement a function that scopes these to tenants and
more.

Here is an example function that would scope certain locales to tenants:

**`payload.config.ts`**
```ts
// ... rest of payload config

localization: {
  defaultLocale: 'en',
  locales: ['en', 'es'],
  filterAvailableLocales: async ({ req, locales }) => {
    if (getTenantFromCookie(req.headers, 'text')) {
      try {
        const fullTenant = await req.payload.findByID({
          id: getTenantFromCookie(req.headers, 'text') as string,
          collection: 'tenants',
        })
        if (fullTenant && fullTenant.supportedLocales?.length) {
          return locales.filter((locale) => {
            return fullTenant.supportedLocales?.includes(locale.code as 'en' | 'es')
          })
        }
      } catch (_) {
        // do nothing
      }
    }
    return locales
  },
}
  ```

The filter above assumes you have a field on your tenants collection like so:

```ts
{
  name: 'supportedLocales',
  type: 'select',
  hasMany: true,
  options: [
    {
      label: 'English',
      value: 'en',
    },
    {
      label: 'Spanish',
      value: 'es',
    },
  ],
}
```
This commit is contained in:
Jarrod Flesch
2025-02-06 16:57:59 -05:00
committed by GitHub
parent 57143b37d0
commit a63a3d0518
2 changed files with 22 additions and 0 deletions

View File

@@ -91,6 +91,20 @@ export const RootLayout = async ({
importMap,
})
if (
clientConfig.localization &&
config.localization &&
typeof config.localization.filterAvailableLocales === 'function'
) {
clientConfig.localization.locales = (
await config.localization.filterAvailableLocales({
locales: config.localization.locales,
req,
})
).map(({ toString, ...rest }) => rest)
clientConfig.localization.localeCodes = config.localization.locales.map(({ code }) => code)
}
const locale = await getRequestLocale({
req,
})

View File

@@ -470,6 +470,14 @@ export type BaseLocalizationConfig = {
* @default true
*/
fallback?: boolean
/**
* Define a function to filter the locales made available in Payload admin UI
* based on user.
*/
filterAvailableLocales?: (args: {
locales: Locale[]
req: PayloadRequest
}) => Locale[] | Promise<Locale[]>
}
export type LocalizationConfigWithNoLabels = Prettify<