|
| 1 | +function activateDarkMode() { |
| 2 | + const rootElement = document.querySelector(':root') |
| 3 | + const darkTheme = { |
| 4 | + '--background-color': '#1e1e1e', |
| 5 | + '--primary-color': '#157efb', |
| 6 | + '--font-color': '#dedede', |
| 7 | + '--subtle-primary-color': '#151513', |
| 8 | + '--block-background-color': '#323232', |
| 9 | + '--menu-item-color': '#dedede', |
| 10 | + '--menu-item-hover-color': '#157efb', |
| 11 | + '--menu-item-alert-bg': '#151513', |
| 12 | + '--menu-item-alert-shadow': '#151513', |
| 13 | + '--alert-border-color': '#000', |
| 14 | + '--tertiary-color:': '#727680' |
| 15 | + } |
| 16 | + for(k in darkTheme) { |
| 17 | + rootElement.style.setProperty(k, darkTheme[k]) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +function activateLightMode() { |
| 22 | + const rootElement = document.querySelector(':root') |
| 23 | + const lightTheme = { |
| 24 | + '--background-color': '#fff', |
| 25 | + '--page-width': '70em', |
| 26 | + '--primary-color': '#151513', |
| 27 | + '--font-color': '#151513', |
| 28 | + '--subtle-primary-color': '#151513', |
| 29 | + '--block-background-color': '#f1f3f4', |
| 30 | + '--menu-item-color': '#000', |
| 31 | + '--menu-item-hover-color': '#000', |
| 32 | + '--menu-item-alert-bg': '#ffffff', |
| 33 | + '--menu-item-alert-shadow': '#dfe1e7', |
| 34 | + '--alert-border-color': '#dfe1e7', |
| 35 | + '--tertiary-color:': '#727680' |
| 36 | + } |
| 37 | + for(k in lightTheme) { |
| 38 | + rootElement.style.setProperty(k, lightTheme[k]) |
| 39 | + } |
| 40 | +} |
| 41 | +/** |
| 42 | + * Sets a color scheme for the website. |
| 43 | + * If browser supports "prefers-color-scheme" it will respect the setting for light or dark mode |
| 44 | + * otherwise it will set a dark theme during night time |
| 45 | + */ |
| 46 | +export default function setColorScheme() { |
| 47 | + const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches |
| 48 | + const isLightMode = window.matchMedia("(prefers-color-scheme: light)").matches |
| 49 | + const isNotSpecified = window.matchMedia("(prefers-color-scheme: no-preference)").matches |
| 50 | + const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified; |
| 51 | + |
| 52 | + window.matchMedia("(prefers-color-scheme: dark)").addListener(e => e.matches && activateDarkMode()) |
| 53 | + window.matchMedia("(prefers-color-scheme: light)").addListener(e => e.matches && activateLightMode()) |
| 54 | + |
| 55 | + if(isDarkMode) activateDarkMode() |
| 56 | + if(isLightMode) activateLightMode() |
| 57 | + if(isNotSpecified || hasNoSupport) { |
| 58 | + console.log('You specified no preference for a color scheme or your browser does not support it. I schedule dark mode during night time.') |
| 59 | + now = new Date(); |
| 60 | + hour = now.getHours(); |
| 61 | + if (hour < 4 || hour >= 16) { |
| 62 | + activateDarkMode(); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments