tonai / storybook-addon-themes

MIT License
83 stars 30 forks source link

onChange not called on initial load with storybook V7 #73

Open Hecatron opened 2 years ago

Hecatron commented 2 years ago

Hi, So I've recently trying out this addon in combination with storybook / tailwindcss. Also using daisyui with it's list of themes - https://daisyui.com/docs/themes/ I've also been using the Version 7 Alpha of Storybook.

From what I can tell the onChange hook isn't being called when the page is initially loaded. Only when the theme is changed in the menu.

I was going to try the addParameters way of doing things. https://github.com/tonai/storybook-addon-themes/issues/67 But it looks as if it's been depreciated in V7 https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-addparameters-and-adddecorator

preview.js

function getDaisyUiThemes() {
  const duilist = [
    "light", "dark", "cupcake", "bumblebee", "emerald",
    "corporate", "synthwave", "retro", "cyberpunk", "valentine",
    "halloween", "garden", "forest", "aqua", "lofi",
    "pastel", "fantasy", "wireframe", "black", "luxury",
    "dracula", "cmyk", "autumn", "business", "acid",
    "lemonade", "night", "coffee", "winter"
  ];
  const themes = [];
  for (const theme of duilist) {
    themes.push({name: theme})
  }
  return themes;
};

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
  themes: {
    default: 'cupcake',
    list: getDaisyUiThemes(),
    onChange: (theme) => {
      const storybookIframe = document.getElementById("storybook-preview-iframe");
      const storybookIframeDocument = storybookIframe.contentDocument || storybookIframe.contentWindow.document;
      const storybookHtml = storybookIframeDocument.querySelector("html");
      if(theme) {
        console.log('THEME:', theme.name);
        storybookHtml.setAttribute("data-theme", theme.name);
      } else {
        console.log('THEME:', 'None');
        storybookHtml.removeAttribute("data-theme");
      }
    }
  },
}