Created
May 14, 2019 19:04
-
-
Save nfarina/fb708f66858d2d3317877ab8adf8d926 to your computer and use it in GitHub Desktop.
Auto Dark Theme for Storybook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import addons from '@storybook/addons'; | |
import { FORCE_RE_RENDER } from '@storybook/core-events'; | |
import { themes } from '@storybook/theming'; | |
// Automatically switch light/dark theme based on system pref. | |
addons.register("auto-theme-switcher", api => { | |
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)'); | |
let lastTheme; | |
// Check every second. This keeps everything in sync and works reliably | |
// on Chrome which doesn't seem to support change events on this media query. | |
setInterval(() => { | |
const desiredTheme = prefersDark.matches ? "dark" : "normal"; | |
if (lastTheme !== desiredTheme) { | |
lastTheme = desiredTheme; | |
api.setOptions({theme: themes[desiredTheme]}); | |
addons.getChannel().emit(FORCE_RE_RENDER); | |
} | |
}, 1000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code snippet! Just minor update event handler works fine for me.