Skip to content
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
29 changes: 29 additions & 0 deletions packages/ra-core/src/i18n/useTranslatable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,34 @@ describe('useTranslatable', () => {
const recordForLocale = getRecordForLocale(record, 'fr');
expect(recordForLocale).toEqual(undefined);
});

it('should not modify the original record', () => {
const json =
'{"tags":{"en":["a","b"],"fr":["c"]},"title":{"en":{"en":{"a":1},"b":{"c":2}}}}';
const record = JSON.parse(json);
getRecordForLocale(record, 'en');
expect(record).toEqual(JSON.parse(json));
expect(Object.keys(record.tags.en)).toEqual(['0', '1']);
});

it('should not modify nested objects of the original record', () => {
const json = '{"title":{"en":{"en":{"x":{"en":1}},"x":{"en":2}}}}';
const record = JSON.parse(json);
getRecordForLocale(record, 'en');
expect(record).toEqual(JSON.parse(json));
});

it('should not overwrite a translated value with nested translations', () => {
const record = {
title: {
en: 'Hello',
fr: 'Bonjour',
notes: { en: 'Greeting' },
},
};
expect(getRecordForLocale(record, 'en')).toEqual({
title: 'Hello',
});
});
});
});
8 changes: 5 additions & 3 deletions packages/ra-core/src/i18n/useTranslatable.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState, useMemo } from 'react';
import set from 'lodash/set.js';
import get from 'lodash/get.js';
import has from 'lodash/has.js';
import cloneDeep from 'lodash/cloneDeep.js';
import { TranslatableContextValue } from './TranslatableContext';
import { useLocaleState } from './useLocaleState';
Expand Down Expand Up @@ -60,11 +61,12 @@ export const getRecordForLocale = (record: {} | undefined, locale: string) => {
const paths = getRecordPaths(record);

// For each path, if a path ends with the locale, set the value of the path without the locale
// to the value of the path with the locale
// to the value of the path with the locale.
// Paths under a value already replaced by its translation no longer exist and are skipped.
const recordForLocale = paths.reduce((acc, path) => {
if (path.includes(locale)) {
if (path[path.length - 1] === locale && has(acc, path)) {
const pathWithoutLocale = path.slice(0, -1);
const value = get(record, path);
const value = get(acc, path);
return set(acc, pathWithoutLocale, value);
}
return acc;
Expand Down
Loading