main-site/components/themeselector.tsx

99 lines
2.5 KiB
TypeScript
Raw Normal View History

import { useUpdateTheme } from "../pages/_app";
2022-12-15 20:23:54 +00:00
import { Fragment, useContext, useState } from 'react';
import { ThemeContext, DefaultTheme } from "styled-components";
import { darkTheme, amoledTheme, lightTheme, amoled2Theme } from './themes';
import { ThemeDropDown, ThemeDropDownButton, ThemeDropDownOption, ThemeDropDownOptions } from "./styles/themedropdown";
const themes = [
lightTheme,
darkTheme,
amoledTheme,
amoled2Theme,
]
export const StyleSelector = () => {
const updateTheme = useUpdateTheme();
const currentTheme = useContext(ThemeContext);
2022-12-15 20:23:54 +00:00
const [selectedTheme, setSelectedTheme] = useState(themes[currentTheme.themeId]);
2022-12-15 22:41:48 +00:00
if(currentTheme !== selectedTheme) {
setSelectedTheme(currentTheme);
}
2022-12-15 20:23:54 +00:00
const updateThemeWithStorage = (newTheme: DefaultTheme) => {
2022-12-15 20:23:54 +00:00
if (newTheme.themeId === lightTheme.themeId) {
updateLightTheme(newTheme);
}
else {
setSelectedTheme(newTheme);
localStorage.setItem("theme", newTheme.themeId.toString());
updateTheme(newTheme);
}
}
const updateLightTheme = (newTheme: DefaultTheme) => {
if (confirm("Really switch to Light Mode?")) {
setSelectedTheme(newTheme);
localStorage.setItem("theme", newTheme.themeId.toString());
updateTheme(newTheme)
}
else {
}
}
2022-12-15 20:23:54 +00:00
const [test, setTest] = useState(false);
2022-12-16 21:58:46 +00:00
function handleBlur(event:any) {
console.log(event)
if (!event.currentTarget.contains(event.relatedTarget)) {
setTest(false);
}
}
return (
2022-12-15 20:23:54 +00:00
2022-12-16 21:58:46 +00:00
<ThemeDropDown onBlur={(event) => handleBlur(event)}>
2022-12-17 00:56:41 +00:00
<ThemeDropDownButton show={test} onClick={() => setTest(test => !test)}>{selectedTheme.themeName}</ThemeDropDownButton>
2022-12-15 20:23:54 +00:00
<ThemeDropDownOptions id="themesDropdown" show={test}>
{themes.map((theme) => (
<ThemeDropDownOption active={theme === selectedTheme} key={theme.themeId} onClick={() => updateThemeWithStorage(theme)}>
{theme.themeName}
</ThemeDropDownOption>
))}
</ThemeDropDownOptions>
</ThemeDropDown>
);
}
export const StyleSelectorPlaceholder = () => {
return (
<ThemeDropDown></ThemeDropDown>
)
}
2022-12-15 20:23:54 +00:00
export function getTheme(themeId: number): DefaultTheme {
let theme: DefaultTheme;
2022-12-15 20:23:54 +00:00
switch (themeId) {
case 0:
theme = lightTheme;
break;
2022-12-15 20:23:54 +00:00
case 1:
theme = darkTheme;
break;
2022-12-15 20:23:54 +00:00
case 2:
theme = amoledTheme;
break;
2022-12-15 20:23:54 +00:00
case 3:
theme = amoled2Theme;
break;
default:
theme = darkTheme
}
return theme;
}
export default StyleSelector;