|
| 1 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +(() => { |
| 6 | + const mermaidUrl = 'https://cdn.jsdelivr.net/npm/mermaid@11.6.0/dist/mermaid.min.js'; |
| 7 | + const mermaidIntegrity = 'sha384-zkWMJO4sgpPUzyuOgDx8HB/K55glbAwajEpk1Go2NWRuPkPA/wIhoEJTuSkmOYrV'; |
| 8 | + const darkThemes = ['ayu', 'navy', 'coal']; |
| 9 | + const lightThemes = ['light', 'rust']; |
| 10 | + |
| 11 | + const classList = document.getElementsByTagName('html')[0].classList; |
| 12 | + |
| 13 | + let lastThemeWasLight = true; |
| 14 | + for (const cssClass of classList) { |
| 15 | + if (darkThemes.includes(cssClass)) { |
| 16 | + lastThemeWasLight = false; |
| 17 | + break; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + const loadMermaid = () => { |
| 22 | + if (window.mermaid) { |
| 23 | + return Promise.resolve(); |
| 24 | + } |
| 25 | + |
| 26 | + return new Promise((resolve, reject) => { |
| 27 | + const script = document.createElement('script'); |
| 28 | + script.src = mermaidUrl; |
| 29 | + script.integrity = mermaidIntegrity; |
| 30 | + script.crossOrigin = 'anonymous'; |
| 31 | + script.onload = resolve; |
| 32 | + script.onerror = () => reject(new Error(`Failed to load Mermaid from ${mermaidUrl}`)); |
| 33 | + document.head.appendChild(script); |
| 34 | + }); |
| 35 | + }; |
| 36 | + |
| 37 | + const renderMermaid = async () => { |
| 38 | + const theme = lastThemeWasLight ? 'default' : 'dark'; |
| 39 | + window.mermaid.initialize({ startOnLoad: false, theme }); |
| 40 | + await window.mermaid.run({ querySelector: '.mermaid' }); |
| 41 | + }; |
| 42 | + |
| 43 | + const reloadOnThemeChange = (themeIds, shouldReload) => { |
| 44 | + for (const themeId of themeIds) { |
| 45 | + const themeButton = document.getElementById(themeId); |
| 46 | + if (!themeButton) { |
| 47 | + continue; |
| 48 | + } |
| 49 | + |
| 50 | + themeButton.addEventListener('click', () => { |
| 51 | + if (shouldReload()) { |
| 52 | + window.location.reload(); |
| 53 | + } |
| 54 | + }); |
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + loadMermaid().then(renderMermaid).catch((error) => { |
| 59 | + console.error(error); |
| 60 | + }); |
| 61 | + |
| 62 | + // Simplest way to make Mermaid re-render diagrams in the new theme is via refreshing the page. |
| 63 | + reloadOnThemeChange(darkThemes, () => lastThemeWasLight); |
| 64 | + reloadOnThemeChange(lightThemes, () => !lastThemeWasLight); |
| 65 | +})(); |
0 commit comments