Files
puzzle-design-kb/mermaid-init.js
Bryce faa30b9285 Fix: Check if theme button elements exist before adding event listeners
The mermaid-init script was throwing 'Uncaught TypeError: can't access
property addEventListener, document.getElementById(...) is null' because
it tried to attach click handlers to theme toggle buttons (ayu, navy, coal,
light, rust) that may not exist on all pages.

Fixed by:
- Wrapping theme button event listener registration in null checks
- Using DOMContentLoaded fallback when document is still loading
- Keeping mermaid.initialize() call outside the check since it needs to
  run early with startOnLoad: true
2026-03-19 20:14:58 -07:00

54 lines
1.7 KiB
JavaScript

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
(() => {
const darkThemes = ['ayu', 'navy', 'coal'];
const lightThemes = ['light', 'rust'];
const classList = document.getElementsByTagName('html')[0].classList;
let lastThemeWasLight = true;
for (const cssClass of classList) {
if (darkThemes.includes(cssClass)) {
lastThemeWasLight = false;
break;
}
}
const theme = lastThemeWasLight ? 'default' : 'dark';
mermaid.initialize({ startOnLoad: true, theme });
// Simplest way to make mermaid re-render the diagrams in the new theme is via refreshing the page
function initThemeButtons() {
for (const darkTheme of darkThemes) {
const darkBtn = document.getElementById(darkTheme);
if (darkBtn) {
darkBtn.addEventListener('click', () => {
if (lastThemeWasLight) {
window.location.reload();
}
});
}
}
for (const lightTheme of lightThemes) {
const lightBtn = document.getElementById(lightTheme);
if (lightBtn) {
lightBtn.addEventListener('click', () => {
if (!lastThemeWasLight) {
window.location.reload();
}
});
}
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initThemeButtons);
} else {
initThemeButtons();
}
})();