From a087494f6809a7a8ea8e6c27a105d8c8f0f3839e Mon Sep 17 00:00:00 2001
From: Tom van der Lee <tom@vanderlee.io>
Date: Wed, 4 Sep 2024 10:27:24 +0200
Subject: Updated the libraries

---
 src/contexts/Settings.tsx | 65 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 65 insertions(+)
 create mode 100644 src/contexts/Settings.tsx

(limited to 'src/contexts/Settings.tsx')

diff --git a/src/contexts/Settings.tsx b/src/contexts/Settings.tsx
new file mode 100644
index 0000000..2bbebcc
--- /dev/null
+++ b/src/contexts/Settings.tsx
@@ -0,0 +1,65 @@
+import * as React from "react";
+import {
+  Context,
+  createContext,
+  PropsWithChildren,
+  useCallback,
+  useEffect,
+  useState,
+} from "react";
+import { Settings } from "~/types";
+
+interface SettingsApi {
+  darkMode: boolean;
+  setSetting: (key: keyof Settings, value: any) => void;
+}
+
+export const SettingsContext = createContext<Partial<SettingsApi>>(
+  {}
+) as Context<SettingsApi>;
+
+export default function SettingsProvider({ children }: PropsWithChildren<any>) {
+  // const themeConfig = useMemo(() => new ThemeConfig(), []);
+  const [settings, setSettings] = useState<Settings>(() => {
+    const stored = localStorage.getItem("settings");
+
+    if (stored) {
+      return JSON.parse(stored);
+    }
+
+    return {
+      darkMode:
+        window.matchMedia &&
+        window.matchMedia("(prefers-color-scheme: dark)").matches,
+    };
+  });
+
+  const setSetting = useCallback(
+    (key: keyof Settings, value: any) => {
+      const newSetting = {
+        ...settings,
+        [key]: value,
+      };
+      setSettings(newSetting);
+      localStorage.setItem("settings", JSON.stringify(newSetting));
+    },
+    [settings]
+  );
+
+  useEffect(() => {
+    document
+      .querySelector("html")
+      ?.setAttribute("data-bs-theme", settings.darkMode ? "dark" : "light");
+  }, [settings.darkMode]);
+
+  return (
+    <SettingsContext.Provider
+      value={{
+        darkMode: settings.darkMode,
+        setSetting,
+      }}
+    >
+      {children}
+    </SettingsContext.Provider>
+  );
+}
-- 
cgit v1.2.3

