(defaultTheme: Theme = null)
| 8 | export type Theme = 'light' | 'dark' | null; |
| 9 | |
| 10 | export function useTheme(defaultTheme: Theme = null) { |
| 11 | const storageContext = useStorageContext(); |
| 12 | |
| 13 | const [theme, setThemeInternal] = useState<Theme>(() => { |
| 14 | if (!storageContext) { |
| 15 | return null; |
| 16 | } |
| 17 | |
| 18 | const stored = storageContext.get(STORAGE_KEY); |
| 19 | switch (stored) { |
| 20 | case 'light': |
| 21 | return 'light'; |
| 22 | case 'dark': |
| 23 | return 'dark'; |
| 24 | default: |
| 25 | if (typeof stored === 'string') { |
| 26 | // Remove the invalid stored value |
| 27 | storageContext.set(STORAGE_KEY, ''); |
| 28 | } |
| 29 | return defaultTheme; |
| 30 | } |
| 31 | }); |
| 32 | |
| 33 | useLayoutEffect(() => { |
| 34 | if (typeof window === 'undefined') { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | document.body.classList.remove('graphiql-light', 'graphiql-dark'); |
| 39 | if (theme) { |
| 40 | document.body.classList.add(`graphiql-${theme}`); |
| 41 | } |
| 42 | }, [theme]); |
| 43 | |
| 44 | const setTheme = (newTheme: Theme) => { |
| 45 | storageContext?.set(STORAGE_KEY, newTheme || ''); |
| 46 | setThemeInternal(newTheme); |
| 47 | }; |
| 48 | |
| 49 | return { theme, setTheme }; |
| 50 | } |
| 51 | |
| 52 | const STORAGE_KEY = 'theme'; |
no test coverage detected