2024-04-08 16:46:24 +02:00
|
|
|
import { atom, useAtom } from "jotai";
|
|
|
|
import { useEffect, useLayoutEffect, useState } from "react";
|
|
|
|
import { THEME } from "../packages/excalidraw";
|
|
|
|
import { EVENT } from "../packages/excalidraw/constants";
|
2024-05-08 10:51:50 +02:00
|
|
|
import type { Theme } from "../packages/excalidraw/element/types";
|
2024-04-08 16:59:03 +02:00
|
|
|
import { CODES, KEYS } from "../packages/excalidraw/keys";
|
2024-04-08 16:46:24 +02:00
|
|
|
import { STORAGE_KEYS } from "./app_constants";
|
|
|
|
|
|
|
|
export const appThemeAtom = atom<Theme | "system">(
|
|
|
|
(localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_THEME) as
|
|
|
|
| Theme
|
|
|
|
| "system"
|
|
|
|
| null) || THEME.LIGHT,
|
|
|
|
);
|
|
|
|
|
|
|
|
const getDarkThemeMediaQuery = (): MediaQueryList | undefined =>
|
|
|
|
window.matchMedia?.("(prefers-color-scheme: dark)");
|
|
|
|
|
|
|
|
export const useHandleAppTheme = () => {
|
|
|
|
const [appTheme, setAppTheme] = useAtom(appThemeAtom);
|
|
|
|
const [editorTheme, setEditorTheme] = useState<Theme>(THEME.LIGHT);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const mediaQuery = getDarkThemeMediaQuery();
|
|
|
|
|
|
|
|
const handleChange = (e: MediaQueryListEvent) => {
|
|
|
|
setEditorTheme(e.matches ? THEME.DARK : THEME.LIGHT);
|
|
|
|
};
|
|
|
|
|
|
|
|
if (appTheme === "system") {
|
|
|
|
mediaQuery?.addEventListener("change", handleChange);
|
|
|
|
}
|
|
|
|
|
|
|
|
const handleKeydown = (event: KeyboardEvent) => {
|
|
|
|
if (
|
|
|
|
!event[KEYS.CTRL_OR_CMD] &&
|
|
|
|
event.altKey &&
|
|
|
|
event.shiftKey &&
|
2024-04-08 16:55:33 +02:00
|
|
|
event.code === CODES.D
|
2024-04-08 16:46:24 +02:00
|
|
|
) {
|
|
|
|
event.preventDefault();
|
|
|
|
event.stopImmediatePropagation();
|
|
|
|
setAppTheme(editorTheme === THEME.DARK ? THEME.LIGHT : THEME.DARK);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
document.addEventListener(EVENT.KEYDOWN, handleKeydown, { capture: true });
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
mediaQuery?.removeEventListener("change", handleChange);
|
|
|
|
document.removeEventListener(EVENT.KEYDOWN, handleKeydown, {
|
|
|
|
capture: true,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}, [appTheme, editorTheme, setAppTheme]);
|
|
|
|
|
|
|
|
useLayoutEffect(() => {
|
|
|
|
localStorage.setItem(STORAGE_KEYS.LOCAL_STORAGE_THEME, appTheme);
|
|
|
|
|
|
|
|
if (appTheme === "system") {
|
|
|
|
setEditorTheme(
|
|
|
|
getDarkThemeMediaQuery()?.matches ? THEME.DARK : THEME.LIGHT,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
setEditorTheme(appTheme);
|
|
|
|
}
|
|
|
|
}, [appTheme]);
|
|
|
|
|
|
|
|
return { editorTheme };
|
|
|
|
};
|