chenzhaoyang
2025-12-17 d3e5a4b7658ece4f845bbc0c4f95acf3fbdf8a61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { global } from "@storybook/global";
import { atomWithStorage } from "jotai/utils";
import { atom } from "jotai/vanilla";
import { PARAM_KEY } from "./constants";
 
export const themeAtom = atomWithStorage(PARAM_KEY, "auto");
export const evaluatedThemeAtom = atom((get) => {
  let theme = get(themeAtom);
 
  if (theme === "auto") {
    theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  }
 
  global.document.documentElement.setAttribute("data-color-scheme", theme);
 
  return theme;
});
 
(evaluatedThemeAtom as any).onMount = (get: any, set: (a: any, v: any) => void) => {
  const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
  const callback = (event: MediaQueryListEvent) => {
    const theme = get(themeAtom);
    const evaluatedTheme = theme === "auto" ? (event.matches ? "dark" : "light") : theme;
    if (theme === "auto") {
      set(evaluatedThemeAtom, evaluatedTheme);
    }
    global.document.documentElement.setAttribute("data-color-scheme", evaluatedTheme);
  };
  mediaQueryList.addEventListener("change", callback);
  return () => {
    mediaQueryList.removeEventListener("change", callback);
  };
};