mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
Consolidate ThemeProvider and AppProvider
This commit is contained in:
7 files changed
+199
-145
No files matched your search
@@ -0,0 +1,54 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Generic hook for managing localStorage state
|
||||
*/
|
||||
export function useLocalStorage<T>(
|
||||
key: string,
|
||||
defaultValue: T,
|
||||
serializer?: {
|
||||
serialize: (value: T) => string;
|
||||
deserialize: (value: string) => T;
|
||||
}
|
||||
) {
|
||||
const serialize = serializer?.serialize || JSON.stringify;
|
||||
const deserialize = serializer?.deserialize || JSON.parse;
|
||||
|
||||
const [state, setState] = useState<T>(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? deserialize(item) : defaultValue;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to load ${key} from localStorage:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(state) : value;
|
||||
setState(valueToStore);
|
||||
localStorage.setItem(key, serialize(valueToStore));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to save ${key} to localStorage:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Sync with localStorage changes from other tabs
|
||||
useEffect(() => {
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue !== null) {
|
||||
try {
|
||||
setState(deserialize(e.newValue));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to sync ${key} from localStorage:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [key, deserialize]);
|
||||
|
||||
return [state, setValue] as const;
|
||||
}
|
||||
+3
-10
@@ -1,13 +1,6 @@
|
||||
import { useContext } from "react"
|
||||
import { ThemeContext, type ThemeContextType } from "@/lib/ThemeContext"
|
||||
import { useTheme as useThemeFromProvider } from "@/components/AppProvider";
|
||||
|
||||
/** Hook to get and set the active theme. */
|
||||
export function useTheme(): ThemeContextType {
|
||||
const context = useContext(ThemeContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
export function useTheme() {
|
||||
return useThemeFromProvider();
|
||||
}
|
||||
Reference in new issue
Block a user