|
1 | 1 | const giscusPlugin = (hook, vm) => { |
2 | 2 | hook.ready(() => { |
3 | | - // Move giscus container to content area. |
| 3 | + // Move Giscus container to content area. |
4 | 4 | const content = document.querySelector('.content') |
5 | 5 | const giscusContainer = document.querySelector(`.giscus`) |
6 | 6 | if (content && giscusContainer) { |
7 | 7 | content.appendChild(giscusContainer) |
8 | 8 | } |
9 | | - // Add theme toggle event. |
| 9 | + // Initial theme setup. |
| 10 | + const iframe = document.querySelector('.giscus-frame') |
10 | 11 | const themeToggle = document.getElementById('docsify-darklight-theme') |
11 | | - if (themeToggle) { |
12 | | - themeToggle.addEventListener('click', () => toggleGiscusTheme(themeToggle)) |
13 | | - toggleGiscusTheme(themeToggle) |
| 12 | + if (iframe && themeToggle) { |
| 13 | + toggleGiscusTheme(themeToggle, iframe) |
14 | 14 | } |
15 | 15 | }) |
| 16 | + hook.doneEach(() => { |
| 17 | + // Update `term` parameter. |
| 18 | + const iframe = document.querySelector('.giscus-frame') |
| 19 | + if (iframe) { |
| 20 | + setupGiscusTerm(iframe) |
| 21 | + // Add theme toggle event. |
| 22 | + const themeToggle = document.getElementById('docsify-darklight-theme') |
| 23 | + if (themeToggle) { |
| 24 | + themeToggle.addEventListener('click', () => toggleGiscusTheme(themeToggle, iframe)) |
| 25 | + } |
| 26 | + } |
| 27 | + }) |
| 28 | +} |
| 29 | + |
| 30 | +const setupGiscusTerm = (iframe) => { |
| 31 | + // Replace `term` parameter in iframe src. |
| 32 | + const src = iframe.getAttribute('src') |
| 33 | + let term = decodeURIComponent(location.hash).replace('#', '') |
| 34 | + if (!term) term = '/' |
| 35 | + const newSrc = src.replace(/term=[^&]*/, `term=${encodeURIComponent(term)}`) |
| 36 | + iframe.setAttribute('src', newSrc) |
16 | 37 | } |
17 | 38 |
|
18 | | -const toggleGiscusTheme = (toggle) => { |
19 | | - const iframe = document.querySelector('.giscus-frame') |
20 | | - if (iframe) { |
21 | | - // Check if dark mode is enabled. |
22 | | - const isDark = toggle.getAttribute('data-link-title') === 'dark' |
23 | | - const theme = isDark ? 'dark_dimmed' : 'light' |
24 | | - // Replace `theme` parameter in iframe src. |
25 | | - const src = iframe.getAttribute('src') |
26 | | - const newSrc = src.replace( |
27 | | - /theme=[^&]*/, |
28 | | - `theme=${theme}` |
29 | | - ) |
30 | | - iframe.setAttribute('src', newSrc) |
31 | | - } |
| 39 | +const toggleGiscusTheme = (toggle, iframe) => { |
| 40 | + // Check if dark mode is enabled. |
| 41 | + const isDark = toggle.getAttribute('data-link-title') === 'dark' |
| 42 | + const theme = isDark ? 'dark_dimmed' : 'light' |
| 43 | + // Replace `theme` parameter in iframe src. |
| 44 | + const src = iframe.getAttribute('src') |
| 45 | + const newSrc = src.replace(/theme=[^&]*/, `theme=${theme}`) |
| 46 | + iframe.setAttribute('src', newSrc) |
32 | 47 | } |
33 | 48 |
|
34 | 49 | $docsify.plugins.push(giscusPlugin) |
0 commit comments