2019-06-01 22:07:31 +02:00
|
|
|
const prefersDarkTheme = process.browser && window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
|
|
const meta = process.browser && document.getElementById('theThemeColor')
|
2019-02-12 06:03:51 +01:00
|
|
|
|
2019-05-25 17:19:11 +02:00
|
|
|
export const INLINE_THEME = 'default' // theme that does not require external CSS
|
|
|
|
export const DEFAULT_LIGHT_THEME = 'default' // theme that is shown by default
|
|
|
|
export const DEFAULT_DARK_THEME = 'ozark' // theme that is shown for prefers-color-scheme:dark
|
2019-02-12 06:03:51 +01:00
|
|
|
export const DEFAULT_THEME = prefersDarkTheme ? DEFAULT_DARK_THEME : DEFAULT_LIGHT_THEME
|
2018-01-22 00:20:50 +01:00
|
|
|
|
2018-11-24 09:41:36 +01:00
|
|
|
function getExistingThemeLink () {
|
|
|
|
return document.head.querySelector('link[rel=stylesheet][href^="/theme-"]')
|
|
|
|
}
|
|
|
|
|
|
|
|
function resetExistingTheme () {
|
|
|
|
let existingLink = getExistingThemeLink()
|
|
|
|
if (existingLink) {
|
|
|
|
document.head.removeChild(existingLink)
|
2018-01-14 03:59:49 +01:00
|
|
|
}
|
2018-11-24 09:41:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function loadCSS (href) {
|
|
|
|
let existingLink = getExistingThemeLink()
|
|
|
|
|
|
|
|
let link = document.createElement('link')
|
|
|
|
link.rel = 'stylesheet'
|
|
|
|
link.href = href
|
|
|
|
|
|
|
|
link.addEventListener('load', function onload () {
|
|
|
|
link.removeEventListener('load', onload)
|
|
|
|
if (existingLink) { // remove after load to avoid flash of default theme
|
|
|
|
document.head.removeChild(existingLink)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2019-06-01 22:07:31 +02:00
|
|
|
document.head.appendChild(link)
|
2018-11-24 09:41:36 +01:00
|
|
|
}
|
|
|
|
|
2019-06-01 22:07:31 +02:00
|
|
|
export function switchToTheme (themeName = DEFAULT_THEME, enableGrayscale) {
|
|
|
|
if (enableGrayscale) {
|
|
|
|
themeName = prefersDarkTheme ? 'grayscale-dark' : 'grayscale'
|
|
|
|
}
|
2018-01-22 00:20:50 +01:00
|
|
|
let themeColor = window.__themeColors[themeName]
|
2019-02-12 06:03:51 +01:00
|
|
|
meta.content = themeColor || window.__themeColors[DEFAULT_THEME]
|
2019-05-25 17:19:11 +02:00
|
|
|
if (themeName !== INLINE_THEME) {
|
2018-01-14 03:59:49 +01:00
|
|
|
loadCSS(`/theme-${themeName}.css`)
|
2018-11-24 09:41:36 +01:00
|
|
|
} else {
|
|
|
|
resetExistingTheme()
|
2018-01-14 03:59:49 +01:00
|
|
|
}
|
2018-02-09 07:29:29 +01:00
|
|
|
}
|