From 6ea11324c988e58a54de7a6d6ed329ee5b84a357 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Fri, 23 Jun 2023 19:15:06 -0700 Subject: [PATCH] Extract language switch component --- components/LanguageSwitch/index.module.scss | 56 +++++++++++++++++++++ components/LanguageSwitch/index.tsx | 51 +++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 components/LanguageSwitch/index.module.scss create mode 100644 components/LanguageSwitch/index.tsx diff --git a/components/LanguageSwitch/index.module.scss b/components/LanguageSwitch/index.module.scss new file mode 100644 index 00000000..1d8b83f0 --- /dev/null +++ b/components/LanguageSwitch/index.module.scss @@ -0,0 +1,56 @@ +.languageSwitch { + $height: 24px; + + background: $grey-60; + border-radius: calc($height / 2); + border: none; + position: relative; + width: 44px; + height: $height; + + &:hover { + cursor: pointer; + } + + .thumb { + $diameter: 18px; + + background: $grey-100; + border-radius: calc($diameter / 2); + display: block; + height: $diameter; + width: $diameter; + position: absolute; + top: 3px; + left: 3px; + z-index: 3; + + &:hover { + cursor: pointer; + } + + &[data-state='checked'] { + background: $grey-100; + left: 23px; + } + } + + .left, + .right { + color: $grey-100; + font-size: 10px; + font-weight: $bold; + position: absolute; + z-index: 2; + } + + .left { + top: 6px; + left: 6px; + } + + .right { + top: 6px; + right: 5px; + } +} diff --git a/components/LanguageSwitch/index.tsx b/components/LanguageSwitch/index.tsx new file mode 100644 index 00000000..c14fc907 --- /dev/null +++ b/components/LanguageSwitch/index.tsx @@ -0,0 +1,51 @@ +import React, { PropsWithChildren, useEffect, useState } from 'react' +import { useRouter } from 'next/router' +import { setCookie } from 'cookies-next' +import { retrieveLocaleCookies } from '~utils/retrieveCookies' +import * as SwitchPrimitive from '@radix-ui/react-switch' +import styles from './index.module.scss' + +interface Props extends SwitchPrimitive.SwitchProps {} + +export const LanguageSwitch = React.forwardRef( + function languageSwitch( + { children }: PropsWithChildren, + forwardedRef + ) { + // Router and locale data + const router = useRouter() + const localeData = retrieveLocaleCookies() + + // State + const [languageChecked, setLanguageChecked] = useState(false) + + // Hooks + useEffect(() => { + setLanguageChecked(localeData === 'ja' ? true : false) + }, [localeData]) + + function changeLanguage(value: boolean) { + const language = value ? 'ja' : 'en' + const expiresAt = new Date() + expiresAt.setDate(expiresAt.getDate() + 120) + + setCookie('NEXT_LOCALE', language, { path: '/', expires: expiresAt }) + router.push(router.asPath, undefined, { locale: language }) + } + + return ( + + + JP + EN + + ) + } +) + +export default LanguageSwitch