|
| 1 | +import modeOptions from './modeOptions' |
| 2 | + |
| 3 | +export function activateMode (mode) { |
| 4 | + console.log(mode) |
| 5 | + const rootElement = document.querySelector(':root') |
| 6 | + const options = modeOptions[mode] |
| 7 | + |
| 8 | + for (const k in options) { |
| 9 | + rootElement.style.setProperty(k, options[k]) |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +export function activateDarkMode () { |
| 14 | + const rootElement = document.querySelector(':root') |
| 15 | + const darkTheme = { |
| 16 | + '--background-color': '#25272a', |
| 17 | + '--box-shadow': '0 1px 6px 0 rgba(0, 0, 0, .9)', |
| 18 | + '--box-shadow-hover': '0 2px 26px 0 rgba(0, 0, 0, .9)' |
| 19 | + } |
| 20 | + for (const k in darkTheme) { |
| 21 | + rootElement.style.setProperty(k, darkTheme[k]) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +export function activateLightMode () { |
| 26 | + const rootElement = document.querySelector(':root') |
| 27 | + const lightTheme = { |
| 28 | + '--background-color': '#fff', |
| 29 | + '--box-shadow': '0 1px 6px 0 rgba(0, 0, 0, 0.2)', |
| 30 | + '--box-shadow-hover': '0 2px 16px 0 rgba(0, 0, 0, 0.2)' |
| 31 | + } |
| 32 | + for (const k in lightTheme) { |
| 33 | + rootElement.style.setProperty(k, lightTheme[k]) |
| 34 | + } |
| 35 | +} |
| 36 | +/** |
| 37 | + * Sets a color scheme for the website. |
| 38 | + * If browser supports "prefers-color-scheme" it will respect the setting for light or dark mode |
| 39 | + * otherwise it will set a dark theme during night time |
| 40 | + */ |
| 41 | +export default function setMode () { |
| 42 | + const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches |
| 43 | + const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches |
| 44 | + const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches |
| 45 | + const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified |
| 46 | + |
| 47 | + window.matchMedia('(prefers-color-scheme: dark)').addListener(e => e.matches && activateMode('dark')) |
| 48 | + window.matchMedia('(prefers-color-scheme: light)').addListener(e => e.matches && activateMode('light')) |
| 49 | + |
| 50 | + if (isDarkMode) activateMode('dark') |
| 51 | + if (isLightMode) activateMode('light') |
| 52 | + if (isNotSpecified || hasNoSupport) { |
| 53 | + console.log('You specified no preference for a color scheme or your browser does not support it. I schedule dark mode during night time.') |
| 54 | + const now = new Date() |
| 55 | + const hour = now.getHours() |
| 56 | + if (hour < 4 || hour >= 16) { |
| 57 | + activateMode('dark') |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments