-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathno-flash-color-mode-plugin.ts
More file actions
68 lines (62 loc) · 2.32 KB
/
no-flash-color-mode-plugin.ts
File metadata and controls
68 lines (62 loc) · 2.32 KB
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
import type {LoadContext, PluginModule} from '@docusaurus/types';
type ThemeConfigWithColorMode = {
colorMode?: {
defaultMode?: string;
respectPrefersColorScheme?: boolean;
};
};
const noFlashColorModePlugin: PluginModule<void> = (context: LoadContext) => {
const themeConfig = (context.siteConfig.themeConfig ?? {}) as ThemeConfigWithColorMode;
const defaultMode = themeConfig.colorMode?.defaultMode ?? 'light';
const respectPrefers = themeConfig.colorMode?.respectPrefersColorScheme ?? false;
return {
name: 'no-flash-color-mode-plugin',
injectHtmlTags() {
return {
headTags: [
{
tagName: 'style',
innerHTML: 'html { visibility: hidden; } html[data-theme] { visibility: visible; }',
},
{
tagName: 'script',
innerHTML: `(function() {
var defaultMode = '${defaultMode}';
var respectPrefersColorScheme = ${respectPrefers};
var storageKey = 'theme';
function getStoredTheme() {
try {
return window.localStorage.getItem(storageKey);
} catch (e) {
return null;
}
}
function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
var storedTheme = getStoredTheme();
var theme = storedTheme || (respectPrefersColorScheme ? getSystemTheme() : defaultMode);
document.documentElement.setAttribute('data-theme', theme);
document.documentElement.setAttribute('data-theme-choice', storedTheme || (respectPrefersColorScheme ? 'system' : defaultMode));
document.documentElement.style.colorScheme = theme;
if (document.body) {
document.body.style.colorScheme = theme;
}
var observer = new MutationObserver(function() {
var newTheme = document.documentElement.getAttribute('data-theme');
if (newTheme) {
document.documentElement.style.colorScheme = newTheme;
if (document.body) {
document.body.style.colorScheme = newTheme;
}
}
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
})();`,
},
],
};
},
};
};
export default noFlashColorModePlugin;