mirror of
https://github.com/getformwork/formwork.git
synced 2025-01-17 21:49:04 +01:00
Allow theme switch on prefers-color-scheme
change
This commit is contained in:
parent
9f275bcd89
commit
57539238a3
@ -1,30 +1,59 @@
|
||||
import { getCookies, setCookie } from "../utils/cookies";
|
||||
import { $ } from "../utils/selectors";
|
||||
import { app } from "../app";
|
||||
|
||||
type ColorSchemeName = "light" | "dark";
|
||||
type ColorSchemePreference = ColorSchemeName | "light dark";
|
||||
|
||||
export class ColorScheme {
|
||||
constructor() {
|
||||
const setPreferredColorScheme = () => {
|
||||
const getSupportedColorSchemes = (): ColorSchemePreference => {
|
||||
const meta = $("meta[name=color-scheme]") as HTMLMetaElement;
|
||||
if (!meta) {
|
||||
return "light dark";
|
||||
}
|
||||
switch (meta.content) {
|
||||
case "light":
|
||||
return "light";
|
||||
case "dark":
|
||||
return "dark";
|
||||
default:
|
||||
return "light dark";
|
||||
}
|
||||
};
|
||||
|
||||
const setColorScheme = (colorScheme: ColorSchemeName) => {
|
||||
document.documentElement.classList.remove("color-scheme-light", "color-scheme-dark");
|
||||
document.documentElement.classList.add(`color-scheme-${colorScheme}`);
|
||||
};
|
||||
|
||||
const setPreferredColorScheme = (event: Event) => {
|
||||
const cookies = getCookies();
|
||||
const cookieName = "formwork_preferred_color_scheme";
|
||||
const oldValue = cookieName in cookies ? cookies[cookieName] : null;
|
||||
let value: "light" | "dark" = "light";
|
||||
let colorScheme: ColorSchemeName = "light";
|
||||
|
||||
if (window.matchMedia("(prefers-color-scheme: light)").matches) {
|
||||
value = "light";
|
||||
colorScheme = "light";
|
||||
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||||
value = "dark";
|
||||
colorScheme = "dark";
|
||||
}
|
||||
|
||||
if (value && value !== oldValue) {
|
||||
setCookie(cookieName, value, {
|
||||
if (colorScheme && colorScheme !== oldValue) {
|
||||
setCookie(cookieName, colorScheme, {
|
||||
"max-age": 2592000, // 1 month
|
||||
path: app.config.baseUri,
|
||||
samesite: "strict",
|
||||
});
|
||||
|
||||
if (event.type === "change" && getSupportedColorSchemes() === "light dark") {
|
||||
setColorScheme(colorScheme);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("beforeunload", setPreferredColorScheme);
|
||||
window.addEventListener("pagehide", setPreferredColorScheme);
|
||||
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", setPreferredColorScheme);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user