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

Set initial mode based on users prefered color scheme #165

Open h0t-p1xels opened 2 years ago

h0t-p1xels commented 2 years ago

I noticed that the initial mode (light or dark) is hard set using current:.

This means that if a user has their prefered color scheme set to dark but it is set to light using current: Storybook will still render in light mode before being changed by the user.

My solution to detect the users prefered color scheme is:

// .storybook/preview.js

import { themes } from "@storybook/theming"

// Detect if users preferred color scheme is dark
const isDark =
    typeof window !== `undefined`
        ? window.matchMedia &&
          window.matchMedia("(prefers-color-scheme: dark)").matches
        : null

export const parameters = {
    darkMode: {
        // Set initial theme based on users preferred color scheme
        current: isDark ? "dark" : "light",

I wanted to share this solution incase it helps anyone else out.

But also wanted to check if anyone has any better solution they could share? or if this could somehow be added to the addon?

hipstersmoothie commented 1 year ago

@nikkipantony Would you be willing to submit a PR? In my mind if the user changes it back to system settings from then on it should match system settings

beltranrengifo commented 9 months ago

I addressed a related matter in this fix. I opted not to utilize the OS color schema over current prop because I believe it's important for us to maintain a bit of control over the color scheme of our Storybook, rather than totally relying on the user's preferences. This decision ensures that we can serve the Storybook with the specific schema we desire