utterances 是基于 GitHub issues 构建的轻量级评论小部件,通过此组件可以将 Github issues 应用于任何网站
前置条件
- 一个公开的 github repo
- 在该 repo 中安装utterances app
简单集成
打开utterances官网
在 configuration 节点填写 repo 信息等,填写好后会生成对应的组件代码
我使用的是 PaperMod1 主题,将生成好的代码放入
layouts/partials/comments.html
<!--layouts/partials/comments.html--> <script src="https://utteranc.es/client.js" repo="[ENTER REPO HERE]" issue-term="pathname" theme="github-light" label="Comment" crossorigin="anonymous" async ></script>
然后在
config.yaml
中开启评论功能即可简单集成params: comments: true
动态主题适配
PaperMod 有明亮和暗黑两种颜色模式,而 utterances 的主题是编码时就写在script
标签中的,为了使 comments 组件的主题适配 PaperMod 颜色主题,有以下两个步骤:
主题动态初始化
<!-- layouts/partials/comments.html -->
<script>
(function () {
let theme = localStorage.getItem("pref-theme");
// already has prefer theme
if (theme) {
theme = theme === "dark" ? "github-dark" : "github-light";
}
// auto detected
else {
theme = window.matchMedia("(prefers-color-scheme: dark)").matches
? "github-dark"
: "github-light";
}
const comment = document.createElement("script");
comment.src = "https://utteranc.es/client.js";
comment.crossorigin = "anonymous";
comment.async = true;
comment.setAttribute("repo", "fissssssh/fissssssh.github.io");
comment.setAttribute("issue-term", "pathname");
comment.setAttribute("label", "Comment");
comment.setAttribute("theme", theme);
document.body.appendChild(comment);
})();
</script>
用户未切换主题时,Local Storage 中还没有
pref-theme
的值,需要识别系统主题来确定评论组件的主题
主题动态切换
<!-- layouts/partials/extend_footer.html -->
{{- if (not site.Params.disableThemeToggle) }}
<script>
document.getElementById("theme-toggle").addEventListener("click", () => {
const iframe = document.querySelector(".utterances-frame");
const message = {
type: "set-theme",
theme:
localStorage.getItem("pref-theme") === "light" // if current theme is light, then set comment widget's theme to dark, otherwise light.
? "github-dark"
: "github-light",
};
iframe?.contentWindow.postMessage(message, "https://utteranc.es");
});
</script>
{{- end }}
PaperMod 会将当前颜色主题存在
localStorage
->pref-theme
下