main-site/components/themeselector.tsx
2022-12-15 23:41:48 +01:00

92 lines
2.3 KiB
TypeScript

import { useUpdateTheme } from "../pages/_app";
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);
const [selectedTheme, setSelectedTheme] = useState(themes[currentTheme.themeId]);
if(currentTheme !== selectedTheme) {
setSelectedTheme(currentTheme);
}
const updateThemeWithStorage = (newTheme: DefaultTheme) => {
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 {
}
}
const [test, setTest] = useState(false);
return (
<ThemeDropDown>
<ThemeDropDownButton onClick={() => setTest(test => !test)}>{selectedTheme.themeName}</ThemeDropDownButton>
<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>
)
}
export function getTheme(themeId: number): DefaultTheme {
let theme: DefaultTheme;
switch (themeId) {
case 0:
theme = lightTheme;
break;
case 1:
theme = darkTheme;
break;
case 2:
theme = amoledTheme;
break;
case 3:
theme = amoled2Theme;
break;
default:
theme = darkTheme
}
return theme;
}
export default StyleSelector;