Seeder: whole localized arrays keep every language (1.15.4)

createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-12 15:33:35 +01:00
co-authored by Claude Opus 5.5
parent 4d1de4c66a
commit 00e814e3ca
6 changed files with 315 additions and 12 deletions
+87 -10
View File
@@ -25,19 +25,81 @@ export function isLocalizedValue(v: unknown, codes: string[]): v is Record<strin
return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
}
/** The schema of the value being localized: its fields, or its block types (`blocks` field rows). */
export type SeedSchema = { blocks?: Record<string, readonly SeedField[]>; fields?: readonly SeedField[] }
/** The slice of a Payload field config the seed helper reads. */
export type SeedField = {
blocks?: readonly ({ fields: readonly SeedField[]; slug: string } | string)[]
fields?: readonly SeedField[]
localized?: boolean
name?: string
tabs?: readonly { fields: readonly SeedField[]; name?: string }[]
type: string
}
/** Named fields at one level: rows, collapsibles and unnamed tabs add no path segment. */
function namedFields(fields: readonly SeedField[] = []): Map<string, SeedField> {
const out = new Map<string, SeedField>()
for (const f of fields) {
if (f.type === 'tabs') {
for (const tab of f.tabs ?? []) {
if (tab.name) {out.set(tab.name, { name: tab.name, type: 'group', fields: tab.fields })}
else {for (const [k, v] of namedFields(tab.fields)) {out.set(k, v)}}
}
} else if (f.name) {out.set(f.name, f)}
else if (f.fields) {for (const [k, v] of namedFields(f.fields)) {out.set(k, v)}}
}
return out
}
/** The schema below a field: a group's or array's fields, or a blocks field's block types. */
function schemaOf(field: SeedField | undefined, blockConfigs?: (slug: string) => readonly SeedField[] | undefined): SeedSchema | undefined {
if (!field) {return undefined}
if (field.type === 'blocks') {
const blocks: Record<string, readonly SeedField[]> = {}
for (const b of field.blocks ?? []) {
if (typeof b === 'string') {
const fields = blockConfigs?.(b)
if (fields) {blocks[b] = fields}
} else {blocks[b.slug] = b.fields}
}
return { blocks }
}
return field.fields ? { fields: field.fields } : undefined
}
/**
* The value for one locale. Arrays (array fields, blocks) keep the ids of the
* rows already stored at the same index — new ids would wipe the other
* locales' texts. A block row keeps its id only when its blockType matches.
* The value for one locale. Rows of arrays and blocks keep the ids of the rows
* already stored at the same index — new ids would wipe the other locales' texts.
* A block row keeps its id only when its blockType matches. A whole localized
* value (`fields: { pl: [...], en: [...] }`) is localized again after its locale
* is picked, so its rows keep the stored ids too.
*
* With `schema` (writeLocales passes the collection's or global's fields), a field
* that is itself localized (`localized: true` array, blocks or group) gets no
* stored ids: its rows belong to one locale and are never shared.
* undefined = leave the field out.
*/
export function localize(value: unknown, locale: string | undefined, existing: unknown, codes: string[]): unknown {
if (isLocalizedValue(value, codes)) {return locale ? value[locale] : undefined}
export function localize(
value: unknown,
locale: string | undefined,
existing: unknown,
codes: string[],
schema?: SeedSchema,
blockConfigs?: (slug: string) => readonly SeedField[] | undefined,
): unknown {
if (isLocalizedValue(value, codes)) {
const picked = locale ? value[locale] : undefined
return picked === undefined ? undefined : localize(picked, locale, existing, codes, schema, blockConfigs)
}
if (Array.isArray(value)) {
const rows = Array.isArray(existing) ? (existing as unknown[]) : []
return value.map((item, i) => {
const row = rows[i] as Record<string, unknown> | undefined
const out = localize(item, locale, row, codes)
const type = isPlainObject(item) && typeof item.blockType === 'string' ? item.blockType : undefined
const rowSchema = schema?.blocks ? (type && schema.blocks[type] ? { fields: schema.blocks[type] } : undefined) : schema
const out = localize(item, locale, row, codes, rowSchema, blockConfigs)
if (!isPlainObject(out) || !row?.id) {return out ?? null}
if (out.blockType !== undefined && row.blockType !== undefined && out.blockType !== row.blockType) {return out}
return { ...out, id: row.id }
@@ -45,9 +107,12 @@ export function localize(value: unknown, locale: string | undefined, existing: u
}
if (isPlainObject(value)) {
const ex = isPlainObject(existing) ? existing : {}
const fields = schema?.fields ? namedFields(schema.fields) : undefined
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value)) {
const r = localize(v, locale, ex[k], codes)
const field = fields?.get(k)
// A localized field's stored rows belong to another locale — never reuse their ids.
const r = localize(v, locale, field?.localized ? undefined : ex[k], codes, schemaOf(field, blockConfigs), blockConfigs)
if (r !== undefined) {out[k] = r}
}
return out
@@ -132,6 +197,16 @@ export function editedSinceSeed({
export type SeedTarget = { collection: string; id: number | string } | { global: string }
/** The fields of a seed target (collection or global) and the config's shared blocks, for localize. */
export function seedSchemaOf(payload: BasePayload, target: SeedTarget): { blockConfigs: (slug: string) => readonly SeedField[] | undefined; schema?: SeedSchema } {
const config = payload.config as { blocks?: { fields: SeedField[]; slug: string }[]; collections?: { fields: SeedField[]; slug: string }[]; globals?: { fields: SeedField[]; slug: string }[] }
const owner = 'global' in target ? config.globals?.find((g) => g.slug === target.global) : config.collections?.find((c) => c.slug === target.collection)
return {
blockConfigs: (slug) => config.blocks?.find((b) => b.slug === slug)?.fields,
...(owner ? { schema: { fields: owner.fields } } : {}),
}
}
export type WriteLocalesOptions = {
/** Passed to every write — see docs/seeding.md § Context flags. */
context?: Record<string, unknown>
@@ -161,20 +236,21 @@ export async function writeLocales(
{ context = {}, draft = false }: WriteLocalesOptions = {},
): Promise<void> {
const { codes, defaultLocale } = localesOf(payload)
const { blockConfigs, schema } = seedSchemaOf(payload, target)
const local = (locale: string | undefined, rows: unknown) => localize(data, locale, rows, codes, schema, blockConfigs)
const write = (value: unknown, locale: string | undefined) => {
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
return 'global' in target
? payload.updateGlobal({ slug: target.global as never, context, data: value as never, depth: 0, ...loc })
: payload.update({ id: target.id, collection: target.collection as never, context, data: value as never, depth: 0, ...loc })
}
await write(localize(data, defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft), codes), defaultLocale)
await write(local(defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft)), defaultLocale)
const others = codes.filter((c) => c !== defaultLocale)
if (!others.length) {return}
const rows = await readSeedTarget(payload, target, defaultLocale, draft)
for (const locale of others) {await write(localize(data, locale, rows, codes), locale)}
for (const locale of others) {await write(local(locale, rows), locale)}
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
/** Field types whose stored value is a choice, not text an editor wrote. */
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
@@ -189,6 +265,7 @@ export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; t
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
export function hasContent(v: unknown): boolean {
if (typeof v === 'string') {return v.trim() !== ''}
if (typeof v === 'number' || v === true) {return true}