1
1
mirror of https://github.com/theoludwig/theoludwig.git synced 2024-11-05 13:01:30 +01:00
.profile/components/Header/Language/index.tsx

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-05-03 10:05:11 +02:00
import { useCallback, useEffect, useState, useRef } from 'react'
import useTranslation from 'next-translate/useTranslation'
import setLanguage from 'next-translate/setLanguage'
import classNames from 'clsx'
2021-12-04 15:52:51 +01:00
import i18n from 'i18n.json'
import { Arrow } from './Arrow'
import { LanguageFlag } from './LanguageFlag'
export const Language: React.FC = () => {
const { lang: currentLanguage } = useTranslation()
const [hiddenMenu, setHiddenMenu] = useState(true)
2022-05-03 10:05:11 +02:00
const languageClickRef = useRef<HTMLDivElement | null>(null)
2021-06-15 20:35:52 +02:00
const handleHiddenMenu = useCallback(() => {
2022-09-04 20:40:58 +02:00
setHiddenMenu((oldHiddenMenu) => {
return !oldHiddenMenu
})
2022-05-03 10:05:11 +02:00
}, [])
2021-06-15 20:35:52 +02:00
useEffect(() => {
2022-05-03 10:05:11 +02:00
const handleClickEvent = (event: MouseEvent): void => {
if (languageClickRef.current == null || event.target == null) {
return
}
if (!languageClickRef.current.contains(event.target as Node)) {
setHiddenMenu(true)
}
}
2022-05-03 10:05:11 +02:00
window.document.addEventListener('click', handleClickEvent)
return () => {
2022-05-03 10:05:11 +02:00
return window.removeEventListener('click', handleClickEvent)
}
2022-05-03 10:05:11 +02:00
}, [])
const handleLanguage = async (language: string): Promise<void> => {
await setLanguage(language)
}
return (
2021-12-04 15:52:51 +01:00
<div className='flex cursor-pointer flex-col items-center justify-center'>
2021-08-13 15:48:29 +02:00
<div
2022-05-03 10:05:11 +02:00
ref={languageClickRef}
2021-08-13 15:48:29 +02:00
data-cy='language-click'
2021-12-04 15:52:51 +01:00
className='mr-5 flex items-center'
2021-08-13 15:48:29 +02:00
onClick={handleHiddenMenu}
>
<LanguageFlag language={currentLanguage} />
<Arrow />
</div>
2021-08-23 19:41:39 +02:00
<ul
data-cy='languages-list'
className={classNames(
2022-02-22 21:19:42 +01:00
'absolute top-14 z-10 mt-3 mr-4 flex w-24 list-none flex-col items-center justify-center rounded-lg bg-white p-0 shadow-lightFlag dark:bg-black dark:shadow-darkFlag',
2021-08-23 19:41:39 +02:00
{ hidden: hiddenMenu }
)}
>
{i18n.locales.map((language, index) => {
if (language === currentLanguage) {
return null
}
return (
<li
key={index}
2021-12-04 15:52:51 +01:00
className='flex h-12 w-full items-center justify-center pl-2 hover:bg-[#4f545c] hover:bg-opacity-20'
2022-09-04 20:40:58 +02:00
onClick={async () => {
return await handleLanguage(language)
}}
2021-08-23 19:41:39 +02:00
>
<LanguageFlag language={language} />
</li>
)
})}
</ul>
</div>
)
}