forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetThemeProps.ts
67 lines (57 loc) · 1.95 KB
/
getThemeProps.ts
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
type ThemeT = { name: string; color_mode: string }
const defaultCSSThemeProps = {
colorMode: 'auto', // light, dark, auto
nightTheme: 'dark',
dayTheme: 'light',
}
export const defaultComponentThemeProps = {
colorMode: 'auto', // day, night, auto
nightTheme: 'dark',
dayTheme: 'light',
}
const cssColorModeToComponentColorMode: Record<string, string> = {
auto: 'auto',
light: 'day',
dark: 'night',
}
const supportedThemes = ['light', 'dark', 'dark_dimmed']
/*
* Our version of primer/css is out of date, so we can only support known themes.
* For the least jarring experience possible, we fallback to the color_mode (light / dark) if provided by the theme, otherwise our own defaults
*/
function getSupportedTheme(theme: ThemeT | undefined, fallbackTheme: string) {
if (!theme) {
return fallbackTheme
}
return supportedThemes.includes(theme.name) ? theme.name : theme.color_mode
}
/*
* Returns theme props for consumption by either primer/css or primer/components
* based on the cookie and/or fallback values
*/
export function getThemeProps(req: any, mode?: 'css') {
let cookieValue: {
color_mode?: 'auto' | 'light' | 'dark'
dark_theme?: ThemeT
light_theme?: ThemeT
} = {}
const defaultThemeProps = mode === 'css' ? defaultCSSThemeProps : defaultComponentThemeProps
if (req.cookies?.color_mode) {
try {
cookieValue = JSON.parse(decodeURIComponent(req.cookies.color_mode))
} catch {
// do nothing
}
}
// The cookie value is a primer/css color_mode. sometimes we need to convert that to a primer/components compatible version
const colorMode =
(mode === 'css'
? cookieValue.color_mode
: cssColorModeToComponentColorMode[cookieValue.color_mode || '']) ||
defaultThemeProps.colorMode
return {
colorMode,
nightTheme: getSupportedTheme(cookieValue.dark_theme, defaultThemeProps.nightTheme),
dayTheme: getSupportedTheme(cookieValue.light_theme, defaultThemeProps.dayTheme),
}
}