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