pinafore/routes/_utils/themeEngine.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-02-16 16:59:44 +00:00
let meta = process.browser && document.getElementById('theThemeColor')
let offlineStyle = process.browser && document.getElementById('theOfflineStyle')
2018-01-21 23:20:50 +00: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 02:59:49 +00: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 23:20:50 +00:00
let themeColor = window.__themeColors[themeName]
meta.content = themeColor || window.__themeColors['default']
2018-01-14 02:59:49 +00:00
if (themeName !== 'default') {
loadCSS(`/theme-${themeName}.css`)
} else {
resetExistingTheme()
2018-01-14 02:59:49 +00:00
}
2018-02-09 06:29:29 +00:00
}