@redocly/theme
Version:
Shared UI components lib
35 lines (27 loc) • 1.14 kB
text/typescript
import { useNavigate } from 'react-router-dom';
import type { L10nConfig } from '@redocly/theme/core/types';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { getPathnameForLocale, withPathPrefix, withoutPathPrefix } from '@redocly/theme/core/utils';
export function useLanguagePicker(): {
currentLocale: L10nConfig['locales'][number] | undefined;
locales: L10nConfig['locales'];
setLocale: (value: string) => void;
} {
const { useL10nConfig, useLoadAndNavigate } = useThemeHooks();
const navigate = useNavigate();
const loadAndNavigate = useLoadAndNavigate();
const { currentLocale, locales, defaultLocale } = useL10nConfig();
const locale = locales.find((l) => l.code === currentLocale);
function setLocale(value: string) {
const newLangPathname = withPathPrefix(
getPathnameForLocale(withoutPathPrefix(location.pathname), defaultLocale, value, locales),
);
const newUrlWithLanguage = `${newLangPathname}${location.search}${location.hash}`;
loadAndNavigate({ navigate, to: newUrlWithLanguage });
}
return {
currentLocale: locale,
locales,
setLocale,
};
}