pinafore/routes/_utils/themeEngine.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-02-16 08:59:44 -08:00
let meta = process.browser && document.getElementById('theThemeColor')
let offlineStyle = process.browser && document.getElementById('theOfflineStyle')
2018-01-21 15:20:50 -08: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-13 18:59:49 -08: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)
}
})
// inserting before the offline <style> ensures that the offline style wins when offline
document.head.insertBefore(link, offlineStyle)
}
export function switchToTheme (themeName) {
2018-01-21 15:20:50 -08:00
let themeColor = window.__themeColors[themeName]
meta.content = themeColor || window.__themeColors['default']
2018-01-13 18:59:49 -08:00
if (themeName !== 'default') {
loadCSS(`/theme-${themeName}.css`)
} else {
resetExistingTheme()
2018-01-13 18:59:49 -08:00
}
2018-02-08 22:29:29 -08:00
}