main-site/components/themeselector.tsx

75 lines
2.3 KiB
TypeScript

import { useUpdateTheme } from "../pages/_app";
import { useContext, useState } from 'react';
import { ThemeContext, DefaultTheme } from "styled-components";
import { darkTheme, lightTheme } from './themes';
import { ThemeDropDown, ThemeDropDownButton, ThemeDropDownOption, ThemeDropDownOptions } from "./styles/themedropdown";
import Themes from '../public/data/themes.json';
export const StyleSelector = () => {
const themes = Themes.themes;
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)
}
}
const [visible, setVisible] = useState(false);
function handleBlur(event:any) {
if (!event.currentTarget.contains(event.relatedTarget)) {
setVisible(false);
}
}
return (
<ThemeDropDown onBlur={(event) => handleBlur(event)}>
<ThemeDropDownButton show={+visible} onClick={() => setVisible(visible => !visible)}>{selectedTheme.themeName}</ThemeDropDownButton>
<ThemeDropDownOptions id="themesDropdown" show={+visible}>
{themes.map((theme) => (
<ThemeDropDownOption active={theme.themeId === selectedTheme.themeId ? 1 : 0} key={theme.themeId} onClick={() => updateThemeWithStorage(theme)}>
{theme.themeName}
</ThemeDropDownOption>
))}
</ThemeDropDownOptions>
</ThemeDropDown>
);
}
export const StyleSelectorPlaceholder = () => {
return (
<ThemeDropDown></ThemeDropDown>
)
}
export function getTheme(themeId: number, themes: DefaultTheme[]): DefaultTheme {
let retTheme: DefaultTheme = darkTheme;
themes.forEach((theme) => {
if (theme.themeId === themeId) { retTheme = theme};
})
return retTheme;
}
export default StyleSelector;