Added support for crossLocaleFieldSync

This commit is contained in:
2026-10-09 20:18:16 +02:00
parent f9d3d9ae97
commit b25f221a50
20 changed files with 593 additions and 5 deletions
@@ -0,0 +1,174 @@
import type { BasePayload, 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
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,
})) 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
}
return doc
}
}
+1
View File
@@ -2,6 +2,7 @@
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
export { normalizeFilenameHook } from '../media/index.js'
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'
export { buildRevalidateHook } from './buildRevalidateHook.js'
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
export { setPublishedAtHook } from './setPublishedAt.js'
+95
View File
@@ -0,0 +1,95 @@
import type { CheckboxField, Field, FieldHook } from 'payload'
type BuildNoindexFieldArgs = {
/** Help text under the checkbox. */
description?: string
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
label?: string
/**
* Dotted path, inside the document, that the SEO read path (metadata +
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
* The checkbox value is mirrored here on every save, so editors toggle one
* friendly switch and the machinery reads a stable location.
*/
metaPath?: string
/** Field name for the editor-facing checkbox. Default 'noindex'. */
name?: string
/** Extend/override the generated checkbox (position, access, etc.). */
overrides?: Partial<CheckboxField>
}
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */
function readPath(obj: null | Record<string, unknown> | undefined, path: string[]): unknown {
let cur: unknown = obj
for (const key of path) {
if (cur == null || typeof cur !== 'object') {return undefined}
cur = (cur as Record<string, unknown>)[key]
}
return cur
}
/** Write a dotted path, creating intermediate objects as needed. */
function writePath(obj: Record<string, unknown>, path: string[], value: unknown): void {
let cur: Record<string, unknown> = obj
for (let i = 0; i < path.length - 1; i++) {
const key = path[i]
const next = cur[key]
if (next == null || typeof next !== 'object') {cur[key] = {}}
cur = cur[key] as Record<string, unknown>
}
cur[path[path.length - 1]] = value
}
/**
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
* sitemap and metadata generators actually read). Replaces the hand-rolled
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
* glue copied into every project — no `any`, one source of truth for editors,
* one stable read location for the engine.
*
* Idempotent and order-independent: if either the checkbox OR an existing
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
*
* // collections/Pages.ts
* import { buildNoindexField } from '@intecion/ipal-kit'
* fields: [ /* … *\/ buildNoindexField() ],
*/
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
const {
name = 'noindex',
description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.',
label = 'Wyklucz z indeksowania (noindex)',
metaPath = 'meta.noindex',
overrides = {},
} = args
const segments = metaPath.split('.')
const mirror: FieldHook = ({ data, value }) => {
const shouldNoindex = Boolean(value ?? readPath(data as Record<string, unknown>, segments))
if (data && typeof data === 'object') {
writePath(data as Record<string, unknown>, segments, shouldNoindex)
}
return shouldNoindex
}
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides
return {
name,
type: 'checkbox',
admin: {
description,
position: 'sidebar',
...adminOverrides,
},
defaultValue: false,
hooks: {
...hooksOverrides,
// mirror runs first, then any project-supplied beforeChange hooks.
beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],
},
label,
...restOverrides,
} as CheckboxField
}
+1
View File
@@ -9,6 +9,7 @@ export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
export { createManifestHandler } from './buildManifest.js'
export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { buildRobots } from './buildRobots.js'
export type { RobotsRules } from './buildRobots.js'