hipstersmoothie / storybook-dark-mode

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

Possibility to link to a story with dark theme set #242

Open Meemaw opened 11 months ago

Meemaw commented 11 months ago

Is it possible to somehow link to a story that would have dark mode predefined? e.g via some kind of query parameter.

d9k commented 7 months ago

Excerpt from my notes:

I think, yes,

1. you can add global control to .storybook/preview.ts: globalTypes which adds URL parameter when you click the switch (all custom global controls changes URL params).

See :balloon: demo with such control having &globals=theme:dark in URL

2. Then you can write custom global storybook decorator to .storybook/preview.ts: decorators with useEffect which will emit storybook-dark-mode action to sync dark state with your custom storybook global control value (see README):

import { useDarkMode } from 'storybook-dark-mode';

// . . .
decorators: [
  (Story, context) => {
   // if we added "theme" global variable earlier
   const theme = context.globals.theme;
   const darkMode = useDarkMode();

    useEffect(() => {
      const darkModeFromTheme = theme === 'dark';
      if (darkModeFromTheme != darkMode) {
        channel.emit(UPDATE_DARK_MODE_EVENT_NAME);
      }
    }, [theme]);

    return <Story />;
  },

  // ...rest decorators
]

(didn't test the snippet, just an idea. If you will succeed please share working code :slightly_smiling_face:)