blog/src/components/Comments/Giscus.astro
2025-05-31 00:25:36 +01:00

123 lines
2.9 KiB
Text

---
import { defaultLocale, themeConfig } from '@/config'
import { giscusLocaleMap } from '@/i18n/config'
const {
repo = '',
repoID = '',
category = '',
categoryID = '',
mapping = 'pathname',
strict = '0',
reactionsEnabled = '1',
emitMetadata = '0',
inputPosition = 'bottom',
} = themeConfig.comment?.giscus ?? {}
const siteUrl = themeConfig.site.url
const shouldRender = Boolean(repo && repoID && categoryID)
---
{shouldRender && (
<div
id="giscus"
class="giscus mt-16"
></div>
<script
is:inline
define:vars={{
repo,
repoID,
category,
categoryID,
mapping,
strict,
reactionsEnabled,
emitMetadata,
inputPosition,
giscusLocaleMap,
defaultLocale,
siteUrl,
}}
>
function getThemeUrl() {
const isDark = document.documentElement.classList.contains('dark')
return isDark
? `${siteUrl}/vendors/giscus/theme-dark.css`
: `${siteUrl}/vendors/giscus/theme-light.css`
// For local development
// ? `http://localhost:4321/vendors/giscus/theme-dark.css`
// : `http://localhost:4321/vendors/giscus/theme-light.css`
}
function setupGiscus() {
const giscusContainer = document.getElementById('giscus')
if (!giscusContainer)
return
giscusContainer.innerHTML = ''
const currentPath = window.location.pathname
const pathLang = Object.keys(giscusLocaleMap).find(code =>
currentPath.startsWith(`/${code}/`),
)
const lang = pathLang || defaultLocale
const currentGiscusLang = giscusLocaleMap[lang]
const script = document.createElement('script')
script.src = 'https://giscus.app/client.js'
script.crossOrigin = 'anonymous'
script.async = true
// Set up basic attributes
const dataAttributes = {
repo,
repoId: repoID,
category: undefined,
categoryId: categoryID,
mapping,
strict,
reactionsEnabled,
emitMetadata,
inputPosition,
theme: getThemeUrl(),
lang: currentGiscusLang,
}
// Add category conditionally
if (category)
dataAttributes.category = category
// Apply all attributes
Object.assign(script.dataset, dataAttributes)
try {
giscusContainer.appendChild(script)
}
catch (error) {
console.error('Failed to setup Giscus:', error)
}
}
function updateGiscusTheme() {
const iframe = document.querySelector('.giscus-frame')
if (!iframe || !iframe.contentWindow)
return
try {
iframe.contentWindow.postMessage(
{ giscus: { setConfig: { theme: getThemeUrl() } } },
'https://giscus.app',
)
}
catch (error) {
console.error('Failed to update Giscus theme:', error)
}
}
setupGiscus()
document.addEventListener('astro:page-load', setupGiscus)
document.addEventListener('theme-changed', updateGiscusTheme)
</script>
)}