Files
DecomEval/web/src/shared/theme.ts
T

37 lines
1.2 KiB
TypeScript

import { computed, ref } from "vue";
export type ThemeChoice = "system" | "dark" | "light";
const STORAGE_KEY = "decomeval.theme";
const LEGACY_KEY = "decom-theme";
const media = window.matchMedia("(prefers-color-scheme: dark)");
const legacy = localStorage.getItem(LEGACY_KEY);
if (legacy !== null) {
if (localStorage.getItem(STORAGE_KEY) === null) localStorage.setItem(STORAGE_KEY, legacy);
localStorage.removeItem(LEGACY_KEY);
}
const stored = localStorage.getItem(STORAGE_KEY);
export const themeChoice = ref<ThemeChoice>(stored === "dark" || stored === "light" || stored === "system" ? stored : "system");
const systemDark = ref(media.matches);
media.addEventListener("change", () => {
systemDark.value = media.matches;
});
export const isDark = computed(() => {
if (themeChoice.value === "dark") return true;
if (themeChoice.value === "light") return false;
return systemDark.value;
});
export function setThemeChoice(choice: ThemeChoice) {
themeChoice.value = choice;
localStorage.setItem(STORAGE_KEY, choice);
}
export function cycleTheme() {
const order: ThemeChoice[] = ["system", "dark", "light"];
const index = order.indexOf(themeChoice.value);
setThemeChoice(order[(index + 1) % order.length]);
}