SanYeCao-blog/src/components/remark42-embed.svelte

76 lines
1.8 KiB
Svelte
Raw Normal View History

<script>
import { onMount } from "svelte";
export let slug;
let pagePath = `/posts/${slug}/`;
2026-04-04 10:07:50 +00:00
function getTheme() {
2026-04-04 10:14:25 +00:00
return document.documentElement.classList.contains("dark")
? "dark"
: "light";
2026-04-04 10:07:50 +00:00
}
2026-04-04 10:14:25 +00:00
function applyRemark42Theme() {
if (window.REMARK42 && typeof window.REMARK42.changeTheme === "function") {
2026-04-04 10:07:50 +00:00
window.REMARK42.changeTheme(getTheme());
2026-04-04 10:14:25 +00:00
return true;
2026-04-04 10:07:50 +00:00
}
2026-04-04 10:14:25 +00:00
return false;
2026-04-04 10:07:50 +00:00
}
onMount(() => {
const scriptId = "remark42-script";
window.remark_config = {
2026-04-04 17:57:22 +00:00
host: import.meta.env.PUBLIC_REMARK42_HOST,
site_id: import.meta.env.PUBLIC_REMARK42_SITE_ID,
components: ["embed"],
show_rss_subscription: false,
2026-04-04 10:07:50 +00:00
theme: getTheme(),
url: pagePath,
page_id: pagePath,
};
2026-04-04 10:07:50 +00:00
if (!document.getElementById(scriptId)) {
const script = document.createElement("script");
script.id = scriptId;
script.async = true;
script.innerHTML = `
!function(e,n){
for(var o=0;o<e.length;o++){
var r=n.createElement("script"),c=".js",d=n.head||n.body;
"noModule"in r?(r.type="module",c=".mjs"):r.async=!0;
r.defer=!0;
r.src=window.remark_config.host+"/web/"+e[o]+c;
d.appendChild(r);
}
}(window.remark_config.components||["embed"],document);
`;
document.body.appendChild(script);
}
2026-04-04 10:14:25 +00:00
const applyWhenReady = setInterval(() => {
if (applyRemark42Theme()) {
clearInterval(applyWhenReady);
}
}, 200);
2026-04-04 10:07:50 +00:00
const observer = new MutationObserver(() => {
2026-04-04 10:14:25 +00:00
applyRemark42Theme();
2026-04-04 10:07:50 +00:00
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class"],
});
return () => {
2026-04-04 10:14:25 +00:00
clearInterval(applyWhenReady);
2026-04-04 10:07:50 +00:00
observer.disconnect();
};
});
</script>
<div id="remark42"></div>