|
| 1 | +<script setup lang="ts"> |
| 2 | +import { onMounted, onBeforeUnmount, watch, ref, nextTick, toRef, type Ref } from "vue"; |
| 3 | +
|
| 4 | +const props = defineProps<{ |
| 5 | + theme: string; |
| 6 | +}>(); |
| 7 | +
|
| 8 | +const containerRef = ref<HTMLDivElement | null>(null); |
| 9 | +
|
| 10 | +function mountUtterances(theme: string) { |
| 11 | + const container = containerRef.value; |
| 12 | + if (!container) return; |
| 13 | +
|
| 14 | + if (container.querySelector("iframe.utterances-frame")) return; |
| 15 | +
|
| 16 | + const script = document.createElement("script"); |
| 17 | +
|
| 18 | + script.src = "https://utteranc.es/client.js"; |
| 19 | + script.async = true; |
| 20 | + script.crossOrigin = "anonymous"; |
| 21 | +
|
| 22 | + script.setAttribute("repo", "toothlessdev/toothlessdev-comments"); |
| 23 | + script.setAttribute("issue-term", "pathname"); |
| 24 | + script.setAttribute("label", "blog-comment"); |
| 25 | + script.setAttribute("theme", theme); |
| 26 | +
|
| 27 | + container.appendChild(script); |
| 28 | +} |
| 29 | +
|
| 30 | +function setUtterancesTheme(theme: string) { |
| 31 | + const iframe = containerRef.value?.querySelector<HTMLIFrameElement>("iframe.utterances-frame"); |
| 32 | + if (!iframe?.contentWindow) return; |
| 33 | + iframe.contentWindow.postMessage({ type: "set-theme", theme }, "https://utteranc.es"); |
| 34 | +} |
| 35 | +
|
| 36 | +onMounted(async () => { |
| 37 | + await nextTick(); |
| 38 | + mountUtterances(props.theme); |
| 39 | +}); |
| 40 | +
|
| 41 | +watch(toRef(props, "theme"), (t) => { |
| 42 | + if (!containerRef.value?.querySelector("iframe.utterances-frame")) { |
| 43 | + mountUtterances(t); |
| 44 | + return; |
| 45 | + } |
| 46 | + setUtterancesTheme(t); |
| 47 | +}); |
| 48 | +
|
| 49 | +onBeforeUnmount(() => { |
| 50 | + const container = containerRef.value; |
| 51 | + if (!container) return; |
| 52 | +
|
| 53 | + container.querySelector("iframe.utterances-frame")?.remove(); |
| 54 | +}); |
| 55 | +</script> |
| 56 | + |
| 57 | +<template> |
| 58 | + <div ref="containerRef" /> |
| 59 | +</template> |
0 commit comments