@wise/components-theming
Version:
Provides theming support for the Wise Design system components
54 lines (44 loc) • 1.5 kB
text/typescript
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<Theming['theme']>;
screenMode: ScreenMode;
isModern: boolean;
isForestGreenTheme: boolean;
isScreenModeDark: boolean;
className: string;
}
const FALLBACK_VALUES = {
theme: DEFAULT_BASE_THEME,
screenMode: DEFAULT_SCREEN_MODE,
} 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: contextScreenMode } = theming ?? FALLBACK_VALUES;
const screenMode = theme === DEFAULT_BASE_THEME ? DEFAULT_SCREEN_MODE : contextScreenMode;
return useMemo(
() => ({
theme,
screenMode,
isModern: isThemeModern(theme),
isForestGreenTheme: isForestGreenTheme(theme),
isScreenModeDark: isScreenModeDark(theme, screenMode),
className: getThemeClassName(theme, screenMode),
}),
[theme, screenMode],
);
};