|
27 | 27 | <a class="site-button" id="theme-toggle" style="cursor: pointer;"></a> |
28 | 28 |
|
29 | 29 | <script> |
| 30 | + const light = 'light'; |
| 31 | + const dark = 'dark'; |
| 32 | + const system = 'system'; |
30 | 33 | const storageKey = 'dpfa-docs-theme'; |
31 | 34 |
|
| 35 | + const isThemePreferred = function(theme) { |
| 36 | + const state = window.matchMedia(`(prefers-color-scheme: ${theme})`); |
| 37 | + |
| 38 | + if (!state) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + return !!state.matches; |
| 43 | + } |
| 44 | + |
| 45 | + const getDefaultTheme = function() { |
| 46 | + if (isThemePreferred(dark)) { |
| 47 | + return dark; |
| 48 | + } |
| 49 | + |
| 50 | + return light; |
| 51 | + } |
| 52 | + |
| 53 | + const resolveTheme = function(theme) { |
| 54 | + if (theme === system) { |
| 55 | + return getDefaultTheme(); |
| 56 | + } |
| 57 | + |
| 58 | + return theme; |
| 59 | + } |
| 60 | + |
32 | 61 | const button = document.getElementById('theme-toggle'); |
33 | | - const loadedTheme = localStorage.getItem(storageKey) || 'light'; |
| 62 | + const loadedTheme = localStorage.getItem(storageKey) || system; |
34 | 63 |
|
35 | 64 | const setTheme = function(theme) { |
36 | 65 | localStorage.setItem(storageKey, theme); |
37 | 66 |
|
38 | | - if (theme === 'light') { |
| 67 | + const realTheme = resolveTheme(theme); |
| 68 | + |
| 69 | + if (realTheme === light) { |
39 | 70 | button.innerHTML = `<svg width='18px' height='18px'><use href="#svg-moon"></use></svg>`; |
40 | 71 | } else { |
41 | 72 | button.innerHTML = `<svg width='18px' height='18px'><use href="#svg-sun"></use></svg>`; |
42 | 73 | } |
43 | 74 |
|
44 | | - jtd.setTheme(theme); |
| 75 | + jtd.setTheme(realTheme); |
45 | 76 | } |
46 | 77 |
|
47 | 78 | const toggleTheme = function() { |
48 | 79 | const theme = localStorage.getItem(storageKey); |
49 | | - if (theme === 'light') { |
50 | | - setTheme('dark'); |
| 80 | + const realTheme = resolveTheme(theme); |
| 81 | + |
| 82 | + if (realTheme === light) { |
| 83 | + setTheme(dark); |
51 | 84 | } else { |
52 | | - setTheme('light'); |
| 85 | + setTheme(light); |
53 | 86 | } |
54 | 87 | } |
55 | 88 |
|
|
0 commit comments