2020-09-07 10:22:16 +02:00
|
|
|
import React, { useState, useRef } from 'react';
|
2020-09-11 22:21:17 +02:00
|
|
|
import Head from 'next/head';
|
2020-09-07 10:22:16 +02:00
|
|
|
import Globe from 'assets/globe.svg';
|
|
|
|
import useDocumentClick from 'hooks/useDocumentClick';
|
|
|
|
import Menu from './Menu';
|
|
|
|
import Button from './Button';
|
2020-09-08 04:48:40 +02:00
|
|
|
import { menuOptions } from 'lib/lang';
|
|
|
|
import styles from './LanguageButton.module.css';
|
2020-09-09 05:46:31 +02:00
|
|
|
import useLocale from '../../hooks/useLocale';
|
2020-09-07 10:22:16 +02:00
|
|
|
|
2020-09-08 00:25:09 +02:00
|
|
|
export default function LanguageButton({ menuPosition = 'bottom', menuAlign = 'left' }) {
|
2020-09-07 10:22:16 +02:00
|
|
|
const [showMenu, setShowMenu] = useState(false);
|
2020-09-09 05:46:31 +02:00
|
|
|
const [locale, setLocale] = useLocale();
|
2020-09-07 10:22:16 +02:00
|
|
|
const ref = useRef();
|
2020-09-08 04:48:40 +02:00
|
|
|
const selectedLocale = menuOptions.find(e => e.value === locale)?.display;
|
2020-09-07 10:22:16 +02:00
|
|
|
|
|
|
|
function handleSelect(value) {
|
2020-09-09 05:46:31 +02:00
|
|
|
setLocale(value);
|
2020-09-07 10:22:16 +02:00
|
|
|
window.localStorage.setItem('locale', value);
|
|
|
|
setShowMenu(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
useDocumentClick(e => {
|
|
|
|
if (!ref.current.contains(e.target)) {
|
|
|
|
setShowMenu(false);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return (
|
2020-09-11 22:21:17 +02:00
|
|
|
<>
|
|
|
|
<Head>
|
|
|
|
{locale === 'zh-CN' && (
|
|
|
|
<link
|
|
|
|
href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap"
|
|
|
|
rel="stylesheet"
|
|
|
|
/>
|
|
|
|
)}
|
2020-09-13 10:26:54 +02:00
|
|
|
{locale === 'ja-JP' && (
|
2020-09-11 22:21:17 +02:00
|
|
|
<link
|
|
|
|
href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;500;700&display=swap"
|
|
|
|
rel="stylesheet"
|
|
|
|
/>
|
|
|
|
)}
|
|
|
|
</Head>
|
|
|
|
<div ref={ref} className={styles.container}>
|
|
|
|
<Button icon={<Globe />} onClick={() => setShowMenu(true)} size="small">
|
|
|
|
<div className={locale}>{selectedLocale}</div>
|
|
|
|
</Button>
|
|
|
|
{showMenu && (
|
|
|
|
<Menu
|
|
|
|
className={styles.menu}
|
|
|
|
options={menuOptions}
|
|
|
|
onSelect={handleSelect}
|
|
|
|
float={menuPosition}
|
|
|
|
align={menuAlign}
|
|
|
|
/>
|
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
</>
|
2020-09-07 10:22:16 +02:00
|
|
|
);
|
|
|
|
}
|