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

Option to specify class on preview's html #133

Closed dricholm closed 3 years ago

dricholm commented 3 years ago

Hello, Thanks for this plugin, it works great!

There is one extra feature I'd like to have: add a dark class to the preview's element. Seems like this was requested in #101 and implemented in #102, but the implementation adds the class to the element in the preview iframe. The reason I want it for is so body can also apply dark styles to itself if a parent element has .dark. In my case I use it with Tailwind CSS, where the dark mode will be applied if a parent element has the class .dark applied. See docs for more information about this.

Here are two pictures to better demonstrate this. This is the current state, when the class is applied to the body: image I added class="dark" in the developer tools to the preview element: image As you can see, on the top it will only apply the dark theme to the component, while on the bottom it will also be applied to the body.

I tried it out by changing the line about body to select the html instead and it worked locally. What do you think about this? Could this be added? If yes, I can help with a PR if it's okay. In that case what should be the default: adding it to HTML or body. Or add a new option to specify this or other possibilities?

lharress commented 3 years ago

Had this problem as well, may not be the best solution, but I just used a global decorator;

(Story) => {
    const isDarkMode = useDarkMode();

    useEffect(() => {
        if (!isDarkMode) {
            return;
        }

        document.documentElement.classList.add("dark");

        return () => {
            document.documentElement.classList.remove("dark");
        };
    }, [isDarkMode]);

    return <Story />;
},
hipstersmoothie commented 3 years ago

I'd be open to merging a PR for this. The option could be name classTarget and default to body.

hipstersmoothie commented 3 years ago

:rocket: Issue was released in v1.0.7 :rocket: