bigbuffet-rw/app/soapbox/hooks/useSystemTheme.ts

34 lines
818 B
TypeScript
Raw Normal View History

2022-05-11 17:19:08 -07:00
import { useState, useEffect } from 'react';
type SystemTheme = 'light' | 'dark';
/** Get the system color scheme of the system. */
export const useSystemTheme = (): SystemTheme => {
const query = window.matchMedia('(prefers-color-scheme: dark)');
const [dark, setDark] = useState(query.matches);
const handleChange = (event: MediaQueryListEvent) => {
setDark(event.matches);
};
// Older versions of Safari on iOS don't support these events,
// so try-catch and do nothing.
2022-05-11 17:19:08 -07:00
useEffect(() => {
try {
query.addEventListener('change', handleChange);
} catch (e) {
// do nothing
}
2022-05-11 17:19:08 -07:00
return () => {
try {
query.removeEventListener('change', handleChange);
} catch (e) {
// do nothing
}
};
2022-05-11 17:19:08 -07:00
}, []);
return dark ? 'dark' : 'light';
};