import { useContext, useMemo } from 'react'; import { ThemeContext } from './ThemeProviderContext'; import type { ScreenMode, Theming } from './const'; import { DEFAULT_BASE_THEME, DEFAULT_SCREEN_MODE } from './const'; import { isThemeModern, isForestGreenTheme, isScreenModeDark, getThemeClassName } from './helpers'; interface ThemeHookValue { theme: NonNullable; screenMode: ScreenMode; /** * @deprecated there is no more such thing as "modern" theme */ isModern: boolean; isForestGreenTheme: boolean; isScreenModeDark: boolean; className: string; setTheme: (theme: NonNullable) => void; setScreenMode: (screenMode: ScreenMode) => void; } const FALLBACK_VALUES = { theme: DEFAULT_BASE_THEME, screenMode: DEFAULT_SCREEN_MODE, setTheme: () => {}, setScreenMode: () => {}, } as const; const isNotProduction = () => { try { return ['localhost', 'dev-wi.se'].includes(window.location.hostname); } catch { return false; } }; export const useTheme = (): ThemeHookValue => { const theming = useContext(ThemeContext); if (!theming && isNotProduction()) { // eslint-disable-next-line no-console console.warn('Call to useTheme outside a ThemeProvider'); } const { theme, screenMode, setTheme, setScreenMode } = theming ?? FALLBACK_VALUES; return useMemo( () => ({ theme, screenMode, /** * @deprecated there is no more such thing as "modern" theme */ isModern: isThemeModern(theme), isForestGreenTheme: isForestGreenTheme(theme), isScreenModeDark: isScreenModeDark(theme, screenMode), className: getThemeClassName(theme, screenMode), setTheme, setScreenMode, }), [theme, screenMode, setTheme, setScreenMode], ); };