Every language filled (fillEmptyLocales, default on): text saved in one language goes to every language where the same field is still empty, never over a language's own text. Applies to the cookie list (purpose, duration) and the cookie review (purpose, duration). Scanner and approval writes give a language without its own text the default language's text. Building blocks: buildFillEmptyLocalesGlobalHook / CollectionHook, fillEmptyLocales, withFillLocales. One Cookies entry (cookieScanner.adminLayout, default combined): the Cookie banner global is now labelled Cookies and gets Review and approve (scan box and approval list inline) and Site check tabs, built from ui fields. Cookie review and Cookie check leave the navigation (admin.group false) but keep their pages, data and API. This is presentation only: no schema change and no migration, only generate:importmap. adminLayout separate keeps the old layout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
135 lines
6.0 KiB
TypeScript
135 lines
6.0 KiB
TypeScript
import type { BasePayload, CollectionAfterChangeHook, CollectionConfig, GlobalAfterChangeHook, GlobalConfig, PayloadRequest } from 'payload'
|
|
|
|
/**
|
|
* Localized text the editor wrote in one language goes to every language that
|
|
* is still empty — so a cookie added in Polish is not blank on the English page.
|
|
* A language that already has its own text is never touched: the editor can
|
|
* still change any language on its own.
|
|
*
|
|
* Fields: `'purpose'` (top-level) or `'cookies.purpose'` (a sub-field of the
|
|
* rows of an array; rows are matched by their id, which Payload keeps the same
|
|
* in every locale).
|
|
*
|
|
* Payload's own `localization.fallback` only covers part of this: an empty
|
|
* locale *reads* as the default locale's text, but nothing is stored, the admin
|
|
* shows the field empty, and the text always comes from the default locale,
|
|
* not from the language that was just edited.
|
|
*/
|
|
export type FillEmptyLocalesTarget = { collection: string; id: number | string } | { global: string }
|
|
|
|
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
|
|
|
|
/** Writes `source`'s text (read in `sourceLocale`) into every other locale where that text is empty. Returns the locales changed. */
|
|
export async function fillEmptyLocales({
|
|
fields,
|
|
payload,
|
|
req,
|
|
source,
|
|
sourceLocale,
|
|
target,
|
|
}: {
|
|
fields: string[]
|
|
payload: BasePayload
|
|
req?: PayloadRequest
|
|
source: Record<string, unknown>
|
|
sourceLocale: string
|
|
target: FillEmptyLocalesTarget
|
|
}): Promise<string[]> {
|
|
const l = payload.config.localization
|
|
if (!l) {return []}
|
|
const others = l.localeCodes.filter((c) => c !== sourceLocale)
|
|
const common = { context: { ipalFillLocales: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
|
|
const changedLocales: string[] = []
|
|
|
|
for (const locale of others) {
|
|
const doc = (
|
|
'global' in target
|
|
? await payload.findGlobal({ ...common, slug: target.global as never, locale: locale as never })
|
|
: await payload.findByID({ ...common, id: target.id as never, collection: target.collection as never, locale: locale as never })
|
|
) as Record<string, unknown>
|
|
const patch: Record<string, unknown> = {}
|
|
|
|
for (const field of fields) {
|
|
const [head, sub] = field.split('.')
|
|
if (!sub) {
|
|
if (empty(doc[head]) && !empty(source[head])) {patch[head] = source[head]}
|
|
continue
|
|
}
|
|
const sourceRows = Array.isArray(source[head]) ? (source[head] as Record<string, unknown>[]) : []
|
|
const rows = (patch[head] as Record<string, unknown>[] | undefined) ?? (Array.isArray(doc[head]) ? (doc[head] as Record<string, unknown>[]).map((r) => ({ ...r })) : [])
|
|
let changed = false
|
|
for (const row of rows) {
|
|
const from = sourceRows.find((s) => s.id != null && s.id === row.id)
|
|
if (from && empty(row[sub]) && !empty(from[sub])) {
|
|
row[sub] = from[sub]
|
|
changed = true
|
|
}
|
|
}
|
|
if (changed) {patch[head] = rows}
|
|
}
|
|
|
|
if (!Object.keys(patch).length) {continue}
|
|
if ('global' in target) {
|
|
await payload.updateGlobal({ ...common, slug: target.global as never, data: patch as never, locale: locale as never })
|
|
} else {
|
|
await payload.update({ ...common, id: target.id as never, collection: target.collection as never, data: patch as never, locale: locale as never })
|
|
}
|
|
changedLocales.push(locale)
|
|
}
|
|
return changedLocales
|
|
}
|
|
|
|
/** Runs `fn` with `req`, then puts back req.locale / req.fallbackLocale (Local API calls with `req` change them). */
|
|
async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
|
|
const { fallbackLocale, locale } = req
|
|
try {
|
|
await fn()
|
|
} catch (err) {
|
|
req.payload.logger.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
} finally {
|
|
req.locale = locale
|
|
req.fallbackLocale = fallbackLocale
|
|
}
|
|
}
|
|
|
|
/** Skips its own writes and writes that fill every locale themselves (the cookie scanner). */
|
|
const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
|
|
Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*'
|
|
|
|
/**
|
|
* afterChange hook for a global: text saved in one language fills that field in
|
|
* every language where it is empty.
|
|
*
|
|
* hooks: { afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'cookie-settings', fields: ['cookies.purpose'] })] }
|
|
*/
|
|
export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: string[]; global: string }): GlobalAfterChangeHook {
|
|
return async ({ context, doc, req }) => {
|
|
if (skip(context, req.locale)) {return doc}
|
|
await keepingLocale(req, () =>
|
|
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { global } }),
|
|
)
|
|
return doc
|
|
}
|
|
}
|
|
|
|
/** The same for a collection: the saved document's text fills its empty languages. */
|
|
export function buildFillEmptyLocalesCollectionHook({ collection, fields }: { collection: string; fields: string[] }): CollectionAfterChangeHook {
|
|
return async ({ context, doc, req }) => {
|
|
if (skip(context, req.locale) || doc?.id == null) {return doc}
|
|
await keepingLocale(req, () =>
|
|
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { id: doc.id, collection } }),
|
|
)
|
|
return doc
|
|
}
|
|
}
|
|
|
|
/** Adds the fill hook to a global or a collection config (no fields = unchanged). */
|
|
export function withFillLocales<T extends CollectionConfig | GlobalConfig>(kind: 'collection' | 'global', entity: T, fields: string[] | undefined): T {
|
|
if (!fields?.length) {return entity}
|
|
const hook =
|
|
kind === 'collection'
|
|
? buildFillEmptyLocalesCollectionHook({ collection: entity.slug, fields })
|
|
: buildFillEmptyLocalesGlobalHook({ fields, global: entity.slug })
|
|
return { ...entity, hooks: { ...entity.hooks, afterChange: [...(entity.hooks?.afterChange ?? []), hook] } } as T
|
|
}
|