umami/components/settings/LanguageButton.js

71 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-09-07 10:22:16 +02:00
import React, { useState, useRef } from 'react';
2020-09-20 12:28:05 +02:00
import classNames from 'classnames';
import Head from 'next/head';
2020-09-20 10:33:39 +02:00
import Menu from 'components/common/Menu';
import Button from 'components/common/Button';
2020-09-08 04:48:40 +02:00
import { menuOptions } from 'lib/lang';
import useLocale from 'hooks/useLocale';
import useDocumentClick from 'hooks/useDocumentClick';
import Globe from 'assets/globe.svg';
2020-09-08 04:48:40 +02:00
import styles from './LanguageButton.module.css';
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
setShowMenu(false);
}
function toggleMenu() {
setShowMenu(state => !state);
}
2020-09-07 10:22:16 +02:00
useDocumentClick(e => {
if (!ref.current.contains(e.target)) {
setShowMenu(false);
}
});
return (
<>
<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' && (
<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}>
2020-09-20 12:28:05 +02:00
<Button
icon={<Globe />}
className={classNames({ [styles.open]: showMenu })}
onClick={toggleMenu}
variant="light"
>
<div className={styles.text}>{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
);
}