pinafore/routes/_utils/themeEngine.js
Nolan Lawson 48a1bd47b3
refactor(themes): use CSS specificity order for themes (#684)
The point of this PR is to make it easier to implement scrollbars (#683).

With this PR, the themes move from a body tag-based system (e.g. `body.theme-scarlet`) to a system where they simply declare global CSS and we use CSS specificity order to give us the right theme.
2018-11-24 00:41:36 -08:00

42 lines
1.2 KiB
JavaScript

let meta = process.browser && document.getElementById('theThemeColor')
let offlineStyle = process.browser && document.getElementById('theOfflineStyle')
function getExistingThemeLink () {
return document.head.querySelector('link[rel=stylesheet][href^="/theme-"]')
}
function resetExistingTheme () {
let existingLink = getExistingThemeLink()
if (existingLink) {
document.head.removeChild(existingLink)
}
}
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) {
let themeColor = window.__themeColors[themeName]
meta.content = themeColor || window.__themeColors['default']
if (themeName !== 'default') {
loadCSS(`/theme-${themeName}.css`)
} else {
resetExistingTheme()
}
}