Files
soorya-carpet/resources/js/utils/i18n.ts

91 lines
1.9 KiB
TypeScript

import { usePage } from '@inertiajs/react';
// Type definitions for our translations
interface Translations {
nav: {
'about-us': string;
art: string;
products: string;
bespoke: string;
faq: string;
contact: string;
};
footer: {
desc: {
title: string;
company: string;
address: string;
phone: string;
email: string;
};
// Add other translation sections as needed
};
}
interface PageProps {
locale: string;
translations: Translations;
[key: string]: any;
}
/**
* Translation function
*/
export function t(
translations: any,
key: string,
replacements: Record<string, string> = {},
): string {
if (!translations) {
console.warn('No translations provided');
return key;
}
const keys = key.split('.');
let value: any = translations;
for (const k of keys) {
if (value && typeof value === 'object' && k in value) {
value = value[k];
} else {
console.warn(`Translation key not found: ${key}`);
return key;
}
}
if (typeof value !== 'string') {
return key;
}
let text = value;
Object.entries(replacements).forEach(([k, v]) => {
text = text.replace(new RegExp(`:${k}`, 'g'), v);
});
return text;
}
/**
* React hook for translations
*/
export function useTranslations() {
const { translations } = usePage<PageProps>().props;
const translate = (
key: string,
replacements: Record<string, string> = {},
) => {
return t(translations, key, replacements);
};
return { t: translate, translations };
}
/**
* Hook to get current locale
*/
export function useLocale() {
const { locale } = usePage<PageProps>().props;
return locale;
}