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 sourceLocale: string target: FillEmptyLocalesTarget }): Promise { 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 const patch: Record = {} 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[]) : [] const rows = (patch[head] as Record[] | undefined) ?? (Array.isArray(doc[head]) ? (doc[head] as Record[]).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) { 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 | undefined, locale: unknown) => Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*' /** No Payload instance on the request (tests, scripts): nothing to read or write. */ const noPayload = (req: PayloadRequest | undefined) => !req?.payload /** * 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 (noPayload(req) || skip(context, req.locale)) {return doc} await keepingLocale(req, () => fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record, 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 (noPayload(req) || skip(context, req.locale) || doc?.id == null) {return doc} await keepingLocale(req, () => fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record, 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(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 }