Skip to content
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

fix: Use default messages from en as fallback if messages are missing in another locale #7054

Merged
merged 3 commits into from
Sep 21, 2024
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
19 changes: 13 additions & 6 deletions apps/site/i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down
20 changes: 20 additions & 0 deletions apps/site/util/deepMerge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default function deepMerge<Obj1 extends object, Obj2 extends object>(
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;
}
Loading