hipstersmoothie / storybook-dark-mode

A storybook addon that lets your users toggle between dark and light mode.
MIT License
435 stars 56 forks source link

Dark mode class not applied in "open canvas in new tab" mode #173

Open quantizor opened 2 years ago

quantizor commented 2 years ago

Storybook 6.x, storybook-dark-mode 1.0.8

When using the config storyPreview: true the dark mode class is not applied to the canvas body tag when using the Storybook functionality to open the story in a new tab.

Screen Shot 2022-01-14 at 5 02 38 PM

Result:

Screen Shot 2022-01-14 at 5 02 44 PM
farmerpaul commented 1 year ago

Unfortunately, this bug seems to make the stylePreview: true setting incompatible with Chromatic's component views, which are also rendered in isolation. Chromatic relies heavily on isolated component renderings for its features.

farmerpaul commented 1 year ago

I came up with a workaround for anyone interested! Create .storybook/preview-head.html and populate it with this code:

<script>
  /* =================================================
  Manually apply dark/light mode class to target element if not already applied.
  Workaround for bug of storybook-dark-mode (stylePreview: true in isolated view).
  @see https://github.com/hipstersmoothie/storybook-dark-mode/issues/173
  =================================================== */
  window.addEventListener('DOMContentLoaded', () => {
    const getStore = () => {
      const storeJson = localStorage.getItem('sb-addon-themes-3');
      return storeJson ? JSON.parse(storeJson) : undefined;
    };

    const store = getStore();
    const target = document.querySelector(store.classTarget);

    // Check if required dark/light class has NOT been applied to the target.
    if (
      target &&
      !target.classList.contains(store.current === 'light' ? store.lightClass : store.darkClass)
    ) {
      // If absent, bug is occurring, so update classList and respond to local storage changes.
      const updateTheme = () => {
        const newStore = getStore();
        if (newStore) {
          target.classList.toggle(newStore.lightClass, newStore.current === 'light');
          target.classList.toggle(newStore.darkClass, newStore.current === 'dark');
        }
      };

      window.addEventListener('storage', updateTheme);
      updateTheme();
    }
  });
</script>