@kawapress/plugin-comments 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) KawaPress contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,156 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo-dark.png">
4
+ <img src="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo.png" alt="KawaPress" width="180">
5
+ </picture>
6
+ </p>
2
7
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
8
+ <h1 align="center">KawaPress</h1>
9
+
10
+ <p align="center">
11
+ <strong>A Vue-first static site generator for documentation and content-focused websites.</strong>
12
+ </p>
13
+
14
+ <p align="center">
15
+ Write in Markdown. Develop with real SSR. Extend everything through public APIs.
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress?label=npm&color=42b883" alt="npm version"></a>
20
+ <a href="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml"><img src="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml/badge.svg" alt="documentation build"></a>
21
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE"><img src="https://img.shields.io/github/license/ShenQingchuan/kawapress" alt="MIT license"></a>
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A522.12-339933?logo=nodedotjs&logoColor=white" alt="Node.js 22.12 or newer">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <a href="https://shenqingchuan.github.io/kawapress/en/">Documentation</a>
27
+ ·
28
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.zh-CN.md">简体中文</a>
29
+ </p>
30
+
31
+ If you run into any problems while using KawaPress, please [open an issue](https://github.com/ShenQingchuan/kawapress/issues). Your feedback helps shape the project during its early development.
32
+
33
+ ## Why KawaPress?
34
+
35
+ KawaPress turns Markdown into pre-rendered Vue websites. It keeps the familiar simplicity of a documentation generator while giving themes and plugins the same public extension points used by the official experience.
36
+
37
+ - **Real SSR during development** — every initial request is server-rendered, so SSR-only problems appear before build or deployment.
38
+ - **A complete default experience** — the built-in nagi (凪) preset includes responsive documentation layouts, dark mode, local search, syntax highlighting, Twoslash, code groups, multilingual navigation, and more.
39
+ - **Vue from end to end** — Markdown becomes Vue components, Vue Router handles navigation, and regular Vue SFCs fit naturally into content.
40
+ - **AI-ready output** — nagi generates page-level Markdown, locale-aware `llms.txt` and `llms-full.txt`, plus built-in copy actions.
41
+ - **One extension model** — Generator Plugins, Runtime Plugins, and Presets cover build-time behavior, the Vue runtime, themes, and reusable product setups without private theme hooks.
42
+
43
+ KawaPress is an independent project. It is not a VitePress fork or a drop-in replacement, and it intentionally does not use VitePress configuration.
44
+
45
+ ## Quick Start
46
+
47
+ You need [Node.js](https://nodejs.org/) 22.12 or newer.
48
+
49
+ Create a new site with the scaffolder:
50
+
51
+ ```sh
52
+ npm create kawapress@latest my-kawapress-site
53
+ cd my-kawapress-site
54
+ npm run dev
55
+ ```
56
+
57
+ `pnpm create kawapress my-kawapress-site` and `yarn create kawapress my-kawapress-site` do the same thing. The scaffolder asks for a site title and a default language, and can install dependencies for you.
58
+
59
+ If you would rather see every file from the start, set the site up by hand:
60
+
61
+ ```sh
62
+ mkdir my-kawapress-site
63
+ cd my-kawapress-site
64
+ pnpm init
65
+ pnpm add --save-dev kawapress
66
+ ```
67
+
68
+ Create `kawapress.config.ts`:
69
+
70
+ ```ts
71
+ import { nagi } from 'kawapress/nagi'
72
+
73
+ export default nagi({
74
+ title: 'My Docs',
75
+ })
76
+ ```
77
+
78
+ Create `index.md`:
79
+
80
+ ```md
81
+ ---
82
+ layout: home
83
+ title: My Docs
84
+ ---
85
+
86
+ # My Docs
87
+
88
+ Welcome to my KawaPress site.
89
+ ```
90
+
91
+ Start the development server:
92
+
93
+ ```sh
94
+ pnpm exec kawapress dev
95
+ ```
96
+
97
+ Build static files into `dist`:
98
+
99
+ ```sh
100
+ pnpm exec kawapress build
101
+ ```
102
+
103
+ The deployed output is static and does not require a Node.js server. npm and Yarn commands are available in the [Getting Started guide](https://shenqingchuan.github.io/kawapress/en/guide/getting-started).
104
+
105
+ > If your site directly imports Vue APIs or Vue components, also install `vue` as a development dependency.
106
+
107
+ ## What You Get
108
+
109
+ | Area | Included capability |
110
+ | --- | --- |
111
+ | Authoring | Markdown, frontmatter, Vue in Markdown, file-based routing, data loaders |
112
+ | Rendering | Shared development/build SSR semantics, hydration, Vue Router navigation |
113
+ | Documentation UI | nagi layouts, responsive sidebar, page outline, dark mode, i18n |
114
+ | Content | Shiki, Twoslash, code groups, code copy, containers, GitHub alerts |
115
+ | Discovery | Lazy local search and locale-aware navigation |
116
+ | AI consumption | Page `.md`, `llms.txt`, `llms-full.txt`, copy actions |
117
+ | Styling | UnoCSS integration with sensible nagi defaults |
118
+
119
+ The `kawapress` package includes nagi and its official plugins. A basic site only needs this one package; advanced users can compose the individual `@kawapress/*` packages directly.
120
+
121
+ ## Extension Model
122
+
123
+ KawaPress keeps extension boundaries explicit:
124
+
125
+ - a **Generator Plugin** extends configuration, Markdown, page data, Vite, and build artifacts;
126
+ - a **Runtime Plugin** extends the real Vue App and Vue Router in both SSR and the browser;
127
+ - a **Preset** combines configuration and plugins into a ready-to-use experience such as nagi.
128
+
129
+ A logical plugin is installed once and can provide both generator and runtime behavior. Learn more in the [Plugin System guide](https://shenqingchuan.github.io/kawapress/en/guide/plugin-system).
130
+
131
+ ## Documentation
132
+
133
+ - [Getting Started](https://shenqingchuan.github.io/kawapress/en/guide/getting-started)
134
+ - [What is KawaPress?](https://shenqingchuan.github.io/kawapress/en/guide/what-is-kawapress)
135
+ - [Markdown Extensions](https://shenqingchuan.github.io/kawapress/en/guide/markdown-extensions)
136
+ - [Internationalization](https://shenqingchuan.github.io/kawapress/en/guide/internationalization)
137
+ - [Plugin System](https://shenqingchuan.github.io/kawapress/en/guide/plugin-system)
138
+ - [Theme Customization](https://shenqingchuan.github.io/kawapress/en/guide/theme-customization)
139
+
140
+ ## Contributing
141
+
142
+ Issues and pull requests are welcome. For a large feature, please open an issue first so the direction can be agreed on before implementation.
143
+
144
+ ```sh
145
+ pnpm install
146
+ pnpm lint
147
+ pnpm typecheck
148
+ pnpm test
149
+ pnpm build
150
+ ```
151
+
152
+ KawaPress uses Node.js 22.12 or newer and pnpm 11.22.0 for repository development.
153
+
154
+ ## License
155
+
156
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress contributors
@@ -0,0 +1,156 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo-dark.png">
4
+ <img src="https://raw.githubusercontent.com/ShenQingchuan/kawapress/main/docs/public/kawapress-logo.png" alt="KawaPress" width="180">
5
+ </picture>
6
+ </p>
7
+
8
+ <h1 align="center">KawaPress</h1>
9
+
10
+ <p align="center">
11
+ <strong>以 Vue 为核心,面向文档与内容型网站的静态站点生成器。</strong>
12
+ </p>
13
+
14
+ <p align="center">
15
+ 用 Markdown 安心写作,在真实 SSR 中开发,通过公开能力自由扩展。
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="https://www.npmjs.com/package/kawapress"><img src="https://img.shields.io/npm/v/kawapress?label=npm&color=42b883" alt="npm 版本"></a>
20
+ <a href="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml"><img src="https://github.com/ShenQingchuan/kawapress/actions/workflows/deploy-pages.yml/badge.svg" alt="文档构建状态"></a>
21
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE"><img src="https://img.shields.io/github/license/ShenQingchuan/kawapress" alt="MIT 许可"></a>
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A522.12-339933?logo=nodedotjs&logoColor=white" alt="Node.js 22.12 或更高版本">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <a href="https://shenqingchuan.github.io/kawapress/">中文文档</a>
27
+ ·
28
+ <a href="https://github.com/ShenQingchuan/kawapress/blob/main/README.md">English</a>
29
+ </p>
30
+
31
+ 使用 KawaPress 时遇到任何问题,欢迎到 [提交 Issue](https://github.com/ShenQingchuan/kawapress/issues) 反馈,一起参与本项目的早期建设。
32
+
33
+ ## 为什么选择 KawaPress?
34
+
35
+ KawaPress 会把 Markdown 编译成预渲染的 Vue 网站。它保留了文档生成器简单、轻快的写作方式,同时让官方主题和第三方扩展使用完全相同的公开能力。
36
+
37
+ - **开发时也执行真实 SSR**:每次首次请求都会在服务端渲染。只在 SSR 中出现的问题,不必等到构建或上线后才发现。
38
+ - **默认体验完整**:内置 nagi(凪)预设,包含响应式文档布局、深浅色模式、本地搜索、代码高亮、Twoslash、代码组和多语言导航等常用能力。
39
+ - **从头到尾使用 Vue**:Markdown 会变成 Vue 组件,页面跳转交给 Vue Router;需要交互时,也可以自然地使用普通 Vue SFC。
40
+ - **面向 AI 的文档产物**:nagi 默认生成每页 `.md`、各语言的 `llms.txt` 与 `llms-full.txt`,并提供复制正文和链接的操作。
41
+ - **统一的扩展模型**:Generator Plugin、Runtime Plugin 与 Preset 分别覆盖生成阶段、Vue 运行时和能力组合,不依赖主题私有入口。
42
+
43
+ KawaPress 是一个独立项目,不是 VitePress 的分支或配置兼容层,也不能直接使用 VitePress 配置。
44
+
45
+ ## 快速开始
46
+
47
+ 请先准备 [Node.js](https://nodejs.org/) 22.12 或更高版本。
48
+
49
+ 用脚手架创建新站点:
50
+
51
+ ```sh
52
+ npm create kawapress@latest my-kawapress-site
53
+ cd my-kawapress-site
54
+ npm run dev
55
+ ```
56
+
57
+ `pnpm create kawapress my-kawapress-site` 和 `yarn create kawapress my-kawapress-site` 的作用完全一样。脚手架会询问站点标题和默认语言,也可以顺便帮你安装依赖。
58
+
59
+ 如果你更想从零看清每个文件,可以手动创建:
60
+
61
+ ```sh
62
+ mkdir my-kawapress-site
63
+ cd my-kawapress-site
64
+ pnpm init
65
+ pnpm add --save-dev kawapress
66
+ ```
67
+
68
+ 创建 `kawapress.config.ts`:
69
+
70
+ ```ts
71
+ import { nagi } from 'kawapress/nagi'
72
+
73
+ export default nagi({
74
+ title: 'My Docs',
75
+ })
76
+ ```
77
+
78
+ 创建 `index.md`:
79
+
80
+ ```md
81
+ ---
82
+ layout: home
83
+ title: My Docs
84
+ ---
85
+
86
+ # My Docs
87
+
88
+ 欢迎来到我的 KawaPress 站点。
89
+ ```
90
+
91
+ 启动开发服务器:
92
+
93
+ ```sh
94
+ pnpm exec kawapress dev
95
+ ```
96
+
97
+ 构建静态文件到 `dist`:
98
+
99
+ ```sh
100
+ pnpm exec kawapress build
101
+ ```
102
+
103
+ 部署产物是普通静态文件,不需要在服务器上继续运行 Node.js。npm 和 Yarn 的完整命令可以查看[快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)。
104
+
105
+ > 如果站点会直接导入 Vue API 或 Vue 组件,还需要把 `vue` 安装为开发依赖。
106
+
107
+ ## 默认包含什么?
108
+
109
+ | 范围 | 内置能力 |
110
+ | --- | --- |
111
+ | 内容编写 | Markdown、Frontmatter、在 Markdown 中使用 Vue、文件路由、Data Loader |
112
+ | 渲染 | 开发与构建共享 SSR 语义、Hydration、Vue Router 站内导航 |
113
+ | 文档界面 | nagi 布局、响应式 Sidebar、本页目录、深浅色模式、多语言 |
114
+ | 内容增强 | Shiki、Twoslash、代码组、代码复制、提示容器、GitHub Alerts |
115
+ | 内容发现 | 按需加载的本地搜索与多语言导航 |
116
+ | AI 读取 | 页面 `.md`、`llms.txt`、`llms-full.txt`、页面复制操作 |
117
+ | 样式 | UnoCSS 集成与 nagi 默认配置 |
118
+
119
+ `kawapress` 已经包含 nagi 和它使用的官方插件。普通文档站只需要安装这一个包;需要自行组合能力时,也可以直接使用独立的 `@kawapress/*` 包。
120
+
121
+ ## 扩展模型
122
+
123
+ KawaPress 把扩展边界分得很清楚:
124
+
125
+ - **Generator Plugin** 负责配置、Markdown、页面数据、Vite 与构建产物;
126
+ - **Runtime Plugin** 在 SSR 和浏览器中扩展真实的 Vue App 与 Vue Router;
127
+ - **Preset** 把配置和一组插件组合成可以直接使用的产品体验,例如 nagi。
128
+
129
+ 一个逻辑插件只需要安装一次,同时可以提供生成侧和运行侧能力。更多内容请查看[插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)。
130
+
131
+ ## 文档
132
+
133
+ - [快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)
134
+ - [KawaPress 是什么?](https://shenqingchuan.github.io/kawapress/guide/what-is-kawapress)
135
+ - [Markdown 语法扩展](https://shenqingchuan.github.io/kawapress/guide/markdown-extensions)
136
+ - [国际化](https://shenqingchuan.github.io/kawapress/guide/internationalization)
137
+ - [插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)
138
+ - [主题定制](https://shenqingchuan.github.io/kawapress/guide/theme-customization)
139
+
140
+ ## 参与贡献
141
+
142
+ 欢迎提交 Issue 和 Pull Request。如果准备增加较大的功能,请先创建 Issue,把目标和方案聊清楚后再开始实现。
143
+
144
+ ```sh
145
+ pnpm install
146
+ pnpm lint
147
+ pnpm typecheck
148
+ pnpm test
149
+ pnpm build
150
+ ```
151
+
152
+ KawaPress 仓库使用 Node.js 22.12 或更高版本,以及 pnpm 11.22.0 进行开发。
153
+
154
+ ## 开源许可
155
+
156
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress 贡献者
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@kawapress/plugin-comments",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "GitHub Discussions comments for KawaPress, powered by Giscus",
6
+ "license": "MIT",
7
+ "homepage": "https://shenqingchuan.github.io/kawapress/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ShenQingchuan/kawapress.git",
11
+ "directory": "packages/plugin-comments"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/ShenQingchuan/kawapress/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.ts",
19
+ "import": "./src/index.ts",
20
+ "default": "./src/index.ts"
21
+ },
22
+ "./runtime-plugin": {
23
+ "types": "./src/runtime-plugin.ts",
24
+ "import": "./src/runtime-plugin.ts",
25
+ "default": "./src/runtime-plugin.ts"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "src/**/!(*.test.*)"
31
+ ],
32
+ "engines": {
33
+ "node": ">=22.12.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org/"
38
+ },
39
+ "peerDependencies": {
40
+ "vue": "^3.5.41",
41
+ "kawapress": "0.1.0"
42
+ },
43
+ "devDependencies": {
44
+ "happy-dom": "^20.11.6",
45
+ "vite": "^8.2.2",
46
+ "vue": "^3.5.41",
47
+ "kawapress": "0.1.0"
48
+ }
6
49
  }
@@ -0,0 +1,24 @@
1
+ @layer kawa.plugin {
2
+ .kawa-comments {
3
+ display: flex;
4
+ flex-direction: column;
5
+ gap: 1rem;
6
+ margin-top: 3rem;
7
+ padding-top: 1.5rem;
8
+ border-top: 1px solid var(--kawa-c-divider);
9
+ }
10
+
11
+ .kawa-comments__heading {
12
+ margin: 0;
13
+ color: var(--kawa-c-text-1);
14
+ font-size: 1.25rem;
15
+ font-weight: 600;
16
+ line-height: 1.4;
17
+ }
18
+
19
+ .kawa-comments__thread iframe {
20
+ display: block;
21
+ width: 100%;
22
+ border: 0;
23
+ }
24
+ }
@@ -0,0 +1,126 @@
1
+ <script setup lang="ts">
2
+ import type { CommentsThread } from '../provider'
3
+ import { usePageData, useSite } from 'kawapress/client'
4
+ import { computed, onBeforeUnmount, useId, useTemplateRef, watch } from 'vue'
5
+ import { useCommentsAppearance } from '../composables/useCommentsAppearance'
6
+ import { createGiscusProvider, resolveGiscusLang } from '../providers/giscus'
7
+ import commentsOptions from '../runtime-options'
8
+ import { resolveCommentsLabels } from '../translations'
9
+
10
+ /** How far outside the viewport the comment section starts loading. */
11
+ const PRELOAD_MARGIN = '200px'
12
+
13
+ const site = useSite()
14
+ const page = usePageData()
15
+ const section = useTemplateRef<HTMLElement>('section')
16
+ const threadHost = useTemplateRef<HTMLElement>('thread')
17
+ const appearance = useCommentsAppearance()
18
+ const provider = createGiscusProvider(commentsOptions.giscus)
19
+ const headingId = useId()
20
+
21
+ const labels = computed(() => resolveCommentsLabels(
22
+ commentsOptions,
23
+ site.value.localeIndex,
24
+ site.value.lang,
25
+ ))
26
+ const lang = computed(() => resolveGiscusLang(site.value.lang))
27
+ const enabled = computed(() => page.value?.frontmatter.comments !== false)
28
+ const pagePath = computed(() => page.value?.path ?? '')
29
+
30
+ /** The mounted widget, once the section reached the viewport. */
31
+ let activeThread: CommentsThread | undefined
32
+ let activeThreadPath: string | undefined
33
+ let reachedViewport = false
34
+ let observer: IntersectionObserver | undefined
35
+
36
+ // The section element is created and removed by `v-if`, so the observer follows it.
37
+ watch(section, () => {
38
+ stopObserving()
39
+ closeThread()
40
+ reachedViewport = false
41
+ observeSection()
42
+ }, { flush: 'post' })
43
+
44
+ // A reused instance must show the discussion of the new page, and giscus finds
45
+ // that discussion from the live URL and page title. Rebuilding the widget is
46
+ // therefore more reliable than patching a live iframe through `setConfig`.
47
+ watch(pagePath, () => {
48
+ if (reachedViewport) {
49
+ mountThread()
50
+ }
51
+ }, { flush: 'post' })
52
+
53
+ watch(appearance, (value) => {
54
+ activeThread?.setAppearance(value)
55
+ })
56
+
57
+ onBeforeUnmount(() => {
58
+ stopObserving()
59
+ closeThread()
60
+ })
61
+
62
+ function observeSection(): void {
63
+ const element = section.value
64
+ if (import.meta.env.SSR || !element) {
65
+ return
66
+ }
67
+ if (typeof IntersectionObserver === 'undefined') {
68
+ loadThread()
69
+ return
70
+ }
71
+ observer = new IntersectionObserver((entries) => {
72
+ if (entries.some(entry => entry.isIntersecting)) {
73
+ loadThread()
74
+ }
75
+ }, { rootMargin: PRELOAD_MARGIN })
76
+ observer.observe(element)
77
+ }
78
+
79
+ function stopObserving(): void {
80
+ observer?.disconnect()
81
+ observer = undefined
82
+ }
83
+
84
+ function loadThread(): void {
85
+ reachedViewport = true
86
+ stopObserving()
87
+ mountThread()
88
+ }
89
+
90
+ function mountThread(): void {
91
+ const host = threadHost.value
92
+ if (!host || !enabled.value) {
93
+ return
94
+ }
95
+ const path = pagePath.value
96
+ if (activeThread && activeThreadPath === path) {
97
+ return
98
+ }
99
+ closeThread()
100
+ activeThread = provider.create(host, {
101
+ appearance: appearance.value,
102
+ lang: lang.value,
103
+ })
104
+ activeThreadPath = path
105
+ }
106
+
107
+ function closeThread(): void {
108
+ activeThread?.destroy()
109
+ activeThread = undefined
110
+ activeThreadPath = undefined
111
+ }
112
+ </script>
113
+
114
+ <template>
115
+ <section
116
+ v-if="enabled"
117
+ ref="section"
118
+ class="kawa-comments"
119
+ :aria-labelledby="headingId"
120
+ >
121
+ <h2 :id="headingId" class="kawa-comments__heading">
122
+ {{ labels.heading }}
123
+ </h2>
124
+ <div ref="thread" class="kawa-comments__thread" />
125
+ </section>
126
+ </template>
@@ -0,0 +1,57 @@
1
+ import type { Ref } from 'vue'
2
+ import type { CommentsAppearance } from '../provider'
3
+ import { onBeforeUnmount, onMounted, ref } from 'vue'
4
+
5
+ const DARK_SCHEME_QUERY = '(prefers-color-scheme: dark)'
6
+
7
+ /**
8
+ * Follows the appearance the theme puts on `<html>`. A `dark` or `light` class
9
+ * wins, otherwise the operating system preference decides. Themes that switch
10
+ * appearance only toggle that class, so a `MutationObserver` keeps the comment
11
+ * widget in sync without any theme-specific code here.
12
+ */
13
+ export function useCommentsAppearance(): Ref<CommentsAppearance> {
14
+ const appearance = ref<CommentsAppearance>('light')
15
+ let stopFollowing: (() => void) | undefined
16
+
17
+ onMounted(() => {
18
+ const root = document.documentElement
19
+ const prefersDark = window.matchMedia(DARK_SCHEME_QUERY)
20
+ const update = (): void => {
21
+ appearance.value = resolveAppearance(root, prefersDark.matches)
22
+ }
23
+ const classObserver = new MutationObserver(update)
24
+
25
+ update()
26
+ classObserver.observe(root, {
27
+ attributeFilter: ['class'],
28
+ attributes: true,
29
+ })
30
+ prefersDark.addEventListener('change', update)
31
+
32
+ stopFollowing = () => {
33
+ classObserver.disconnect()
34
+ prefersDark.removeEventListener('change', update)
35
+ }
36
+ })
37
+
38
+ onBeforeUnmount(() => {
39
+ stopFollowing?.()
40
+ })
41
+
42
+ return appearance
43
+ }
44
+
45
+ /** Resolves the current appearance from the theme class and the OS preference. */
46
+ export function resolveAppearance(
47
+ root: Element,
48
+ prefersDark: boolean,
49
+ ): CommentsAppearance {
50
+ if (root.classList.contains('dark')) {
51
+ return 'dark'
52
+ }
53
+ if (root.classList.contains('light')) {
54
+ return 'light'
55
+ }
56
+ return prefersDark ? 'dark' : 'light'
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { KawaPressPlugin } from 'kawapress'
2
+ import type { CommentsPluginOptions } from './options'
3
+ import { definePlugin } from 'kawapress'
4
+ import { resolveCommentsOptions } from './options'
5
+ import { commentsOptionsPlugin } from './vite-plugin'
6
+
7
+ export const COMMENTS_PLUGIN_NAME = '@kawapress/plugin-comments'
8
+
9
+ /**
10
+ * Adds a GitHub Discussions comment section to every documentation page. The
11
+ * options are validated here, at config time, and handed to the runtime as
12
+ * plain JSON through a virtual module.
13
+ */
14
+ export function commentsPlugin(
15
+ options: CommentsPluginOptions,
16
+ ): KawaPressPlugin {
17
+ const resolved = resolveCommentsOptions(options)
18
+
19
+ return definePlugin({
20
+ name: COMMENTS_PLUGIN_NAME,
21
+ setup(api) {
22
+ api.vite((config) => {
23
+ config.plugins ??= []
24
+ config.plugins.push(commentsOptionsPlugin(resolved))
25
+ })
26
+ },
27
+ })
28
+ }
29
+
30
+ export default commentsPlugin
31
+
32
+ export type {
33
+ CommentsLabels,
34
+ CommentsPluginOptions,
35
+ GiscusInputPosition,
36
+ GiscusLoading,
37
+ GiscusMapping,
38
+ GiscusOptions,
39
+ ResolvedCommentsOptions,
40
+ ResolvedGiscusOptions,
41
+ } from './options'
42
+ export type {
43
+ CommentsAppearance,
44
+ CommentsProvider,
45
+ CommentsThread,
46
+ CommentsThreadContext,
47
+ } from './provider'
package/src/options.ts ADDED
@@ -0,0 +1,252 @@
1
+ /** Discussion key giscus uses to find the thread of a page. */
2
+ export type GiscusMapping
3
+ = | 'pathname'
4
+ | 'url'
5
+ | 'title'
6
+ | 'og:title'
7
+ | 'specific'
8
+ | 'number'
9
+
10
+ export type GiscusInputPosition = 'top' | 'bottom'
11
+
12
+ export type GiscusLoading = 'lazy' | 'eager'
13
+
14
+ /** Heading text of the comment section. */
15
+ export interface CommentsLabels {
16
+ heading: string
17
+ }
18
+
19
+ export interface GiscusOptions {
20
+ /** GitHub repository that hosts the discussions, `owner/name`. */
21
+ repo: string
22
+ /** `data-repo-id` from the snippet on giscus.app. */
23
+ repoId: string
24
+ /** Discussion category name. */
25
+ category: string
26
+ /** `data-category-id` from the snippet on giscus.app. */
27
+ categoryId: string
28
+ /** How a page is matched to a discussion. */
29
+ mapping?: GiscusMapping
30
+ /** Only match discussions whose title exactly equals the mapping term. */
31
+ strict?: boolean
32
+ /** Show the reaction bar above the comment box. */
33
+ reactionsEnabled?: boolean
34
+ /** Place the comment box above or below the thread. */
35
+ inputPosition?: GiscusInputPosition
36
+ /** Lazy loading of the giscus iframe: use `lazy` inside long pages. */
37
+ loading?: GiscusLoading
38
+ }
39
+
40
+ export interface CommentsPluginOptions {
41
+ giscus: GiscusOptions
42
+ /** Override the section heading for every locale. */
43
+ labels?: Partial<CommentsLabels>
44
+ /** Override the section heading for one KawaPress locale key. */
45
+ localeLabels?: Record<string, Partial<CommentsLabels>>
46
+ }
47
+
48
+ /** Every optional giscus option filled in, so the runtime never guesses. */
49
+ export type ResolvedGiscusOptions = Required<GiscusOptions>
50
+
51
+ /** Options handed to the browser through the generator virtual module. */
52
+ export interface ResolvedCommentsOptions {
53
+ giscus: ResolvedGiscusOptions
54
+ labels: Partial<CommentsLabels>
55
+ localeLabels: Record<string, Partial<CommentsLabels>>
56
+ }
57
+
58
+ /**
59
+ * Mappings that do not need an explicit term. `specific` and `number` want a
60
+ * fixed discussion term for each page, which this plugin does not collect yet.
61
+ */
62
+ const SUPPORTED_MAPPINGS = ['pathname', 'url', 'title', 'og:title'] as const
63
+
64
+ const GISCUS_DEFAULTS = {
65
+ mapping: 'pathname',
66
+ strict: false,
67
+ reactionsEnabled: true,
68
+ inputPosition: 'bottom',
69
+ loading: 'lazy',
70
+ } as const
71
+
72
+ const OPTION_PATH = 'plugins: [commentsPlugin({ giscus: ... })]'
73
+
74
+ /**
75
+ * Validates the plugin options and fills in the giscus defaults, so the runtime
76
+ * receives one complete, JSON-serializable object.
77
+ */
78
+ export function resolveCommentsOptions(
79
+ options: CommentsPluginOptions | undefined,
80
+ ): ResolvedCommentsOptions {
81
+ if (!options || typeof options !== 'object') {
82
+ throw new Error(
83
+ `KawaPress Comments: ${OPTION_PATH} is missing its options. `
84
+ + 'Pass the values from the snippet that https://giscus.app generates for your repository, '
85
+ + 'for example commentsPlugin({ giscus: { repo, repoId, category, categoryId } }).',
86
+ )
87
+ }
88
+
89
+ const giscus = options.giscus
90
+ if (!giscus || typeof giscus !== 'object') {
91
+ throw new Error(
92
+ `KawaPress Comments: ${OPTION_PATH} has no "giscus" section. `
93
+ + 'Open https://giscus.app, install the giscus app on your repository, and copy '
94
+ + 'repo, repoId, category, and categoryId from the generated snippet.',
95
+ )
96
+ }
97
+
98
+ const resolved: ResolvedGiscusOptions = {
99
+ ...GISCUS_DEFAULTS,
100
+ repo: requireText(giscus.repo, 'giscus.repo', 'For example "your-name/your-repo".'),
101
+ repoId: requireText(
102
+ giscus.repoId,
103
+ 'giscus.repoId',
104
+ 'Copy the "data-repo-id" value from the snippet on https://giscus.app.',
105
+ ),
106
+ category: requireText(
107
+ giscus.category,
108
+ 'giscus.category',
109
+ 'For example "Comments"; it is the discussion category name shown on https://giscus.app.',
110
+ ),
111
+ categoryId: requireText(
112
+ giscus.categoryId,
113
+ 'giscus.categoryId',
114
+ 'Copy the "data-category-id" value from the snippet on https://giscus.app.',
115
+ ),
116
+ strict: requireBoolean(giscus.strict, 'giscus.strict', GISCUS_DEFAULTS.strict),
117
+ reactionsEnabled: requireBoolean(
118
+ giscus.reactionsEnabled,
119
+ 'giscus.reactionsEnabled',
120
+ GISCUS_DEFAULTS.reactionsEnabled,
121
+ ),
122
+ mapping: requireMapping(giscus.mapping),
123
+ inputPosition: requireChoice(
124
+ giscus.inputPosition,
125
+ 'giscus.inputPosition',
126
+ ['top', 'bottom'],
127
+ GISCUS_DEFAULTS.inputPosition,
128
+ ),
129
+ loading: requireChoice(
130
+ giscus.loading,
131
+ 'giscus.loading',
132
+ ['lazy', 'eager'],
133
+ GISCUS_DEFAULTS.loading,
134
+ ),
135
+ }
136
+
137
+ return {
138
+ giscus: resolved,
139
+ labels: resolveLabelsOption(options.labels, 'labels'),
140
+ localeLabels: resolveLocaleLabelsOption(options.localeLabels),
141
+ }
142
+ }
143
+
144
+ function requireText(
145
+ value: unknown,
146
+ path: string,
147
+ hint: string,
148
+ ): string {
149
+ if (typeof value !== 'string' || value.trim() === '') {
150
+ throw new Error(
151
+ `KawaPress Comments: ${OPTION_PATH} needs a non-empty string at "${path}", `
152
+ + `received ${JSON.stringify(value)}. ${hint}`,
153
+ )
154
+ }
155
+ return value.trim()
156
+ }
157
+
158
+ function requireBoolean(
159
+ value: unknown,
160
+ path: string,
161
+ fallback: boolean,
162
+ ): boolean {
163
+ if (value === undefined) {
164
+ return fallback
165
+ }
166
+ if (typeof value !== 'boolean') {
167
+ throw new TypeError(
168
+ `KawaPress Comments: "${path}" must be true or false, received ${JSON.stringify(value)}.`,
169
+ )
170
+ }
171
+ return value
172
+ }
173
+
174
+ function requireMapping(value: unknown): GiscusMapping {
175
+ if (value === undefined) {
176
+ return GISCUS_DEFAULTS.mapping
177
+ }
178
+ if (isOneOf(value, SUPPORTED_MAPPINGS)) {
179
+ return value
180
+ }
181
+ const reason = isOneOf(value, ['specific', 'number'])
182
+ ? `"${value}" needs a discussion term written by hand for every page, which this plugin does not read yet.`
183
+ : `Received ${JSON.stringify(value)}.`
184
+ throw new Error(
185
+ `KawaPress Comments: "giscus.mapping" must be one of ${SUPPORTED_MAPPINGS.join(', ')}. `
186
+ + `${reason} Use "pathname" to give every page its own discussion automatically.`,
187
+ )
188
+ }
189
+
190
+ function requireChoice<Value extends string>(
191
+ value: unknown,
192
+ path: string,
193
+ allowed: readonly Value[],
194
+ fallback: Value,
195
+ ): Value {
196
+ if (value === undefined) {
197
+ return fallback
198
+ }
199
+ if (isOneOf(value, allowed)) {
200
+ return value
201
+ }
202
+ throw new Error(
203
+ `KawaPress Comments: "${path}" must be one of ${allowed.join(', ')}, received ${JSON.stringify(value)}.`,
204
+ )
205
+ }
206
+
207
+ function isOneOf<Value extends string>(
208
+ value: unknown,
209
+ allowed: readonly Value[],
210
+ ): value is Value {
211
+ return typeof value === 'string' && (allowed as readonly string[]).includes(value)
212
+ }
213
+
214
+ function resolveLabelsOption(
215
+ labels: Partial<CommentsLabels> | undefined,
216
+ path: string,
217
+ ): Partial<CommentsLabels> {
218
+ if (labels === undefined) {
219
+ return {}
220
+ }
221
+ if (!labels || typeof labels !== 'object' || Array.isArray(labels)) {
222
+ throw new Error(
223
+ `KawaPress Comments: "${path}" must be an object such as { heading: 'Comments' }, received ${JSON.stringify(labels)}.`,
224
+ )
225
+ }
226
+ if (labels.heading === undefined) {
227
+ return {}
228
+ }
229
+ if (typeof labels.heading !== 'string' || labels.heading.trim() === '') {
230
+ throw new Error(
231
+ `KawaPress Comments: "${path}.heading" must be a non-empty string, received ${JSON.stringify(labels.heading)}.`,
232
+ )
233
+ }
234
+ return { heading: labels.heading }
235
+ }
236
+
237
+ function resolveLocaleLabelsOption(
238
+ localeLabels: Record<string, Partial<CommentsLabels>> | undefined,
239
+ ): Record<string, Partial<CommentsLabels>> {
240
+ if (localeLabels === undefined) {
241
+ return {}
242
+ }
243
+ if (!localeLabels || typeof localeLabels !== 'object' || Array.isArray(localeLabels)) {
244
+ throw new Error(
245
+ `KawaPress Comments: "localeLabels" must map a locale key to labels, `
246
+ + `for example { en: { heading: 'Comments' } }, received ${JSON.stringify(localeLabels)}.`,
247
+ )
248
+ }
249
+ return Object.fromEntries(Object.entries(localeLabels).map(([locale, labels]) => (
250
+ [locale, resolveLabelsOption(labels, `localeLabels.${locale}`)]
251
+ )))
252
+ }
@@ -0,0 +1,28 @@
1
+ /** Appearance of the site, mirrored from the theme for the comment widget. */
2
+ export type CommentsAppearance = 'light' | 'dark'
3
+
4
+ export interface CommentsThreadContext {
5
+ /** Appearance at the moment the thread is created. */
6
+ appearance: CommentsAppearance
7
+ /** Interface language of the widget, for example `zh-CN` or `en`. */
8
+ lang: string
9
+ }
10
+
11
+ /** One mounted comment thread. */
12
+ export interface CommentsThread {
13
+ /** Follows a new site appearance without reloading the widget. */
14
+ setAppearance: (appearance: CommentsAppearance) => void
15
+ /** Removes every element the widget added. */
16
+ destroy: () => void
17
+ }
18
+
19
+ /**
20
+ * A comment backend. The component owns lazy loading, page and appearance
21
+ * tracking; a provider only knows how to put its widget into a container.
22
+ */
23
+ export interface CommentsProvider {
24
+ create: (
25
+ container: HTMLElement,
26
+ context: CommentsThreadContext,
27
+ ) => CommentsThread
28
+ }
@@ -0,0 +1,98 @@
1
+ import type { ResolvedGiscusOptions } from '../options'
2
+ import type {
3
+ CommentsAppearance,
4
+ CommentsProvider,
5
+ CommentsThreadContext,
6
+ } from '../provider'
7
+
8
+ export const GISCUS_SCRIPT_URL = 'https://giscus.app/client.js'
9
+
10
+ const GISCUS_ORIGIN = 'https://giscus.app'
11
+
12
+ const CHINESE_GISCUS_LANG = 'zh-CN'
13
+ const FALLBACK_GISCUS_LANG = 'en'
14
+
15
+ /**
16
+ * giscus ships its own interface translations, so the site language is mapped
17
+ * to the closest supported one instead of forwarding arbitrary values.
18
+ */
19
+ export function resolveGiscusLang(lang: string | undefined): string {
20
+ return (lang ?? '').toLowerCase().startsWith('zh')
21
+ ? CHINESE_GISCUS_LANG
22
+ : FALLBACK_GISCUS_LANG
23
+ }
24
+
25
+ /**
26
+ * Creates comment threads with the official giscus client script. Every thread
27
+ * derives its discussion from the live URL and page title, which is why the
28
+ * component rebuilds the thread after a route change instead of reusing it.
29
+ */
30
+ export function createGiscusProvider(
31
+ options: ResolvedGiscusOptions,
32
+ ): CommentsProvider {
33
+ return {
34
+ create(container, context) {
35
+ const script = createGiscusScript(options, context)
36
+ container.append(script)
37
+
38
+ return {
39
+ setAppearance(appearance) {
40
+ script.dataset.theme = appearance
41
+ sendGiscusTheme(container, appearance)
42
+ },
43
+ destroy() {
44
+ script.remove()
45
+ container.replaceChildren()
46
+ },
47
+ }
48
+ },
49
+ }
50
+ }
51
+
52
+ function createGiscusScript(
53
+ options: ResolvedGiscusOptions,
54
+ context: CommentsThreadContext,
55
+ ): HTMLScriptElement {
56
+ const script = document.createElement('script')
57
+ script.src = GISCUS_SCRIPT_URL
58
+ script.async = true
59
+ script.crossOrigin = 'anonymous'
60
+ setGiscusData(script, {
61
+ repo: options.repo,
62
+ repoId: options.repoId,
63
+ category: options.category,
64
+ categoryId: options.categoryId,
65
+ mapping: options.mapping,
66
+ strict: options.strict ? '1' : '0',
67
+ reactionsEnabled: options.reactionsEnabled ? '1' : '0',
68
+ inputPosition: options.inputPosition,
69
+ theme: context.appearance,
70
+ lang: context.lang,
71
+ loading: options.loading,
72
+ })
73
+ return script
74
+ }
75
+
76
+ function setGiscusData(
77
+ script: HTMLScriptElement,
78
+ attributes: Record<string, string>,
79
+ ): void {
80
+ for (const [name, value] of Object.entries(attributes)) {
81
+ script.dataset[name] = value
82
+ }
83
+ }
84
+
85
+ /**
86
+ * giscus has no JavaScript API; the official way to change a live thread is a
87
+ * `postMessage` to the iframe it rendered next to our script.
88
+ */
89
+ function sendGiscusTheme(
90
+ container: HTMLElement,
91
+ theme: CommentsAppearance,
92
+ ): void {
93
+ const frame = container.querySelector<HTMLIFrameElement>('iframe.giscus-frame')
94
+ frame?.contentWindow?.postMessage(
95
+ { giscus: { setConfig: { theme } } },
96
+ GISCUS_ORIGIN,
97
+ )
98
+ }
@@ -0,0 +1,10 @@
1
+ import type { ResolvedCommentsOptions } from './options'
2
+ import options from 'virtual:kawapress-comments-options'
3
+
4
+ /**
5
+ * Site options as the generator published them. The runtime reads them here so
6
+ * no module on the browser side imports the generator half of this package.
7
+ */
8
+ const resolvedOptions: ResolvedCommentsOptions = options
9
+
10
+ export default resolvedOptions
@@ -0,0 +1,10 @@
1
+ import { defineRuntimePlugin } from 'kawapress'
2
+ import Comments from './components/Comments.vue'
3
+ import './comments.css'
4
+
5
+ export default defineRuntimePlugin({
6
+ name: '@kawapress/plugin-comments',
7
+ setup(api) {
8
+ api.addToOutlet('doc.after', { id: 'comments', component: Comments })
9
+ },
10
+ })
@@ -0,0 +1,35 @@
1
+ import type { CommentsLabels, ResolvedCommentsOptions } from './options'
2
+
3
+ const ENGLISH_LABELS: CommentsLabels = {
4
+ heading: 'Comments',
5
+ }
6
+
7
+ const CHINESE_LABELS: CommentsLabels = {
8
+ heading: '评论',
9
+ }
10
+
11
+ export type CommentsLabelOptions = Pick<
12
+ ResolvedCommentsOptions,
13
+ 'labels' | 'localeLabels'
14
+ >
15
+
16
+ /**
17
+ * Built-in labels in the language of the current locale, then the site-wide
18
+ * override, then the override for this locale key.
19
+ */
20
+ export function resolveCommentsLabels(
21
+ options: CommentsLabelOptions,
22
+ localeIndex: string,
23
+ lang: string | undefined,
24
+ ): CommentsLabels {
25
+ const builtIn = isChinese(lang) ? CHINESE_LABELS : ENGLISH_LABELS
26
+ return {
27
+ ...builtIn,
28
+ ...options.labels,
29
+ ...options.localeLabels[localeIndex],
30
+ }
31
+ }
32
+
33
+ export function isChinese(lang: string | undefined): boolean {
34
+ return (lang ?? '').toLowerCase().startsWith('zh')
35
+ }
@@ -0,0 +1,4 @@
1
+ declare module 'virtual:kawapress-comments-options' {
2
+ const options: import('./options').ResolvedCommentsOptions
3
+ export default options
4
+ }
@@ -0,0 +1,33 @@
1
+ import type { Plugin } from 'vite'
2
+ import type { ResolvedCommentsOptions } from './options'
3
+ import { stringifyJson } from 'kawapress'
4
+
5
+ export const COMMENTS_OPTIONS_MODULE_ID = 'virtual:kawapress-comments-options'
6
+
7
+ const RESOLVED_MODULE_ID = `\0${COMMENTS_OPTIONS_MODULE_ID}`
8
+
9
+ /**
10
+ * Publishes the plugin options to the browser as plain JSON. The runtime half of
11
+ * the plugin must never import this package's generator half.
12
+ */
13
+ export function commentsOptionsPlugin(
14
+ options: ResolvedCommentsOptions,
15
+ ): Plugin {
16
+ return {
17
+ name: 'kawapress:comments-options',
18
+ resolveId(id) {
19
+ if (id === COMMENTS_OPTIONS_MODULE_ID) {
20
+ return RESOLVED_MODULE_ID
21
+ }
22
+ },
23
+ load(id) {
24
+ if (id !== RESOLVED_MODULE_ID) {
25
+ return
26
+ }
27
+ return `export default ${stringifyJson(options, {
28
+ label: 'options of @kawapress/plugin-comments',
29
+ path: 'commentsPlugin',
30
+ })}`
31
+ },
32
+ }
33
+ }