@vueless/storybook-dark-mode 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Tool.tsx ADDED
@@ -0,0 +1,266 @@
1
+ import * as React from 'react';
2
+ import { global } from '@storybook/global';
3
+ import { themes, ThemeVars } from 'storybook/theming';
4
+ import { IconButton } from 'storybook/internal/components';
5
+ import { MoonIcon, SunIcon } from '@storybook/icons';
6
+ import {
7
+ STORY_CHANGED,
8
+ SET_STORIES,
9
+ DOCS_RENDERED,
10
+ } from 'storybook/internal/core-events';
11
+ import { API, useParameter } from 'storybook/manager-api';
12
+ import equal from 'fast-deep-equal';
13
+ import { DARK_MODE_EVENT_NAME, UPDATE_DARK_MODE_EVENT_NAME } from './constants';
14
+
15
+ const { document, window } = global as { document: Document; window: Window };
16
+ const modes = ['light', 'dark'] as const;
17
+ type Mode = typeof modes[number];
18
+
19
+ interface DarkModeStore {
20
+ /** The class target in the preview iframe */
21
+ classTarget: string;
22
+ /** The current mode the storybook is set to */
23
+ current: Mode;
24
+ /** The dark theme for storybook */
25
+ dark: ThemeVars;
26
+ /** The dark class name for the preview iframe */
27
+ darkClass: string | string[];
28
+ /** The light theme for storybook */
29
+ light: ThemeVars;
30
+ /** The light class name for the preview iframe */
31
+ lightClass: string | string[];
32
+ /** Apply mode to iframe */
33
+ stylePreview: boolean;
34
+ /** Persist if the user has set the theme */
35
+ userHasExplicitlySetTheTheme: boolean;
36
+ }
37
+
38
+ const STORAGE_KEY = 'sb-addon-themes-3';
39
+ export const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)');
40
+
41
+ const defaultParams: Required<Omit<DarkModeStore, 'current'>> = {
42
+ classTarget: 'body',
43
+ dark: themes.dark,
44
+ darkClass: ['dark'],
45
+ light: themes.light,
46
+ lightClass: ['light'],
47
+ stylePreview: false,
48
+ userHasExplicitlySetTheTheme: false,
49
+ };
50
+
51
+ /** Persist the dark mode settings in localStorage */
52
+ export const updateStore = (newStore: DarkModeStore) => {
53
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(newStore));
54
+ };
55
+
56
+ /** Add the light/dark class to an element */
57
+ const toggleDarkClass = (
58
+ el: Element,
59
+ {
60
+ current,
61
+ darkClass = defaultParams.darkClass,
62
+ lightClass = defaultParams.lightClass,
63
+ }: DarkModeStore
64
+ ) => {
65
+ if (current === 'dark') {
66
+ el.classList.remove(...arrayify(lightClass));
67
+ el.classList.add(...arrayify(darkClass));
68
+ } else {
69
+ el.classList.remove(...arrayify(darkClass));
70
+ el.classList.add(...arrayify(lightClass));
71
+ }
72
+ };
73
+
74
+ /** Coerce a string to a single item array, or return an array as-is */
75
+ const arrayify = (classes: string | string[]): string[] => {
76
+ const arr: string[] = [];
77
+ return arr.concat(classes).map((item) => item);
78
+ };
79
+
80
+ /** Update the preview iframe class */
81
+ const updatePreview = (store: DarkModeStore) => {
82
+ const iframe = document.getElementById(
83
+ 'storybook-preview-iframe'
84
+ ) as HTMLIFrameElement;
85
+
86
+ if (!iframe) {
87
+ return;
88
+ }
89
+
90
+ const iframeDocument =
91
+ iframe.contentDocument || iframe.contentWindow?.document;
92
+ const target = iframeDocument?.querySelector<HTMLElement>(store.classTarget);
93
+
94
+ if (!target) {
95
+ return;
96
+ }
97
+
98
+ toggleDarkClass(target, store);
99
+ };
100
+
101
+ /** Update the manager iframe class */
102
+ const updateManager = (store: DarkModeStore) => {
103
+ const manager = document.querySelector(store.classTarget);
104
+
105
+ if (!manager) {
106
+ return;
107
+ }
108
+
109
+ toggleDarkClass(manager, store);
110
+ };
111
+
112
+ /** Update changed dark mode settings and persist to localStorage */
113
+ export const store = (
114
+ userTheme: Partial<DarkModeStore> = {}
115
+ ): DarkModeStore => {
116
+ const storedItem = window.localStorage.getItem(STORAGE_KEY);
117
+
118
+ if (typeof storedItem === 'string') {
119
+ const stored = JSON.parse(storedItem) as DarkModeStore;
120
+
121
+ if (userTheme) {
122
+ if (userTheme.dark && !equal(stored.dark, userTheme.dark)) {
123
+ stored.dark = userTheme.dark;
124
+ updateStore(stored);
125
+ }
126
+
127
+ if (userTheme.light && !equal(stored.light, userTheme.light)) {
128
+ stored.light = userTheme.light;
129
+ updateStore(stored);
130
+ }
131
+ }
132
+
133
+ return stored;
134
+ }
135
+
136
+ return { ...defaultParams, ...userTheme } as DarkModeStore;
137
+ };
138
+
139
+ // On initial load, set the dark mode class on the manager
140
+ // This is needed if you're using mostly CSS overrides to styles the storybook
141
+ // Otherwise the default theme is set in src/preset/manager.tsx
142
+ updateManager(store());
143
+
144
+ interface DarkModeProps {
145
+ /** The storybook API */
146
+ api: API;
147
+ }
148
+
149
+ /** A toolbar icon to toggle between dark and light themes in storybook */
150
+ export function DarkMode({ api }: DarkModeProps) {
151
+ const [isDark, setDark] = React.useState(prefersDark.matches);
152
+ const darkModeParams = useParameter<Partial<DarkModeStore>>('darkMode', {});
153
+ const { current: defaultMode, stylePreview, ...params } = darkModeParams;
154
+ const channel = api.getChannel();
155
+ // Save custom themes on init
156
+ const userHasExplicitlySetTheTheme = React.useMemo(
157
+ () => store(params).userHasExplicitlySetTheTheme,
158
+ [params]
159
+ );
160
+ /** Set the theme in storybook, update the local state, and emit an event */
161
+ const setMode = React.useCallback(
162
+ (mode: Mode) => {
163
+ const currentStore = store();
164
+ api.setOptions({ theme: currentStore[mode] });
165
+ setDark(mode === 'dark');
166
+ api.getChannel().emit(DARK_MODE_EVENT_NAME, mode === 'dark');
167
+ updateManager(currentStore);
168
+ if (stylePreview) {
169
+ updatePreview(currentStore);
170
+ }
171
+ },
172
+ [api, stylePreview]
173
+ );
174
+
175
+ /** Update the theme settings in localStorage, react, and storybook */
176
+ const updateMode = React.useCallback(
177
+ (mode?: Mode) => {
178
+ const currentStore = store();
179
+ const current =
180
+ mode || (currentStore.current === 'dark' ? 'light' : 'dark');
181
+ updateStore({ ...currentStore, current });
182
+ setMode(current);
183
+ },
184
+ [setMode]
185
+ );
186
+
187
+ /** Update the theme based on the color preference */
188
+ function prefersDarkUpdate(event: MediaQueryListEvent) {
189
+ if (userHasExplicitlySetTheTheme || defaultMode) {
190
+ return;
191
+ }
192
+
193
+ updateMode(event.matches ? 'dark' : 'light');
194
+ }
195
+
196
+ /** Render the current theme */
197
+ const renderTheme = React.useCallback(() => {
198
+ const { current = 'light' } = store();
199
+ setMode(current);
200
+ }, [setMode]);
201
+
202
+ /** Handle the user event and side effects */
203
+ const handleIconClick = () => {
204
+ updateMode();
205
+ const currentStore = store();
206
+ updateStore({ ...currentStore, userHasExplicitlySetTheTheme: true });
207
+ };
208
+
209
+ /** When storybook params change update the stored themes */
210
+ React.useEffect(() => {
211
+ const currentStore = store();
212
+ // Ensure we use the stores `current` value first to persist
213
+ // themeing between page loads and story changes.
214
+ updateStore({
215
+ ...currentStore,
216
+ ...darkModeParams,
217
+ current: currentStore.current || darkModeParams.current,
218
+ });
219
+ renderTheme();
220
+ }, [darkModeParams, renderTheme]);
221
+ React.useEffect(() => {
222
+ channel.on(STORY_CHANGED, renderTheme);
223
+ channel.on(SET_STORIES, renderTheme);
224
+ channel.on(DOCS_RENDERED, renderTheme);
225
+ prefersDark.addListener(prefersDarkUpdate);
226
+ return () => {
227
+ channel.removeListener(STORY_CHANGED, renderTheme);
228
+ channel.removeListener(SET_STORIES, renderTheme);
229
+ channel.removeListener(DOCS_RENDERED, renderTheme);
230
+ prefersDark.removeListener(prefersDarkUpdate);
231
+ };
232
+ });
233
+ React.useEffect(() => {
234
+ channel.on(UPDATE_DARK_MODE_EVENT_NAME, updateMode);
235
+ return () => {
236
+ channel.removeListener(UPDATE_DARK_MODE_EVENT_NAME, updateMode);
237
+ };
238
+ });
239
+ // Storybook's first render doesn't have the global user params loaded so we
240
+ // need the effect to run whenever defaultMode is updated
241
+ React.useEffect(() => {
242
+ // If a users has set the mode this is respected
243
+ if (userHasExplicitlySetTheTheme) {
244
+ return;
245
+ }
246
+
247
+ if (defaultMode) {
248
+ updateMode(defaultMode);
249
+ } else if (prefersDark.matches) {
250
+ updateMode('dark');
251
+ }
252
+ }, [defaultMode, updateMode, userHasExplicitlySetTheTheme]);
253
+ return (
254
+ <IconButton
255
+ key="dark-mode"
256
+ title={
257
+ isDark ? 'Change theme to light mode' : 'Change theme to dark mode'
258
+ }
259
+ onClick={handleIconClick}
260
+ >
261
+ {isDark ? <SunIcon aria-hidden="true" /> : <MoonIcon aria-hidden="true" />}
262
+ </IconButton>
263
+ );
264
+ }
265
+
266
+ export default DarkMode;
@@ -0,0 +1,2 @@
1
+ export const DARK_MODE_EVENT_NAME = 'DARK_MODE';
2
+ export const UPDATE_DARK_MODE_EVENT_NAME = 'UPDATE_DARK_MODE';
package/src/index.tsx ADDED
@@ -0,0 +1,20 @@
1
+ import { addons, useState, useEffect } from 'storybook/preview-api';
2
+ import { DARK_MODE_EVENT_NAME } from './constants';
3
+ import { store } from './Tool';
4
+
5
+ /**
6
+ * Returns the current state of storybook's dark-mode
7
+ */
8
+ export function useDarkMode(): boolean {
9
+ const [isDark, setIsDark] = useState(store().current === 'dark');
10
+
11
+ useEffect(() => {
12
+ const chan = addons.getChannel();
13
+ chan.on(DARK_MODE_EVENT_NAME, setIsDark);
14
+ return () => chan.off(DARK_MODE_EVENT_NAME, setIsDark);
15
+ }, []);
16
+
17
+ return isDark;
18
+ }
19
+
20
+ export * from './constants';
@@ -0,0 +1,26 @@
1
+ import { addons } from 'storybook/manager-api';
2
+ import { Addon_TypesEnum } from 'storybook/internal/types';
3
+ import { themes } from 'storybook/theming';
4
+ import * as React from 'react';
5
+
6
+ import Tool, { prefersDark, store } from '../Tool';
7
+
8
+ const currentStore = store();
9
+ const currentTheme =
10
+ currentStore.current || (prefersDark.matches && 'dark') || 'light';
11
+
12
+ addons.setConfig({
13
+ theme: {
14
+ ...themes[currentTheme],
15
+ ...currentStore[currentTheme],
16
+ },
17
+ });
18
+
19
+ addons.register('storybook/dark-mode', (api) => {
20
+ addons.add('storybook/dark-mode', {
21
+ title: 'dark mode',
22
+ type: Addon_TypesEnum.TOOL,
23
+ match: ({ viewMode }) => viewMode === 'story' || viewMode === 'docs',
24
+ render: () => <Tool api={api} />,
25
+ });
26
+ });