'use client'; import { useRouter as _useRouter } from 'next/navigation'; import { urlLocaleMatcherRegex } from '../utils'; import { useLocalization } from './use-localization'; import { LocaleUrlStrategy } from '../localization'; const isNavigableHref = (href: string) => { if (!href || typeof href !== 'string') return false; const trimmedHref = href.trim(); if (!trimmedHref) return false; if (trimmedHref === '#') return true; if (trimmedHref.startsWith('mailto:') || trimmedHref.startsWith('tel:')) { return true; } try { new URL(trimmedHref, 'http://localhost'); return true; } catch { return false; } }; export const useRouter = () => { const { locale, locales, localeUrlStrategy, defaultLocaleValue } = useLocalization(); const defaultLocale = locales.find((l) => l.value === defaultLocaleValue); const router = _useRouter(); const pushOrReplace = ( fn: (href: string, options?) => void, href: string, options? ) => { if (!isNavigableHref(href)) { return fn('#', options); } const trimmedHref = href.trim(); if ( trimmedHref.startsWith('http') || trimmedHref.startsWith('//') || trimmedHref.startsWith('mailto:') || trimmedHref.startsWith('tel:') || trimmedHref.startsWith('#') ) { return fn(trimmedHref, options); } try { const url = new URL(trimmedHref, window.location.origin); const pathnameWithoutLocale = url.pathname.replace( urlLocaleMatcherRegex, '' ); url.pathname = `${ localeUrlStrategy === LocaleUrlStrategy.Subdomain || (locale === defaultLocale?.value && [LocaleUrlStrategy.HideDefaultLocale].includes( localeUrlStrategy as LocaleUrlStrategy )) ? '' : `/${locale}` }${pathnameWithoutLocale}`; return fn(url.href, options); } catch { return fn('#', options); } }; return { ...router, push: (href: string, options?) => pushOrReplace(router.push, href, options), replace: (href: string, options?) => pushOrReplace(router.replace, href, options) } as typeof router; };