buildCrossLocaleFieldSync read other locales outside the save's transaction and its update(req) left req.locale on the last target locale. buildPreventDeleteSystemPage now reads Site Settings with req. Co-Authored-By: Claude Opus 5.5 <[email protected]>
183 lines
6.9 KiB
TypeScript
183 lines
6.9 KiB
TypeScript
import type { CollectionAfterChangeHook } from 'payload'
|
|
|
|
import type { I18nConfig } from '../i18n/index.js'
|
|
|
|
import { getLocaleCodes } from '../i18n/index.js'
|
|
|
|
type Row = { blockType?: string; id?: number | string } & Record<string, unknown>
|
|
|
|
type BuildCrossLocaleFieldSyncArgs = {
|
|
/**
|
|
* The localized `blocks`/`array` field whose rows hold the shared fields.
|
|
* Default 'layout'.
|
|
*/
|
|
arrayField?: string
|
|
/**
|
|
* Slug of the collection this hook is attached to — needed to re-read and
|
|
* update the other locales. (A hook can't discover its own collection.)
|
|
*/
|
|
collection: string
|
|
config: I18nConfig
|
|
/**
|
|
* Fields WITHIN each row that are conceptually language-independent (a shared
|
|
* media reference, an icon, a color) and should be propagated from the edited
|
|
* locale to every other locale — e.g. ['image'] or ['image', 'backgroundImage'].
|
|
*
|
|
* Only fields with a value in the source are copied: clearing a field in one
|
|
* language does NOT wipe it in the others (conservative, matches the hand-
|
|
* rolled hooks this replaces). Text and other truly-localized fields are never
|
|
* touched.
|
|
*/
|
|
fields: string[]
|
|
/**
|
|
* Flag name set on `req` to break the update→afterChange→update loop.
|
|
* Default '_ipalSyncingCrossLocale'. Override only if two syncs run on one
|
|
* collection and must not share a guard.
|
|
*/
|
|
guardFlag?: string
|
|
}
|
|
|
|
/** Relationship/upload values arrive as an id or a populated object — normalize to the id. */
|
|
function toId(value: unknown): null | number | string {
|
|
if (value == null) {return null}
|
|
if (typeof value === 'string' || typeof value === 'number') {return value}
|
|
if (typeof value === 'object' && 'id' in (value as Record<string, unknown>)) {
|
|
const id = (value as Record<string, unknown>).id
|
|
return typeof id === 'string' || typeof id === 'number' ? id : null
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
|
* localized `blocks`/`array` field from the just-edited locale to every other
|
|
* configured locale.
|
|
*
|
|
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
|
* is no way to mark a single sub-field (the image) as non-localized — each
|
|
* locale keeps its own copy of every row, image included. Without this, an
|
|
* editor who picks images in Polish has to re-pick the SAME images in English,
|
|
* German, … This hook does that copy automatically.
|
|
*
|
|
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
|
* a language in the panel and it's covered with no code change. (The hand-rolled
|
|
* versions this replaces carried a literal `['pl','en',...]` that silently
|
|
* dropped any locale not listed.)
|
|
*
|
|
* Row matching: by Payload row `id` when the same id exists in both locales
|
|
* (robust to reordering and to several blocks of the same type); otherwise it
|
|
* falls back to the positional index, but only when the block types at that
|
|
* index match — so it never writes an image into a block of a different type.
|
|
*
|
|
* // collections/Pages.ts
|
|
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
|
* hooks: {
|
|
* afterChange: [
|
|
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
|
* ],
|
|
* }
|
|
*/
|
|
export function buildCrossLocaleFieldSync(
|
|
args: BuildCrossLocaleFieldSyncArgs,
|
|
): CollectionAfterChangeHook {
|
|
const {
|
|
arrayField = 'layout',
|
|
collection,
|
|
config,
|
|
fields,
|
|
guardFlag = '_ipalSyncingCrossLocale',
|
|
} = args
|
|
|
|
return async ({ doc, req }) => {
|
|
const reqAny = req as unknown as Record<string, unknown>
|
|
// Re-entry guard: our own payload.update() below re-fires afterChange.
|
|
if (reqAny[guardFlag] || !doc?.id) {return doc}
|
|
|
|
const sourceRows = (doc as Record<string, unknown>)[arrayField]
|
|
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {return doc}
|
|
|
|
// Source locale = the locale being written. Fall back to the configured
|
|
// default rather than a hard-coded 'pl' when req.locale is absent.
|
|
const sourceLocale = typeof req.locale === 'string' ? req.locale : config.defaultLocale
|
|
const otherLocales = getLocaleCodes(config).filter((l) => l !== sourceLocale)
|
|
if (otherLocales.length === 0) {return doc} // single-locale site: nothing to sync
|
|
|
|
const payload = req.payload
|
|
// Passing `req` keeps the reads and writes in the save's transaction, but
|
|
// the Local API sets req.locale / req.fallbackLocale to the call's locale —
|
|
// restored in `finally`, or the rest of the save (afterRead, the response)
|
|
// would run in the last target locale.
|
|
const { fallbackLocale, locale: requestLocale } = req
|
|
|
|
reqAny[guardFlag] = true
|
|
try {
|
|
for (const locale of otherLocales) {
|
|
let targetDoc: Record<string, unknown>
|
|
try {
|
|
targetDoc = (await payload.findByID({
|
|
id: doc.id as never,
|
|
collection: collection as never,
|
|
depth: 0,
|
|
locale: locale as never,
|
|
req,
|
|
})) as Record<string, unknown>
|
|
} catch {
|
|
continue // locale not yet created for this doc — nothing to sync into
|
|
}
|
|
|
|
const targetRows = targetDoc[arrayField]
|
|
if (!Array.isArray(targetRows) || targetRows.length === 0) {continue}
|
|
|
|
// id → row index, for robust matching across locales.
|
|
const byId = new Map<number | string, number>()
|
|
;(targetRows as Row[]).forEach((row, i) => {
|
|
if (row?.id != null) {byId.set(row.id, i)}
|
|
})
|
|
|
|
let changed = false
|
|
|
|
;(sourceRows as Row[]).forEach((sourceRow, idx) => {
|
|
if (!sourceRow) {return}
|
|
|
|
// Match by id first; else positional index, but only if block types agree.
|
|
let targetRow: Row | undefined
|
|
if (sourceRow.id != null && byId.has(sourceRow.id)) {
|
|
targetRow = (targetRows as Row[])[byId.get(sourceRow.id)!]
|
|
} else {
|
|
const candidate = (targetRows as Row[])[idx]
|
|
if (candidate && candidate.blockType === sourceRow.blockType) {targetRow = candidate}
|
|
}
|
|
if (!targetRow) {return}
|
|
|
|
for (const field of fields) {
|
|
const sourceId = toId(sourceRow[field])
|
|
if (sourceId == null) {continue} // don't propagate a cleared field
|
|
if (toId(targetRow[field]) !== sourceId) {
|
|
targetRow[field] = sourceId
|
|
changed = true
|
|
}
|
|
}
|
|
})
|
|
|
|
if (changed) {
|
|
await payload.update({
|
|
id: doc.id as never,
|
|
collection: collection as never,
|
|
data: { [arrayField]: targetRows } as never,
|
|
locale: locale as never,
|
|
req,
|
|
})
|
|
}
|
|
}
|
|
} catch (err) {
|
|
payload.logger?.error?.({ err, msg: `[ipal] cross-locale ${arrayField} sync failed` })
|
|
} finally {
|
|
reqAny[guardFlag] = false
|
|
req.locale = requestLocale
|
|
req.fallbackLocale = fallbackLocale
|
|
}
|
|
|
|
return doc
|
|
}
|
|
}
|