Skip to content

Commit

Permalink
fix: support dark mode for safari < 14 using matchMedia().addListener (
Browse files Browse the repository at this point in the history
…#495)

* fix: support matchMedia for safari

* fix: edit comment
  • Loading branch information
yunsteel authored Oct 30, 2024
1 parent 5d3a179 commit 6fca6ab
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -578,14 +578,31 @@ const Toaster = forwardRef<HTMLElement, ToasterProps>(function Toaster(props, re
}

if (typeof window === 'undefined') return;

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({ matches }) => {
if (matches) {
setActualTheme('dark');
} else {
setActualTheme('light');
}
});
const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

try {
// Chrome & Firefox
darkMediaQuery.addEventListener('change', ({ matches }) => {
if (matches) {
setActualTheme('dark');
} else {
setActualTheme('light');
}
});
} catch (error) {
// Safari < 14
darkMediaQuery.addListener( ({ matches }) => {
try {
if (matches) {
setActualTheme('dark');
} else {
setActualTheme('light');
}
} catch(e) {
console.error(e)
}
});
}
}, [theme]);

React.useEffect(() => {
Expand Down

0 comments on commit 6fca6ab

Please sign in to comment.