feat(cms): localize translatable Globals fields with lossless migration (MITHOME-111)
Mark every translatable text/textarea field of the Home, About, Services,
Contact and Common globals as localized. Icons, row ids, the external
flag and the postal address stay shared; CTA hrefs are localized because
internal routes differ per locale. String lists (paragraphs, bullets,
features, spec items) are localized at array level so locales can have
different item counts; structured rows share order/icons and localize
only their inner text.
Existing data is not re-seeded (that would overwrite admin edits): a
Payload migration wraps legacy values into { hu: value } on the published
global and every draft/version record, idempotently, and runs on
production startup via prodMigrations. Paths are derived from the Global
configs themselves so the migration cannot drift from the schema.
OpenSpec change: openspec/changes/localize-globals-mithome-111
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9b5ca94030
commit
829f543962
@@ -0,0 +1,131 @@
|
||||
import { collectLocalizedPaths, topLevelKeys, unwrapLocalized, wrapLocalized } from './localize-paths'
|
||||
import { Home } from '../globals/Home'
|
||||
import { Common } from '../globals/Common'
|
||||
|
||||
type Doc = Record<string, unknown>
|
||||
|
||||
const FIELDS = [
|
||||
{
|
||||
name: 'hero',
|
||||
type: 'group',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'bullets', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
fields: [
|
||||
{ name: 'icon', type: 'text' },
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'features', type: 'array', localized: true, fields: [{ name: 'value', type: 'text' }] },
|
||||
],
|
||||
},
|
||||
{ name: 'address', type: 'text' },
|
||||
{ name: 'external', type: 'checkbox' },
|
||||
]
|
||||
|
||||
function legacyDoc(): Doc {
|
||||
return {
|
||||
hero: { title: 'Cím', bullets: [{ id: 'b1', value: 'Egy' }] },
|
||||
items: [
|
||||
{ id: 'r1', icon: 'star', title: 'Első', features: [{ id: 'f1', value: 'A' }] },
|
||||
{ id: 'r2', icon: 'bolt', title: 'Második', features: [] },
|
||||
],
|
||||
address: 'Budapest',
|
||||
external: false,
|
||||
}
|
||||
}
|
||||
|
||||
describe('collectLocalizedPaths', () => {
|
||||
it('should collect localized leaves through groups and shared array rows', () => {
|
||||
expect(collectLocalizedPaths(FIELDS)).toEqual([
|
||||
['hero', 'title'],
|
||||
['hero', 'bullets'],
|
||||
['items', '[]', 'title'],
|
||||
['items', '[]', 'features'],
|
||||
])
|
||||
})
|
||||
|
||||
it('should throw on layout fields that could hide localized data', () => {
|
||||
expect(() => collectLocalizedPaths([{ type: 'tabs' }])).toThrow('unsupported field type "tabs"')
|
||||
})
|
||||
|
||||
it('should derive paths from the real Global configs', () => {
|
||||
const homePaths = collectLocalizedPaths(Home.fields as never)
|
||||
expect(homePaths).toContainEqual(['hero', 'trustBullets'])
|
||||
expect(homePaths).toContainEqual(['services', 'items', '[]', 'features'])
|
||||
expect(homePaths).not.toContainEqual(['about', 'usps', '[]', 'icon'])
|
||||
expect(collectLocalizedPaths(Common.fields as never)).not.toContainEqual(['footer', 'address'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('wrapLocalized', () => {
|
||||
const paths = collectLocalizedPaths(FIELDS)
|
||||
|
||||
it('should wrap strings and arrays under the hu locale and keep shared values', () => {
|
||||
const doc = legacyDoc()
|
||||
const changed = wrapLocalized(doc, paths)
|
||||
|
||||
expect(changed).toBe(6)
|
||||
expect(doc.hero).toEqual({ title: { hu: 'Cím' }, bullets: { hu: [{ id: 'b1', value: 'Egy' }] } })
|
||||
expect(doc.items).toEqual([
|
||||
{ id: 'r1', icon: 'star', title: { hu: 'Első' }, features: { hu: [{ id: 'f1', value: 'A' }] } },
|
||||
{ id: 'r2', icon: 'bolt', title: { hu: 'Második' }, features: { hu: [] } },
|
||||
])
|
||||
expect(doc.address).toBe('Budapest')
|
||||
expect(doc.external).toBe(false)
|
||||
})
|
||||
|
||||
it('should be idempotent on already migrated data', () => {
|
||||
const doc = legacyDoc()
|
||||
wrapLocalized(doc, paths)
|
||||
const snapshot = JSON.stringify(doc)
|
||||
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(JSON.stringify(doc)).toBe(snapshot)
|
||||
})
|
||||
|
||||
it('should leave existing locale maps (e.g. Common.buttons) untouched', () => {
|
||||
const doc: Doc = { hero: { title: { hu: 'Cím', en: 'Title' } } }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(doc).toEqual({ hero: { title: { hu: 'Cím', en: 'Title' } } })
|
||||
})
|
||||
|
||||
it('should skip missing branches and null values', () => {
|
||||
const doc: Doc = { hero: { title: null }, items: null }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
expect(doc).toEqual({ hero: { title: null }, items: null })
|
||||
})
|
||||
|
||||
it('should not descend into a row path when the stored value is not an array', () => {
|
||||
const doc: Doc = { items: { unexpected: true } }
|
||||
expect(wrapLocalized(doc, paths)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('unwrapLocalized', () => {
|
||||
const paths = collectLocalizedPaths(FIELDS)
|
||||
|
||||
it('should restore the legacy shape from the hu value', () => {
|
||||
const doc = legacyDoc()
|
||||
wrapLocalized(doc, paths)
|
||||
;(doc.hero as Doc).title = { hu: 'Cím', en: 'Title' }
|
||||
|
||||
expect(unwrapLocalized(doc, paths)).toBe(6)
|
||||
expect(doc).toEqual(legacyDoc())
|
||||
})
|
||||
|
||||
it('should fall back to null when the hu value is missing', () => {
|
||||
const doc: Doc = { hero: { title: { en: 'Title' } } }
|
||||
unwrapLocalized(doc, paths)
|
||||
expect(doc).toEqual({ hero: { title: null } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('topLevelKeys', () => {
|
||||
it('should return unique first segments', () => {
|
||||
expect(topLevelKeys(collectLocalizedPaths(FIELDS))).toEqual(['hero', 'items'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* MITHOME-111: pure helpers for the "field became `localized: true`"
|
||||
* data migration (design D4).
|
||||
*
|
||||
* WHY config-driven paths: the Global configs are the single source of
|
||||
* truth for which fields are localized — deriving the migration paths from
|
||||
* them means the migration can never drift from the schema.
|
||||
*
|
||||
* Storage shapes (Payload mongooseAdapter):
|
||||
* non-localized text -> "szöveg" localized -> { hu: "szöveg" }
|
||||
* non-localized array -> [{ value }] localized -> { hu: [{ value }] }
|
||||
* A path segment `[]` means "every row of this (shared) array".
|
||||
*/
|
||||
|
||||
type FieldNode = { name?: string; type: string; localized?: boolean; fields?: FieldNode[] }
|
||||
|
||||
export type LocalizedPath = readonly string[]
|
||||
|
||||
const ARRAY_ROWS = '[]'
|
||||
|
||||
/** Layout fields that could hide localized children — not traversed here. */
|
||||
const UNSUPPORTED_CONTAINERS = new Set(['tabs', 'row', 'collapsible', 'blocks'])
|
||||
|
||||
export function collectLocalizedPaths(
|
||||
fields: readonly FieldNode[],
|
||||
prefix: LocalizedPath = [],
|
||||
): LocalizedPath[] {
|
||||
const paths: LocalizedPath[] = []
|
||||
for (const field of fields) {
|
||||
if (UNSUPPORTED_CONTAINERS.has(field.type)) {
|
||||
// DECISION: fail fast rather than silently skip localized data.
|
||||
throw new Error(`collectLocalizedPaths: unsupported field type "${field.type}"`)
|
||||
}
|
||||
if (!field.name) continue
|
||||
const path = [...prefix, field.name]
|
||||
if (field.localized) {
|
||||
paths.push(path)
|
||||
} else if (field.type === 'group') {
|
||||
paths.push(...collectLocalizedPaths(field.fields ?? [], path))
|
||||
} else if (field.type === 'array') {
|
||||
paths.push(...collectLocalizedPaths(field.fields ?? [], [...path, ARRAY_ROWS]))
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
type Transform = (value: unknown) => { value: unknown; changed: boolean }
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function applyAtPath(node: unknown, path: LocalizedPath, transform: Transform): number {
|
||||
if (typeof node !== 'object' || node === null) return 0
|
||||
const [head, ...rest] = path
|
||||
if (head === ARRAY_ROWS) {
|
||||
if (!Array.isArray(node)) return 0
|
||||
return node.reduce<number>((sum, row) => sum + applyAtPath(row, rest, transform), 0)
|
||||
}
|
||||
if (!isPlainObject(node)) return 0
|
||||
if (rest.length > 0) return applyAtPath(node[head], rest, transform)
|
||||
|
||||
const result = transform(node[head])
|
||||
if (result.changed) node[head] = result.value
|
||||
return result.changed ? 1 : 0
|
||||
}
|
||||
|
||||
// WHY in-place mutation instead of structuredClone: raw Mongo documents
|
||||
// carry BSON class instances (ObjectId) that a structured clone would
|
||||
// silently turn into plain objects. Callers pass freshly read documents.
|
||||
function applyAll(doc: Record<string, unknown>, paths: readonly LocalizedPath[], transform: Transform) {
|
||||
return paths.reduce((sum, path) => sum + applyAtPath(doc, path, transform), 0)
|
||||
}
|
||||
|
||||
/** Top-level document keys touched by `paths` — the `$set` scope of a write. */
|
||||
export function topLevelKeys(paths: readonly LocalizedPath[]): string[] {
|
||||
return [...new Set(paths.map((path) => path[0]))]
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps legacy (non-localized) values into `{ [locale]: value }`, in place.
|
||||
* Idempotent: values already stored as a locale map are left untouched,
|
||||
* null/undefined are skipped (nothing to preserve). Returns the number of
|
||||
* values changed.
|
||||
*/
|
||||
export function wrapLocalized(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
locale = 'hu',
|
||||
) {
|
||||
return applyAll(doc, paths, (value) =>
|
||||
typeof value === 'string' || Array.isArray(value)
|
||||
? { value: { [locale]: value }, changed: true }
|
||||
: { value, changed: false },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverse of wrapLocalized (down migration), in place: keeps only
|
||||
* `locale`'s value.
|
||||
* TRADEOFF: every other locale's value is dropped — take a DB dump first.
|
||||
*/
|
||||
export function unwrapLocalized(
|
||||
doc: Record<string, unknown>,
|
||||
paths: readonly LocalizedPath[],
|
||||
locale = 'hu',
|
||||
) {
|
||||
return applyAll(doc, paths, (value) =>
|
||||
isPlainObject(value) ? { value: value[locale] ?? null, changed: true } : { value, changed: false },
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user