Skip to content

Instantly share code, notes, and snippets.

@nfarina
Created May 14, 2019 19:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfarina/fb708f66858d2d3317877ab8adf8d926 to your computer and use it in GitHub Desktop.
Save nfarina/fb708f66858d2d3317877ab8adf8d926 to your computer and use it in GitHub Desktop.
Auto Dark Theme for Storybook
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);
});
@jesse23
Copy link

jesse23 commented Mar 12, 2021

Thanks for the code snippet! Just minor update event handler works fine for me.

const getColorScheme = matches => {
  return matches ? 'dark' : 'light';
};

const queryWindowMatchMedia = () => {
  return window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
};

// Automatically switch light/dark theme based on system pref.
addons.register('auto-theme-switcher', api => {
  let currTheme = initTheme;

  queryWindowMatchMedia().addEventListener('change', e => {
    const updatedTheme = getColorScheme(e.matches);
    if (currTheme !== updatedTheme) {
      currTheme = updatedTheme;
      api.setOptions({ theme: THEME[updatedTheme] });
      addons.getChannel().emit(FORCE_RE_RENDER);

      // Because of issue below, we can do iframe reload for now.
      // https://github.com/storybookjs/storybook/issues/10523
      const addonDocElem = document.getElementById('storybook-preview-iframe');
      addonDocElem.src = addonDocElem.src;
    }
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment