From 06400ad2b5d11963d3beeb1ecc392d44b0d5c6c7 Mon Sep 17 00:00:00 2001 From: Jan Amann Date: Sat, 21 Sep 2024 04:23:50 +0200 Subject: [PATCH] fix: Use default messages from `en` as fallback if messages are missing in another locale (#7054) * fix: Use default messages from `en` as fallback if messages are missing in another locale * chore: Remove `deepmerge` dependency in favor of a more optimized custom function * chore: Revert changes to lockfile --- apps/site/i18n.tsx | 19 +++++++++++++------ apps/site/util/deepMerge.ts | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 apps/site/util/deepMerge.ts diff --git a/apps/site/i18n.tsx b/apps/site/i18n.tsx index 5e235d8e3d15..efed3f4d9c6f 100644 --- a/apps/site/i18n.tsx +++ b/apps/site/i18n.tsx @@ -3,20 +3,27 @@ import { getRequestConfig } from 'next-intl/server'; import { availableLocaleCodes } from '@/next.locales.mjs'; +import deepMerge from './util/deepMerge'; + // Loads the Application Locales/Translations Dynamically const loadLocaleDictionary = async (locale: string) => { + // This enables HMR on the English Locale, so that instant refresh + // happens while we add/change texts on the source locale + const defaultMessages = await import( + '@node-core/website-i18n/locales/en.json' + ).then(f => f.default); + if (locale === 'en') { - // This enables HMR on the English Locale, so that instant refresh - // happens while we add/change texts on the source locale - return import('@node-core/website-i18n/locales/en.json').then( - f => f.default - ); + return defaultMessages; } if (availableLocaleCodes.includes(locale)) { // Other languages don't really require HMR as they will never be development languages // so we can load them dynamically - return importLocale(locale); + const messages = await importLocale(locale); + + // Use default messages as fallback + return deepMerge(defaultMessages, messages); } throw new Error(`Unsupported locale: ${locale}`); diff --git a/apps/site/util/deepMerge.ts b/apps/site/util/deepMerge.ts new file mode 100644 index 000000000000..751c09a3afe1 --- /dev/null +++ b/apps/site/util/deepMerge.ts @@ -0,0 +1,20 @@ +export default function deepMerge( + obj1: Obj1, + obj2: Obj2 +): Obj1 & Obj2 { + const result = { ...obj1 } as Obj1 & Obj2; + + for (const key in obj2) { + if (Object.prototype.hasOwnProperty.call(obj2, key)) { + if (typeof obj2[key] === 'object' && obj2[key] !== null) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + result[key] = deepMerge(result[key] as any, obj2[key] as any); + } else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + result[key] = obj2[key] as any; + } + } + } + + return result; +}