pinafore/src/routes/_utils/themeEngine.js

42 lines
1.2 KiB
JavaScript
Raw Normal View History

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