|
1 | | -'use client'; |
| 1 | +"use client"; |
2 | 2 |
|
3 | | -import { normalizeLocale, type Locale } from '@/lib/i18n'; |
4 | | -import { useEffect } from 'react'; |
| 3 | +import { normalizeLocale, type Locale } from "@/lib/i18n"; |
| 4 | +import { useEffect } from "react"; |
5 | 5 |
|
6 | | -const STORAGE_KEY = 'preferred-lang'; |
| 6 | +const STORAGE_KEY = "preferred-lang"; |
7 | 7 |
|
8 | | -function pathForLocale(locale: Locale): string { |
9 | | - return locale === 'es' ? '/' : `/${locale}`; |
| 8 | +function pathForLocale(locale: Locale, targetPath = ""): string { |
| 9 | + const suffix = targetPath |
| 10 | + ? targetPath.startsWith("/") |
| 11 | + ? targetPath |
| 12 | + : `/${targetPath}` |
| 13 | + : ""; |
| 14 | + const base = `/${locale}`; |
| 15 | + if (suffix === "/" || suffix === "") return base; |
| 16 | + return `${base}${suffix}`; |
10 | 17 | } |
11 | 18 |
|
12 | | -export function LangRedirect({ currentLocale }: { currentLocale: Locale }) { |
| 19 | +export function LangRedirect({ |
| 20 | + currentLocale, |
| 21 | + targetPath = "", |
| 22 | + force = false, |
| 23 | +}: { |
| 24 | + currentLocale: Locale; |
| 25 | + targetPath?: string; |
| 26 | + force?: boolean; |
| 27 | +}) { |
13 | 28 | useEffect(() => { |
14 | 29 | const stored = localStorage.getItem(STORAGE_KEY); |
15 | | - if (stored === 'en' || stored === 'es') { |
16 | | - if (stored !== currentLocale) { |
17 | | - window.location.assign(pathForLocale(stored)); |
18 | | - } |
19 | | - return; |
20 | | - } |
21 | 30 |
|
22 | 31 | const navigatorLang = |
23 | | - typeof navigator !== 'undefined' ? navigator.language || navigator.languages?.[0] : undefined; |
| 32 | + typeof navigator !== "undefined" |
| 33 | + ? navigator.language || navigator.languages?.[0] |
| 34 | + : undefined; |
24 | 35 | const detected = normalizeLocale(navigatorLang); |
25 | 36 |
|
26 | | - if (detected !== currentLocale) { |
27 | | - localStorage.setItem(STORAGE_KEY, detected); |
28 | | - window.location.assign(pathForLocale(detected)); |
| 37 | + const preferred = |
| 38 | + stored === "en" || stored === "es" |
| 39 | + ? (stored as Locale) |
| 40 | + : detected ?? currentLocale; |
| 41 | + |
| 42 | + if (force || preferred !== currentLocale) { |
| 43 | + if (!stored) { |
| 44 | + localStorage.setItem(STORAGE_KEY, preferred); |
| 45 | + } |
| 46 | + window.location.assign(pathForLocale(preferred, targetPath)); |
29 | 47 | } |
30 | | - }, [currentLocale]); |
| 48 | + }, [currentLocale, force, targetPath]); |
31 | 49 |
|
32 | 50 | return null; |
33 | 51 | } |
0 commit comments