Skip to content

fix(ui): preserve localized blocks and arrays when using CopyToLocale #13216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions packages/payload/src/utilities/traverseFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const traverseArrayOrBlocksField = ({
fillEmpty: boolean
leavesFirst: boolean
parentIsLocalized: boolean
parentPath?: string
parentPath: string
parentRef?: unknown
}) => {
if (fillEmpty) {
Expand Down Expand Up @@ -403,7 +403,18 @@ export const traverseFields = ({
currentRef &&
typeof currentRef === 'object'
) {
if (fieldShouldBeLocalized({ field, parentIsLocalized: parentIsLocalized! })) {
// TODO: `?? field.localized ?? false` shouldn't be necessary, but right now it
// is so that all fields are correctly traversed in copyToLocale and
// therefore pass the localization integration tests.
// I tried replacing the `!parentIsLocalized` condition with `parentIsLocalized === false`
// in `fieldShouldBeLocalized`, but several tests failed. We must be calling it with incorrect
// parameters somewhere.
if (
fieldShouldBeLocalized({
field,
parentIsLocalized: parentIsLocalized ?? field.localized ?? false,
})
) {
if (Array.isArray(currentRef)) {
return
}
Expand All @@ -423,6 +434,7 @@ export const traverseFields = ({
fillEmpty,
leavesFirst,
parentIsLocalized: true,
parentPath,
parentRef: currentParentRef,
})
}
Expand All @@ -436,6 +448,7 @@ export const traverseFields = ({
fillEmpty,
leavesFirst,
parentIsLocalized: parentIsLocalized!,
parentPath,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were forgetting about forward parentPath here

parentRef: currentParentRef,
})
}
Expand Down
64 changes: 34 additions & 30 deletions packages/ui/src/utilities/copyDataFromLocale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
formatErrors,
type PayloadRequest,
type ServerFunction,
traverseFields,
} from 'payload'
import { fieldAffectsData, fieldShouldBeLocalized, tabHasName } from 'payload/shared'

Expand Down Expand Up @@ -70,8 +71,9 @@ function iterateFields(
// if the field has no value, take the source value
if (
field.name in toLocaleData &&
// only replace if the target value is null or undefined
[null, undefined].includes(toLocaleData[field.name]) &&
// only replace if the target value is null, undefined, or empty array
([null, undefined].includes(toLocaleData[field.name]) ||
(Array.isArray(toLocaleData[field.name]) && toLocaleData[field.name].length === 0)) &&
Comment on lines +74 to +76
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MongoDB and PostgreSQL behave differently when querying documents that don't exist in a specific locale:

  • PostgreSQL: Returns the document with data from the fallback locale
  • MongoDB: Returns the document with empty arrays for localized fields

This difference caused copyToLocale to fail in MongoDB because the merge algorithm only checked for null or undefined values, but not empty arrays. When MongoDB returned content: [] for a non-existent locale, the algorithm would attempt to iterate over the empty array instead of using the source locale's data.

field.name in fromLocaleData
) {
toLocaleData[field.name] = fromLocaleData[field.name]
Expand Down Expand Up @@ -190,14 +192,22 @@ function mergeData(
return toLocaleData
}

function removeIds(data: Data): Data {
if (Array.isArray(data)) {
return data.map(removeIds)
}
if (typeof data === 'object' && data !== null) {
const { id: _id, ...rest } = data
return Object.fromEntries(Object.entries(rest).map(([key, value]) => [key, removeIds(value)]))
}
/**
* We don't have to recursively remove all ids,
* just the ones from the fields inside a localized array or block.
*/
function removeIdIfParentIsLocalized(data: Data, fields: Field[]): Data {
traverseFields({
callback: ({ parentIsLocalized, ref }) => {
if (parentIsLocalized) {
delete (ref as { id: unknown }).id
}
},
fields,
fillEmpty: false,
ref: data,
})

return data
}

Expand Down Expand Up @@ -306,21 +316,23 @@ export const copyDataFromLocale = async (args: CopyDataFromLocaleArgs) => {
throw new Error(`Error fetching data from locale "${toLocale}"`)
}

const fromLocaleDataWithoutID = removeIds(fromLocaleData.value)
const toLocaleDataWithoutID = removeIds(toLocaleData.value)
const fields = globalSlug
? globals[globalSlug].config.fields
: collections[collectionSlug].config.fields

const fromLocaleDataWithoutID = fromLocaleData.value
const toLocaleDataWithoutID = toLocaleData.value

const dataWithID = overrideData
? fromLocaleDataWithoutID
: mergeData(fromLocaleDataWithoutID, toLocaleDataWithoutID, fields, req, false)

const data = removeIdIfParentIsLocalized(dataWithID, fields)

return globalSlug
? await payload.updateGlobal({
slug: globalSlug,
data: overrideData
? fromLocaleDataWithoutID
: mergeData(
fromLocaleDataWithoutID,
toLocaleDataWithoutID,
globals[globalSlug].config.fields,
req,
false,
),
data,
locale: toLocale,
overrideAccess: false,
req,
Expand All @@ -329,15 +341,7 @@ export const copyDataFromLocale = async (args: CopyDataFromLocaleArgs) => {
: await payload.update({
id: docID,
collection: collectionSlug,
data: overrideData
? fromLocaleDataWithoutID
: mergeData(
fromLocaleDataWithoutID,
toLocaleDataWithoutID,
collections[collectionSlug].config.fields,
req,
false,
),
data,
locale: toLocale,
overrideAccess: false,
req,
Expand Down
5 changes: 5 additions & 0 deletions test/localization/collections/NestedToArrayAndBlock/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export const NestedToArrayAndBlock: CollectionConfig = {
{
slug: 'block',
fields: [
{
name: 'someText',
type: 'text',
localized: true,
},
{
name: 'array',
type: 'array',
Expand Down
26 changes: 0 additions & 26 deletions test/localization/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,32 +431,6 @@ describe('Localization', () => {
await expect(arrayField).toHaveValue(sampleText)
})

test('should copy block to locale', async () => {
const sampleText = 'Copy this text'
const blocksCollection = new AdminUrlUtil(serverURL, blocksCollectionSlug)
await page.goto(blocksCollection.create)
await changeLocale(page, 'pt')
const addBlock = page.locator('.blocks-field__drawer-toggler')
await addBlock.click()
const selectBlock = page.locator('.blocks-drawer__block button')
await selectBlock.click()
const addContentButton = page
.locator('#field-content__0__content')
.getByRole('button', { name: 'Add Content' })
await addContentButton.click()
await selectBlock.click()
const textField = page.locator('#field-content__0__content__0__text')
await expect(textField).toBeVisible()
await textField.fill(sampleText)
await saveDocAndAssert(page)

await openCopyToLocaleDrawer(page)
await setToLocale(page, 'English')
await runCopy(page)

await expect(textField).toHaveValue(sampleText)
})

Comment on lines -434 to -459
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test was migrated to int. See comment below

test('should default source locale to current locale', async () => {
await changeLocale(page, spanishLocale)
await createAndSaveDoc(page, url, { title })
Expand Down
Loading
Loading