Files
hinode/assets/js/navbar.js
Mark Dumay 091526a17b Fix navbar color mode update
Fixes Switching themes does not work properly #1177
2024-10-20 11:43:50 +02:00

76 lines
2.4 KiB
JavaScript

const fixed = {{ site.Params.navigation.fixed }}
const navbar = document.querySelector('.navbar')
const togglers = document.querySelectorAll('.main-nav-toggler')
const modeSelectors = document.querySelectorAll('.switch-mode-collapsed')
const colorsBG = ['body', 'secondary', 'tertiary']
function updateNavbar () {
let storedTheme
if (typeof getLocalStorage === "function") {
storedTheme = getLocalStorage('theme', null, 'functional')
}
if (window.scrollY > 75) {
navbar.classList.add('nav-active')
if (storedTheme) {
navbar.setAttribute('data-bs-theme', storedTheme)
}
} else {
navbar.classList.remove('nav-active')
const defaultTheme = navbar.getAttribute('data-bs-overlay')
const targetTheme = defaultTheme ? defaultTheme : storedTheme
if (targetTheme) {
navbar.setAttribute('data-bs-theme', defaultTheme)
}
}
}
if ((navbar !== null) && (window.performance.getEntriesByType)) {
if (window.performance.getEntriesByType('navigation')[0].type === 'reload') {
fixed && updateNavbar()
}
}
if (navbar !== null && togglers !== null) {
// observe state changes to the site's color mode
const html = document.querySelector('html')
const config = {
attributes: true,
attributeFilter: ['data-bs-theme']
}
const Observer = new MutationObserver((mutationrecords) => {
fixed && updateNavbar()
})
Observer.observe(html, config)
// initialize background color
const color = (navbar.getAttribute('data-navbar-color') || 'body')
const bg = colorsBG.includes(color) ? `var(--bs-${color}-bg)` : `var(--bs-navbar-color-${color})`
navbar.style.setProperty('--bs-navbar-expanded-color', bg)
// set the navbar background color to opaque when scrolling past a breakpoint
window.onscroll = () => {
fixed && updateNavbar()
}
// set the navbar background color to opaque when expanded
for (let i = 0; i < togglers.length; ++i) {
togglers[i].onclick = () => {
navbar.classList.toggle('navbar-expanded')
}
}
// invoke the navbar toggler for each mode switcher to collapse the main menu afterwards
for (let i = 0; i < modeSelectors.length; ++i) {
modeSelectors[i].onclick = () => {
for (let j = 0; j < togglers.length; ++j) {
const toggler = togglers[j]
if (toggler.getAttribute('aria-expanded') === 'true') {
toggler.click()
}
}
}
}
}