73 lines
2.3 KiB
JavaScript
73 lines
2.3 KiB
JavaScript
'use strict';
|
|
|
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
|
var navigation = require('next/navigation');
|
|
var React = require('react');
|
|
var useLocale = require('../../react-client/useLocale.js');
|
|
var utils$1 = require('../../shared/utils.js');
|
|
var syncLocaleCookie = require('../shared/syncLocaleCookie.js');
|
|
var utils = require('../shared/utils.js');
|
|
|
|
/**
|
|
* Returns a wrapped instance of `useRouter` from `next/navigation` that
|
|
* will automatically localize the `href` parameters it receives.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* 'use client';
|
|
*
|
|
* import {useRouter} from 'next-intl/client';
|
|
*
|
|
* const router = useRouter();
|
|
*
|
|
* // When the user is on `/en`, the router will navigate to `/en/about`
|
|
* router.push('/about');
|
|
*
|
|
* // Optionally, you can switch the locale by passing the second argument
|
|
* router.push('/about', {locale: 'de'});
|
|
* ```
|
|
*/
|
|
function useBaseRouter(localePrefix, localeCookie) {
|
|
const router = navigation.useRouter();
|
|
const locale = useLocale.default();
|
|
const pathname = navigation.usePathname();
|
|
return React.useMemo(() => {
|
|
function localize(href, nextLocale) {
|
|
let curPathname = window.location.pathname;
|
|
const basePath = utils.getBasePath(pathname);
|
|
if (basePath) curPathname = curPathname.replace(basePath, '');
|
|
const targetLocale = nextLocale || locale;
|
|
|
|
// We generate a prefix in any case, but decide
|
|
// in `localizeHref` if we apply it or not
|
|
const prefix = utils$1.getLocalePrefix(targetLocale, localePrefix);
|
|
return utils$1.localizeHref(href, targetLocale, locale, curPathname, prefix);
|
|
}
|
|
function createHandler(fn) {
|
|
return function handler(href, options) {
|
|
const {
|
|
locale: nextLocale,
|
|
...rest
|
|
} = options || {};
|
|
syncLocaleCookie.default(localeCookie, pathname, locale, nextLocale);
|
|
const args = [localize(href, nextLocale)];
|
|
if (Object.keys(rest).length > 0) {
|
|
args.push(rest);
|
|
}
|
|
|
|
// @ts-expect-error -- This is ok
|
|
return fn(...args);
|
|
};
|
|
}
|
|
return {
|
|
...router,
|
|
push: createHandler(router.push),
|
|
replace: createHandler(router.replace),
|
|
prefetch: createHandler(router.prefetch)
|
|
};
|
|
}, [locale, localeCookie, localePrefix, pathname, router]);
|
|
}
|
|
|
|
exports.default = useBaseRouter;
|