import React, { useMemo, useCallback, useRef, type FC } from 'react'; import { history, useIntl, useLocale, useLocation, useSiteData } from 'dumi'; import { Box, Button, Drawer, DrawerOverlay, DrawerContent, DrawerBody, DrawerCloseButton, Menu, MenuButton, MenuList, MenuOptionGroup, MenuItemOption, Stack, Show, Hide, useDisclosure } from '@chakra-ui/react'; import { ChevronDownIcon } from '@chakra-ui/icons'; type ILocaleItem = ReturnType['locales'][0]; function getTargetLocalePath({ pathname, current, target }: { pathname: string; current: ILocaleItem; target: ILocaleItem; }) { const clearPath = 'base' in current ? pathname.replace(current.base.replace(/\/$/, ''), '') : pathname.replace(new RegExp(`${current.suffix}$`), ''); return 'base' in target ? `${target.base}${clearPath}`.replace(/^\/\//, '/') : `${clearPath}${target.suffix}`; } const LangSwitch: FC = () => { const { locales } = useSiteData(); const { locale } = useIntl(); const { pathname } = useLocation(); const current = useLocale(); const { isOpen, onOpen, onClose } = useDisclosure(); const finalFocusRef = useRef(null); const localName = useMemo(() => { return locales.find((v) => v.id === locale)?.name; }, [locales, locale]); const changeLocale = useCallback( (localeId: string) => { history.push( getTargetLocalePath({ pathname, current, target: locales.find(({ id }) => id === localeId)! }) ); }, [locales, pathname] ); // do not render in single language if (locales.length <= 1) return null; return ( } colorScheme="brand" > {localName} changeLocale(ev as string)} > {locales.map(({ id, name }) => ( {name} ))} {locales.map(({ id, name }) => ( ))} ); }; export default LangSwitch;