matchMedia.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import {NODE_ENV} from 'sentry/constants';
  2. import ConfigStore from 'sentry/stores/configStore';
  3. function changeFavicon(theme: 'dark' | 'light'): void {
  4. // only on prod because we have a development favicon
  5. if (NODE_ENV !== 'production') {
  6. return;
  7. }
  8. const n = document.querySelector<HTMLLinkElement>('[rel="icon"][type="image/png"]');
  9. if (!n) {
  10. return;
  11. }
  12. const path = n.href.split('/sentry/')[0];
  13. n.href = `${path}/sentry/images/${theme === 'dark' ? 'favicon-dark' : 'favicon'}.png`;
  14. }
  15. function handleColorSchemeChange(e: MediaQueryListEvent): void {
  16. const isDark = e.media === '(prefers-color-scheme: dark)' && e.matches;
  17. const type = isDark ? 'dark' : 'light';
  18. changeFavicon(type);
  19. ConfigStore.updateTheme(type);
  20. }
  21. function prefersDark(): boolean {
  22. return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  23. }
  24. export function setupColorScheme(): void {
  25. // Set favicon to dark on load if necessary)
  26. if (prefersDark()) {
  27. changeFavicon('dark');
  28. ConfigStore.updateTheme('dark');
  29. }
  30. // If matchmedia is not supported, keep whatever configStore.init theme was set to
  31. if (!window.matchMedia) {
  32. return;
  33. }
  34. // Watch for changes in preferred color scheme
  35. const lightMediaQuery = window.matchMedia('(prefers-color-scheme: light)');
  36. const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  37. try {
  38. lightMediaQuery.addEventListener('change', handleColorSchemeChange);
  39. darkMediaQuery.addEventListener('change', handleColorSchemeChange);
  40. } catch (err) {
  41. // Safari 13 (maybe lower too) does not support `addEventListener`
  42. // `addListener` is deprecated
  43. lightMediaQuery.addListener(handleColorSchemeChange);
  44. darkMediaQuery.addListener(handleColorSchemeChange);
  45. }
  46. }