mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
66 lines
2.3 KiB
JavaScript
66 lines
2.3 KiB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
|
|
import { useEffect } from 'react';
|
|
import { z } from 'zod';
|
|
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
|
|
import { AppContext } from '@/contexts/AppContext.js';
|
|
// Zod schema for AppConfig validation
|
|
const AppConfigSchema = z.object({
|
|
theme: z.enum(['dark', 'light', 'system']),
|
|
relayUrl: z.string().url(),
|
|
});
|
|
export function AppProvider(props) {
|
|
const { children, storageKey, defaultConfig, presetRelays, } = props;
|
|
// App configuration state with localStorage persistence
|
|
const [config, setConfig] = useLocalStorage(storageKey, defaultConfig, {
|
|
serialize: JSON.stringify,
|
|
deserialize: (value) => {
|
|
const parsed = JSON.parse(value);
|
|
return AppConfigSchema.parse(parsed);
|
|
}
|
|
});
|
|
// Generic config updater with callback pattern
|
|
const updateConfig = (updater) => {
|
|
setConfig(updater);
|
|
};
|
|
const appContextValue = {
|
|
config,
|
|
updateConfig,
|
|
presetRelays,
|
|
};
|
|
// Apply theme effects to document
|
|
useApplyTheme(config.theme);
|
|
return (_jsx(AppContext.Provider, { value: appContextValue, children: children }));
|
|
}
|
|
/**
|
|
* Hook to apply theme changes to the document root
|
|
*/
|
|
function useApplyTheme(theme) {
|
|
useEffect(() => {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove('light', 'dark');
|
|
if (theme === 'system') {
|
|
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
|
|
.matches
|
|
? 'dark'
|
|
: 'light';
|
|
root.classList.add(systemTheme);
|
|
return;
|
|
}
|
|
root.classList.add(theme);
|
|
}, [theme]);
|
|
// Handle system theme changes when theme is set to "system"
|
|
useEffect(() => {
|
|
if (theme !== 'system')
|
|
return;
|
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
|
const handleChange = () => {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove('light', 'dark');
|
|
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
|
root.classList.add(systemTheme);
|
|
};
|
|
mediaQuery.addEventListener('change', handleChange);
|
|
return () => mediaQuery.removeEventListener('change', handleChange);
|
|
}, [theme]);
|
|
}
|