MCPcopy Create free account
hub / github.com/Oslonline/dithering-studio / useSyncLanguageWithPath

Function useSyncLanguageWithPath

src/hooks/useSyncLanguageWithPath.ts:29–115  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

27 * - Keeps i18n language aligned with the path locale.
28 */
29export function useSyncLanguageWithPath() {
30 const { i18n } = useTranslation();
31 const location = useLocation();
32 const navigate = useNavigate();
33
34 useEffect(() => {
35 const sp = new URLSearchParams(location.search);
36
37 // 1) Legacy migration: ?lang=fr -> /fr/... (preserve other params)
38 const legacyLangRaw = sp.get('lang');
39 const legacyLang = legacyLangRaw ? normalizeLang(legacyLangRaw) : undefined;
40 if (legacyLangRaw) {
41 sp.delete('lang');
42
43 const { restPath } = stripLangPrefix(location.pathname);
44 const targetPath = withLangPrefix(restPath, legacyLang ?? 'en');
45 navigate(
46 {
47 pathname: targetPath,
48 search: sp.toString(),
49 hash: location.hash
50 },
51 { replace: true }
52 );
53
54 if (i18n.language !== (legacyLang ?? 'en')) {
55 i18n.changeLanguage(legacyLang ?? 'en');
56 }
57 return;
58 }
59
60 // 2) Ensure we always have a locale prefix.
61 // If the user lands on a legacy (no-locale) URL, choose a default based on
62 // detected language (navigator/localStorage) instead of always forcing /en/.
63 const pathLang = getPathLang(location.pathname);
64 if (!pathLang) {
65 const detected = normalizeLang(i18n.resolvedLanguage || i18n.language);
66 const preferred = detected !== 'en' ? detected : getBrowserPreferredLanguage();
67
68 const targetPath = withLangPrefix(location.pathname || '/', preferred);
69 navigate(
70 {
71 pathname: targetPath,
72 search: location.search,
73 hash: location.hash
74 },
75 { replace: true }
76 );
77 if (i18n.language !== preferred) i18n.changeLanguage(preferred);
78 return;
79 }
80
81 // 3) Normalize /en -> /en/
82 if (location.pathname === `/${pathLang}`) {
83 navigate(
84 {
85 pathname: `/${pathLang}/`,
86 search: location.search,

Callers 1

LanguagePathSyncFunction · 0.90

Calls 6

normalizeLangFunction · 0.90
stripLangPrefixFunction · 0.90
withLangPrefixFunction · 0.90
getPathLangFunction · 0.90
replaceLangPrefixFunction · 0.90

Tested by

no test coverage detected