'use client'; import { LocalizationContext } from '../localization/provider'; import { useContext } from 'react'; import { setCookie, urlLocaleMatcherRegex } from '../utils'; import { LocaleUrlStrategy } from '../localization'; import { useRouter } from 'next/navigation'; export const useLocalization = () => { const { translate, locale, currency, locales, currencies, defaultLocaleValue, defaultCurrencyCode, localeUrlStrategy } = useContext(LocalizationContext); const router = useRouter(); /** * Sets the locale in the URL. * @param locale Locale value defined in the settings. */ const setLocale = (locale: string) => { const { protocol, hostname, port, search, pathname } = location; const pathnameWithoutLocale = pathname.replace(urlLocaleMatcherRegex, ''); let targetUrl; if (localeUrlStrategy === LocaleUrlStrategy.Subdomain) { const hostParts = hostname.split('.'); const subDomain = hostParts[0]; const isSubdomainLocale = locales.some((loc) => loc.value === subDomain); const baseDomain = isSubdomainLocale ? hostParts.slice(1).join('.') : hostname; const formattedPort = port ? `:${port}` : ''; targetUrl = `${protocol}//${locale}.${baseDomain}${formattedPort}${pathnameWithoutLocale}${search}`; } else { const shouldHideLocale = locale === defaultLocaleValue && localeUrlStrategy !== LocaleUrlStrategy.ShowAllLocales; const localePath = shouldHideLocale ? '' : `/${locale}`; targetUrl = `${localePath}${pathnameWithoutLocale}${search}`; } // router.push is not used because reloading the page also clears the client side cache. location.href = targetUrl; }; /** * Sets the currency. * * If the currency is linked to the locale by using `getActiveCurrencyCode` function in the settings, * you need to use `setLocale` instead of this. * @param currency Currency code defined in the settings. */ const setCurrency = (currency: string) => { // It is a temp cookie to set currency in `currency` middleware. setCookie('pz-set-currency', currency); location.reload(); }; return { /** * Translate function * @param path * Path of the translation. * It is a dot separated string e.g. "common.header.title". * "common" is the file name in the translations folder. * "header" is the key in the file. * "title" is the value of the key. * @returns {string} Translated value */ t: (path: string) => translate(path), setLocale, setCurrency, locale, currency, locales, currencies, defaultLocaleValue, defaultCurrencyCode, localeUrlStrategy }; };