65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
'use client';
|
|
|
|
import { usePathname } from 'next/navigation';
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
import enTranslations from '../../messages/en.json';
|
|
import hrTranslations from '../../messages/hr.json';
|
|
|
|
type NestedMessages = {
|
|
[key: string]: string | NestedMessages;
|
|
};
|
|
|
|
// Dobavi vrijednost po path-u (npr. 'common.button.submit')
|
|
function getNestedTranslation(obj: NestedMessages, path: string): string {
|
|
const keys = path.split('.');
|
|
let current: any = obj;
|
|
|
|
for (const key of keys) {
|
|
if (current[key] === undefined) {
|
|
console.warn(`Translation key not found: ${path}`);
|
|
return path;
|
|
}
|
|
current = current[key];
|
|
}
|
|
|
|
if (typeof current !== 'string') {
|
|
console.warn(`Translation value for ${path} is not a string`);
|
|
return path;
|
|
}
|
|
|
|
return current;
|
|
}
|
|
|
|
export function useTranslation() {
|
|
const pathname = usePathname();
|
|
|
|
// Koristimo useState za praćenje locale-a kako bi izbjegli hydration error
|
|
const [locale, setLocale] = useState('hr'); // Default na 'hr' za prvo renderiranje
|
|
|
|
// Detekcija trenutnog jezika iz URL-a - ovo će biti u useEffect da bi radilo samo na klijentu
|
|
useEffect(() => {
|
|
const detectedLocale = pathname.startsWith('/en') ? 'en' : 'hr';
|
|
setLocale(detectedLocale);
|
|
}, [pathname]);
|
|
|
|
// Odabir odgovarajućeg prijevoda
|
|
const translations = useMemo(() => {
|
|
return locale === 'en' ? enTranslations : hrTranslations;
|
|
}, [locale]);
|
|
|
|
// Funkcija za dohvaćanje prevedenog stringa
|
|
const t = (key: string, variables?: Record<string, string | number>) => {
|
|
let text = getNestedTranslation(translations as unknown as NestedMessages, key);
|
|
|
|
// Replace variables if they exist
|
|
if (variables) {
|
|
Object.entries(variables).forEach(([varName, value]) => {
|
|
text = text.replace(new RegExp(`{${varName}}`, 'g'), String(value));
|
|
});
|
|
}
|
|
|
|
return text;
|
|
};
|
|
|
|
return { t, locale };
|
|
}
|