File size: 1,459 Bytes
5470817
 
 
60de3d1
 
 
 
 
 
 
 
 
 
5470817
60de3d1
5470817
60de3d1
 
 
 
 
5470817
60de3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5470817
 
 
 
60de3d1
 
 
 
 
5470817
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useState, useEffect } from "react";

export const useThemeMode = () => {
  // Function to detect system preference for dark mode
  const getSystemPreference = () => {
    return window.matchMedia &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
      ? "dark"
      : "light";
  };

  // Initialize state with system preference
  const [mode, setMode] = useState(getSystemPreference());

  // Listen for changes in system preference
  useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

    const handleChange = (e) => {
      setMode(e.matches ? "dark" : "light");
    };

    // Add event listener
    if (mediaQuery.addEventListener) {
      mediaQuery.addEventListener("change", handleChange);
    } else {
      // For older browsers
      mediaQuery.addListener(handleChange);
    }

    // Cleanup
    return () => {
      if (mediaQuery.removeEventListener) {
        mediaQuery.removeEventListener("change", handleChange);
      } else {
        // For older browsers
        mediaQuery.removeListener(handleChange);
      }
    };
  }, []);

  // Toggle function is kept for compatibility with existing code
  // but it will only temporarily change the theme until the next system preference change
  const toggleTheme = () => {
    setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
  };

  return {
    mode,
    toggleTheme,
    isSystemPreference: true,
  };
};