@kawapress/plugin-code-block 0.0.1-beta.1

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 ADDED
@@ -0,0 +1,145 @@
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>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/beta?label=npm%20beta&color=42b883" alt="npm beta 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
+ > [!IMPORTANT]
32
+ > KawaPress is in beta. It is ready for testing and early projects, but APIs may change before 0.1.0. Please pin the version when adopting it today.
33
+
34
+ ## Why KawaPress?
35
+
36
+ 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.
37
+
38
+ - **Real SSR during development** — every initial request is server-rendered, so SSR-only problems appear before build or deployment.
39
+ - **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.
40
+ - **Vue from end to end** — Markdown becomes Vue components, Vue Router handles navigation, and regular Vue SFCs fit naturally into content.
41
+ - **AI-ready output** — nagi generates page-level Markdown, locale-aware `llms.txt` and `llms-full.txt`, plus built-in copy actions.
42
+ - **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.
43
+
44
+ KawaPress is an independent project. It is not a VitePress fork or a drop-in replacement, and it intentionally does not use VitePress configuration.
45
+
46
+ ## Quick Start
47
+
48
+ You need [Node.js](https://nodejs.org/) 22.12 or newer.
49
+
50
+ ```sh
51
+ mkdir my-kawapress-site
52
+ cd my-kawapress-site
53
+ pnpm init
54
+ pnpm add --save-dev kawapress
55
+ ```
56
+
57
+ Create `kawapress.config.ts`:
58
+
59
+ ```ts
60
+ import { nagi } from 'kawapress/nagi'
61
+
62
+ export default nagi({
63
+ title: 'My Docs',
64
+ })
65
+ ```
66
+
67
+ Create `index.md`:
68
+
69
+ ```md
70
+ ---
71
+ layout: home
72
+ title: My Docs
73
+ ---
74
+
75
+ # My Docs
76
+
77
+ Welcome to my KawaPress site.
78
+ ```
79
+
80
+ Start the development server:
81
+
82
+ ```sh
83
+ pnpm exec kawapress dev
84
+ ```
85
+
86
+ Build static files into `dist`:
87
+
88
+ ```sh
89
+ pnpm exec kawapress build
90
+ ```
91
+
92
+ 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).
93
+
94
+ > If your site directly imports Vue APIs or Vue components, also install `vue` as a development dependency.
95
+
96
+ ## What You Get
97
+
98
+ | Area | Included capability |
99
+ | --- | --- |
100
+ | Authoring | Markdown, frontmatter, Vue in Markdown, file-based routing, data loaders |
101
+ | Rendering | Shared development/build SSR semantics, hydration, Vue Router navigation |
102
+ | Documentation UI | nagi layouts, responsive sidebar, page outline, dark mode, i18n |
103
+ | Content | Shiki, Twoslash, code groups, code copy, containers, GitHub alerts |
104
+ | Discovery | Lazy local search and locale-aware navigation |
105
+ | AI consumption | Page `.md`, `llms.txt`, `llms-full.txt`, copy actions |
106
+ | Styling | UnoCSS integration with sensible nagi defaults |
107
+
108
+ 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.
109
+
110
+ ## Extension Model
111
+
112
+ KawaPress keeps extension boundaries explicit:
113
+
114
+ - a **Generator Plugin** extends configuration, Markdown, page data, Vite, and build artifacts;
115
+ - a **Runtime Plugin** extends the real Vue App and Vue Router in both SSR and the browser;
116
+ - a **Preset** combines configuration and plugins into a ready-to-use experience such as nagi.
117
+
118
+ 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).
119
+
120
+ ## Documentation
121
+
122
+ - [Getting Started](https://shenqingchuan.github.io/kawapress/en/guide/getting-started)
123
+ - [What is KawaPress?](https://shenqingchuan.github.io/kawapress/en/guide/what-is-kawapress)
124
+ - [Markdown Extensions](https://shenqingchuan.github.io/kawapress/en/guide/markdown-extensions)
125
+ - [Internationalization](https://shenqingchuan.github.io/kawapress/en/guide/internationalization)
126
+ - [Plugin System](https://shenqingchuan.github.io/kawapress/en/guide/plugin-system)
127
+ - [Theme Customization](https://shenqingchuan.github.io/kawapress/en/guide/theme-customization)
128
+
129
+ ## Contributing
130
+
131
+ Issues and pull requests are welcome. For a large feature, please open an issue first so the direction can be agreed on before implementation.
132
+
133
+ ```sh
134
+ pnpm install
135
+ pnpm lint
136
+ pnpm typecheck
137
+ pnpm test
138
+ pnpm build
139
+ ```
140
+
141
+ KawaPress uses Node.js 22.12 or newer and pnpm 11.22.0 for repository development.
142
+
143
+ ## License
144
+
145
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress contributors
@@ -0,0 +1,145 @@
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/beta?label=npm%20beta&color=42b883" alt="npm beta 版本"></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
+ > [!IMPORTANT]
32
+ > KawaPress 目前处于 beta 阶段,适合试用和早期项目。0.1.0 之前,公开 API 仍可能调整;现阶段使用时请固定具体版本。
33
+
34
+ ## 为什么选择 KawaPress?
35
+
36
+ KawaPress 会把 Markdown 编译成预渲染的 Vue 网站。它保留了文档生成器简单、轻快的写作方式,同时让官方主题和第三方扩展使用完全相同的公开能力。
37
+
38
+ - **开发时也执行真实 SSR**:每次首次请求都会在服务端渲染。只在 SSR 中出现的问题,不必等到构建或上线后才发现。
39
+ - **默认体验完整**:内置 nagi(凪)预设,包含响应式文档布局、深浅色模式、本地搜索、代码高亮、Twoslash、代码组和多语言导航等常用能力。
40
+ - **从头到尾使用 Vue**:Markdown 会变成 Vue 组件,页面跳转交给 Vue Router;需要交互时,也可以自然地使用普通 Vue SFC。
41
+ - **面向 AI 的文档产物**:nagi 默认生成每页 `.md`、各语言的 `llms.txt` 与 `llms-full.txt`,并提供复制正文和链接的操作。
42
+ - **统一的扩展模型**:Generator Plugin、Runtime Plugin 与 Preset 分别覆盖生成阶段、Vue 运行时和能力组合,不依赖主题私有入口。
43
+
44
+ KawaPress 是一个独立项目,不是 VitePress 的分支或配置兼容层,也不能直接使用 VitePress 配置。
45
+
46
+ ## 快速开始
47
+
48
+ 请先准备 [Node.js](https://nodejs.org/) 22.12 或更高版本。
49
+
50
+ ```sh
51
+ mkdir my-kawapress-site
52
+ cd my-kawapress-site
53
+ pnpm init
54
+ pnpm add --save-dev kawapress
55
+ ```
56
+
57
+ 创建 `kawapress.config.ts`:
58
+
59
+ ```ts
60
+ import { nagi } from 'kawapress/nagi'
61
+
62
+ export default nagi({
63
+ title: 'My Docs',
64
+ })
65
+ ```
66
+
67
+ 创建 `index.md`:
68
+
69
+ ```md
70
+ ---
71
+ layout: home
72
+ title: My Docs
73
+ ---
74
+
75
+ # My Docs
76
+
77
+ 欢迎来到我的 KawaPress 站点。
78
+ ```
79
+
80
+ 启动开发服务器:
81
+
82
+ ```sh
83
+ pnpm exec kawapress dev
84
+ ```
85
+
86
+ 构建静态文件到 `dist`:
87
+
88
+ ```sh
89
+ pnpm exec kawapress build
90
+ ```
91
+
92
+ 部署产物是普通静态文件,不需要在服务器上继续运行 Node.js。npm 和 Yarn 的完整命令可以查看[快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)。
93
+
94
+ > 如果站点会直接导入 Vue API 或 Vue 组件,还需要把 `vue` 安装为开发依赖。
95
+
96
+ ## 默认包含什么?
97
+
98
+ | 范围 | 内置能力 |
99
+ | --- | --- |
100
+ | 内容编写 | Markdown、Frontmatter、在 Markdown 中使用 Vue、文件路由、Data Loader |
101
+ | 渲染 | 开发与构建共享 SSR 语义、Hydration、Vue Router 站内导航 |
102
+ | 文档界面 | nagi 布局、响应式 Sidebar、本页目录、深浅色模式、多语言 |
103
+ | 内容增强 | Shiki、Twoslash、代码组、代码复制、提示容器、GitHub Alerts |
104
+ | 内容发现 | 按需加载的本地搜索与多语言导航 |
105
+ | AI 读取 | 页面 `.md`、`llms.txt`、`llms-full.txt`、页面复制操作 |
106
+ | 样式 | UnoCSS 集成与 nagi 默认配置 |
107
+
108
+ `kawapress` 已经包含 nagi 和它使用的官方插件。普通文档站只需要安装这一个包;需要自行组合能力时,也可以直接使用独立的 `@kawapress/*` 包。
109
+
110
+ ## 扩展模型
111
+
112
+ KawaPress 把扩展边界分得很清楚:
113
+
114
+ - **Generator Plugin** 负责配置、Markdown、页面数据、Vite 与构建产物;
115
+ - **Runtime Plugin** 在 SSR 和浏览器中扩展真实的 Vue App 与 Vue Router;
116
+ - **Preset** 把配置和一组插件组合成可以直接使用的产品体验,例如 nagi。
117
+
118
+ 一个逻辑插件只需要安装一次,同时可以提供生成侧和运行侧能力。更多内容请查看[插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)。
119
+
120
+ ## 文档
121
+
122
+ - [快速开始](https://shenqingchuan.github.io/kawapress/guide/getting-started)
123
+ - [KawaPress 是什么?](https://shenqingchuan.github.io/kawapress/guide/what-is-kawapress)
124
+ - [Markdown 语法扩展](https://shenqingchuan.github.io/kawapress/guide/markdown-extensions)
125
+ - [国际化](https://shenqingchuan.github.io/kawapress/guide/internationalization)
126
+ - [插件体系](https://shenqingchuan.github.io/kawapress/guide/plugin-system)
127
+ - [主题定制](https://shenqingchuan.github.io/kawapress/guide/theme-customization)
128
+
129
+ ## 参与贡献
130
+
131
+ 欢迎提交 Issue 和 Pull Request。如果准备增加较大的功能,请先创建 Issue,把目标和方案聊清楚后再开始实现。
132
+
133
+ ```sh
134
+ pnpm install
135
+ pnpm lint
136
+ pnpm typecheck
137
+ pnpm test
138
+ pnpm build
139
+ ```
140
+
141
+ KawaPress 仓库使用 Node.js 22.12 或更高版本,以及 pnpm 11.22.0 进行开发。
142
+
143
+ ## 开源许可
144
+
145
+ [MIT](https://github.com/ShenQingchuan/kawapress/blob/main/LICENSE) © KawaPress 贡献者
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@kawapress/plugin-code-block",
3
+ "type": "module",
4
+ "version": "0.0.1-beta.1",
5
+ "description": "Language labels, copy controls, and line numbers for KawaPress code blocks",
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-code-block"
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"
31
+ ],
32
+ "engines": {
33
+ "node": ">=22.12.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org/"
38
+ },
39
+ "peerDependencies": {
40
+ "kawapress": "0.0.1-beta.1"
41
+ },
42
+ "devDependencies": {
43
+ "happy-dom": "^20.11.6",
44
+ "markdown-exit": "^1.3.0"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,307 @@
1
+ import type {
2
+ KawaPressPlugin,
3
+ LocaleConfig,
4
+ } from 'kawapress'
5
+ import type { MarkdownExit } from 'markdown-exit'
6
+ import { definePlugin } from 'kawapress'
7
+
8
+ export interface CodeBlockCopyLabels {
9
+ copy: string
10
+ copied: string
11
+ }
12
+
13
+ export interface CodeBlockPluginOptions {
14
+ /** Show line numbers unless a fence opts out with `:no-line-numbers`. */
15
+ lineNumbers?: boolean
16
+ /** Override visible labels for language identifiers. */
17
+ languageLabels?: Record<string, string>
18
+ /** Override copy feedback for every locale. */
19
+ copyLabels?: Partial<CodeBlockCopyLabels>
20
+ /** Override copy feedback for one KawaPress locale key. */
21
+ localeCopyLabels?: Record<string, Partial<CodeBlockCopyLabels>>
22
+ }
23
+
24
+ interface CodeBlockRenderEnv {
25
+ path?: string
26
+ }
27
+
28
+ interface InstallCodeBlockOptions extends CodeBlockPluginOptions {
29
+ resolveCopyLabels?: (env: CodeBlockRenderEnv) => CodeBlockCopyLabels
30
+ }
31
+
32
+ interface FenceInfo {
33
+ language: string
34
+ normalized: string
35
+ lineNumbers: boolean
36
+ startLine: number
37
+ }
38
+
39
+ interface RenderedLineNumbers {
40
+ digits: number
41
+ html: string
42
+ }
43
+
44
+ const ENGLISH_COPY_LABELS: CodeBlockCopyLabels = {
45
+ copy: 'Copy code',
46
+ copied: 'Copied',
47
+ }
48
+
49
+ const CHINESE_COPY_LABELS: CodeBlockCopyLabels = {
50
+ copy: '复制代码',
51
+ copied: '已复制',
52
+ }
53
+
54
+ const DEFAULT_LANGUAGE_LABELS: Record<string, string> = {
55
+ bash: 'Bash',
56
+ css: 'CSS',
57
+ diff: 'Diff',
58
+ html: 'HTML',
59
+ javascript: 'JavaScript',
60
+ js: 'JavaScript',
61
+ json: 'JSON',
62
+ jsx: 'JSX',
63
+ markdown: 'Markdown',
64
+ md: 'Markdown',
65
+ plaintext: 'Text',
66
+ shell: 'Shell',
67
+ sh: 'Shell',
68
+ text: 'Text',
69
+ ts: 'TypeScript',
70
+ tsx: 'TSX',
71
+ typescript: 'TypeScript',
72
+ txt: 'Text',
73
+ vue: 'Vue',
74
+ yaml: 'YAML',
75
+ yml: 'YAML',
76
+ }
77
+
78
+ const DEFAULT_LOCALES: Record<string, LocaleConfig> = {
79
+ root: {
80
+ label: 'English',
81
+ lang: 'en',
82
+ },
83
+ }
84
+
85
+ const ATTACHED_LINE_NUMBER_DIRECTIVES_RE
86
+ = /^([\w-]+)((?::(?:no-)?line-numbers(?:=\d+)?)+)(?=\s|$)/
87
+ const LINE_NUMBER_DIRECTIVE_RE = /^:(no-)?line-numbers(?:=(\d+))?$/
88
+ const LINE_NUMBER_DIRECTIVES_RE = /:(no-)?line-numbers(?:=(\d+))?/g
89
+ const STANDALONE_LINE_NUMBER_DIRECTIVE_RE
90
+ = /(^|[\t ])(:(?:no-)?line-numbers(?:=\d+)?)(?=$|[\t ])/g
91
+
92
+ export function codeBlockPlugin(
93
+ options: CodeBlockPluginOptions = {},
94
+ ): KawaPressPlugin {
95
+ let locales = DEFAULT_LOCALES
96
+
97
+ return definePlugin({
98
+ name: '@kawapress/plugin-code-block',
99
+ setup(api) {
100
+ api.config((config) => {
101
+ locales = config.locales ?? DEFAULT_LOCALES
102
+ })
103
+ api.markdown((markdown) => {
104
+ installCodeBlocks(markdown, {
105
+ ...options,
106
+ resolveCopyLabels: env => resolveCopyLabels(
107
+ env.path ?? '/',
108
+ locales,
109
+ options,
110
+ ),
111
+ })
112
+ })
113
+ },
114
+ })
115
+ }
116
+
117
+ export default codeBlockPlugin
118
+
119
+ export function installCodeBlocks(
120
+ markdown: MarkdownExit,
121
+ options: InstallCodeBlockOptions = {},
122
+ ): void {
123
+ const renderFence = markdown.renderer.rules.fence
124
+ const languageLabels = new Map([
125
+ ...Object.entries(DEFAULT_LANGUAGE_LABELS),
126
+ ...Object.entries(normalizeLanguageLabels(options.languageLabels)),
127
+ ])
128
+
129
+ markdown.renderer.rules.fence = (tokens, index, renderOptions, env, renderer) => {
130
+ const token = tokens[index]
131
+ const originalInfo = token.info
132
+ const info = parseFenceInfo(originalInfo, options.lineNumbers ?? false)
133
+ token.info = info.normalized
134
+
135
+ let rendered: string | Promise<string>
136
+ try {
137
+ rendered = renderFence
138
+ ? renderFence(tokens, index, renderOptions, env, renderer)
139
+ : renderer.renderToken(tokens, index, renderOptions)
140
+ }
141
+ catch (error) {
142
+ token.info = originalInfo
143
+ throw error
144
+ }
145
+
146
+ const copyLabels = options.resolveCopyLabels?.(env as CodeBlockRenderEnv) ?? ENGLISH_COPY_LABELS
147
+ const wrap = (html: string): string => renderCodeBlock(
148
+ html,
149
+ token.content,
150
+ info,
151
+ copyLabels,
152
+ languageLabels,
153
+ )
154
+ if (typeof rendered === 'string') {
155
+ token.info = originalInfo
156
+ return wrap(rendered)
157
+ }
158
+ return rendered
159
+ .then(wrap)
160
+ .finally(() => {
161
+ token.info = originalInfo
162
+ })
163
+ }
164
+ }
165
+
166
+ function renderCodeBlock(
167
+ rendered: string,
168
+ source: string,
169
+ info: FenceInfo,
170
+ labels: CodeBlockCopyLabels,
171
+ languageLabels: Map<string, string>,
172
+ ): string {
173
+ const languageId = info.language || 'text'
174
+ const languageLabel = languageLabels.get(languageId) ?? languageId
175
+ const lineNumbers = info.lineNumbers
176
+ ? renderLineNumbers(rendered, source, info.startLine)
177
+ : undefined
178
+ const modeClass = info.lineNumbers ? ' kawa-code-block--line-numbers' : ''
179
+ const lineNumberStyle = lineNumbers
180
+ ? ` style="--kawa-code-block-line-number-digits:${lineNumbers.digits}"`
181
+ : ''
182
+
183
+ return `<div class="kawa-code-block language-${escapeAttribute(languageId)}${modeClass}" data-language="${escapeAttribute(languageId)}"${lineNumberStyle}><span class="kawa-code-block__language">${escapeHtml(languageLabel)}</span><button class="kawa-code-block__copy" type="button" aria-label="${escapeAttribute(labels.copy)}" title="${escapeAttribute(labels.copy)}" data-copy-label="${escapeAttribute(labels.copy)}" data-copied-label="${escapeAttribute(labels.copied)}"><span class="kawa-code-block__copy-status" aria-live="polite"></span></button><div class="kawa-code-block__body">${rendered}${lineNumbers?.html ?? ''}</div></div>\n`
184
+ }
185
+
186
+ function parseFenceInfo(info: string, defaultLineNumbers: boolean): FenceInfo {
187
+ let lineNumbers = defaultLineNumbers
188
+ let startLine = 1
189
+
190
+ const applyDirective = (directive: string): void => {
191
+ const match = directive.match(LINE_NUMBER_DIRECTIVE_RE)
192
+ if (!match) {
193
+ return
194
+ }
195
+ lineNumbers = !match[1]
196
+ if (lineNumbers && match[2]) {
197
+ startLine = Number.parseInt(match[2], 10)
198
+ }
199
+ }
200
+
201
+ let normalized = info
202
+ const attached = normalized.match(ATTACHED_LINE_NUMBER_DIRECTIVES_RE)
203
+ if (attached) {
204
+ for (const match of attached[2].matchAll(LINE_NUMBER_DIRECTIVES_RE)) {
205
+ applyDirective(match[0])
206
+ }
207
+ normalized = attached[1] + normalized.slice(attached[0].length)
208
+ }
209
+ normalized = normalized.replace(
210
+ STANDALONE_LINE_NUMBER_DIRECTIVE_RE,
211
+ (_full, _spacing: string, directive: string) => {
212
+ applyDirective(directive)
213
+ return ''
214
+ },
215
+ ).trim()
216
+
217
+ return {
218
+ language: normalized.match(/^[\w-]+/)?.[0]?.toLowerCase() ?? '',
219
+ normalized,
220
+ lineNumbers,
221
+ startLine,
222
+ }
223
+ }
224
+
225
+ function renderLineNumbers(
226
+ rendered: string,
227
+ source: string,
228
+ startLine: number,
229
+ ): RenderedLineNumbers {
230
+ const code = source.replace(/\r?\n$/, '')
231
+ const lineCount = getRenderedLineCount(rendered)
232
+ ?? code.split(/\r?\n/).length
233
+ const lastLine = startLine + lineCount - 1
234
+ const lines = Array.from({ length: lineCount }, (_, index) => (
235
+ `<span class="kawa-code-block__line-number">${startLine + index}</span>`
236
+ )).join('')
237
+ return {
238
+ digits: Math.max(String(startLine).length, String(lastLine).length),
239
+ html: `<div class="kawa-code-block__line-numbers" aria-hidden="true">${lines}</div>`,
240
+ }
241
+ }
242
+
243
+ function getRenderedLineCount(rendered: string): number | undefined {
244
+ const match = rendered.match(
245
+ /\bdata-kawa-line-count=(?:"(\d+)"|'(\d+)')/,
246
+ )
247
+ if (!match) {
248
+ return
249
+ }
250
+ const count = Number.parseInt(match[1] ?? match[2], 10)
251
+ return count > 0 ? count : undefined
252
+ }
253
+
254
+ function resolveCopyLabels(
255
+ path: string,
256
+ locales: Record<string, LocaleConfig>,
257
+ options: CodeBlockPluginOptions,
258
+ ): CodeBlockCopyLabels {
259
+ const localeIndex = resolveLocaleIndex(path, locales)
260
+ const language = locales[localeIndex]?.lang
261
+ const builtIn = language?.toLowerCase().startsWith('zh')
262
+ ? CHINESE_COPY_LABELS
263
+ : ENGLISH_COPY_LABELS
264
+
265
+ return {
266
+ ...builtIn,
267
+ ...options.copyLabels,
268
+ ...options.localeCopyLabels?.[localeIndex],
269
+ }
270
+ }
271
+
272
+ function resolveLocaleIndex(
273
+ path: string,
274
+ locales: Record<string, LocaleConfig>,
275
+ ): string {
276
+ const pathname = path.replace(/([?#].*)$/, '')
277
+ return Object.keys(locales)
278
+ .filter(locale => locale !== 'root')
279
+ .sort((left, right) => right.length - left.length)
280
+ .find((locale) => {
281
+ const prefix = `/${locale}`
282
+ return pathname === prefix || pathname.startsWith(`${prefix}/`)
283
+ }) ?? 'root'
284
+ }
285
+
286
+ function normalizeLanguageLabels(
287
+ labels: Record<string, string> | undefined,
288
+ ): Record<string, string> {
289
+ return Object.fromEntries(
290
+ Object.entries(labels ?? {}).map(([language, label]) => (
291
+ [language.toLowerCase(), label]
292
+ )),
293
+ )
294
+ }
295
+
296
+ function escapeHtml(value: string): string {
297
+ return value
298
+ .replaceAll('&', '&amp;')
299
+ .replaceAll('<', '&lt;')
300
+ .replaceAll('>', '&gt;')
301
+ }
302
+
303
+ function escapeAttribute(value: string): string {
304
+ return escapeHtml(value)
305
+ .replaceAll('"', '&quot;')
306
+ .replaceAll('\'', '&#39;')
307
+ }
@@ -0,0 +1,125 @@
1
+ import { defineRuntimePlugin } from 'kawapress'
2
+
3
+ const COPY_BUTTON_SELECTOR = '.kawa-code-block__copy'
4
+ const COPY_IGNORE_SELECTOR = '.kawa-code-block__copy-ignore, .diff.remove'
5
+ const copiedTimeouts = new WeakMap<HTMLButtonElement, number>()
6
+ let installed = false
7
+
8
+ export default defineRuntimePlugin({
9
+ name: '@kawapress/plugin-code-block',
10
+ setup(api) {
11
+ api.vueApp(() => {
12
+ if (!import.meta.env.SSR) {
13
+ installCodeBlockCopyHandler()
14
+ }
15
+ })
16
+ },
17
+ })
18
+
19
+ export function installCodeBlockCopyHandler(): void {
20
+ if (installed) {
21
+ return
22
+ }
23
+ installed = true
24
+ document.addEventListener('click', (event) => {
25
+ const target = event.target
26
+ if (!(target instanceof Element)) {
27
+ return
28
+ }
29
+ const button = target.closest<HTMLButtonElement>(COPY_BUTTON_SELECTOR)
30
+ if (!button) {
31
+ return
32
+ }
33
+ const code = button
34
+ .closest<HTMLElement>('.kawa-code-block')
35
+ ?.querySelector<HTMLElement>('pre code')
36
+ if (!code) {
37
+ return
38
+ }
39
+
40
+ void copyText(readCodeText(code))
41
+ .then(() => {
42
+ showCopiedFeedback(button)
43
+ })
44
+ .catch(() => {})
45
+ })
46
+ }
47
+
48
+ export function readCodeText(code: HTMLElement): string {
49
+ const clone = code.cloneNode(true) as HTMLElement
50
+ const lines = [...clone.children]
51
+ .filter(element => element.classList.contains('line'))
52
+ if (lines.length > 0) {
53
+ return lines
54
+ .filter(line => !line.matches(COPY_IGNORE_SELECTOR))
55
+ .map((line) => {
56
+ const copy = line.cloneNode(true) as HTMLElement
57
+ copy.querySelectorAll(COPY_IGNORE_SELECTOR).forEach(node => node.remove())
58
+ return copy.textContent ?? ''
59
+ })
60
+ .join('\n')
61
+ }
62
+
63
+ clone.querySelectorAll(COPY_IGNORE_SELECTOR).forEach(node => node.remove())
64
+ return (clone.textContent ?? '').replace(/\n$/, '')
65
+ }
66
+
67
+ function showCopiedFeedback(button: HTMLButtonElement): void {
68
+ const copiedLabel = button.dataset.copiedLabel ?? 'Copied'
69
+ const copyLabel = button.dataset.copyLabel ?? 'Copy code'
70
+ const status = button.querySelector<HTMLElement>('.kawa-code-block__copy-status')
71
+
72
+ button.dataset.copied = 'true'
73
+ button.ariaLabel = copiedLabel
74
+ button.title = copiedLabel
75
+ if (status) {
76
+ status.textContent = copiedLabel
77
+ }
78
+ window.clearTimeout(copiedTimeouts.get(button))
79
+ copiedTimeouts.set(button, window.setTimeout(() => {
80
+ delete button.dataset.copied
81
+ button.ariaLabel = copyLabel
82
+ button.title = copyLabel
83
+ if (status) {
84
+ status.textContent = ''
85
+ }
86
+ copiedTimeouts.delete(button)
87
+ }, 2000))
88
+ }
89
+
90
+ async function copyText(text: string): Promise<void> {
91
+ try {
92
+ await navigator.clipboard.writeText(text)
93
+ }
94
+ catch {
95
+ const textarea = document.createElement('textarea')
96
+ const focused = document.activeElement as HTMLElement | null
97
+ const selection = document.getSelection()
98
+ const range = selection?.rangeCount ? selection.getRangeAt(0) : null
99
+
100
+ textarea.value = text
101
+ textarea.readOnly = true
102
+ textarea.style.position = 'fixed'
103
+ textarea.style.inset = '0 auto auto -9999px'
104
+ textarea.style.fontSize = '12pt'
105
+ let copied = false
106
+ try {
107
+ document.body.appendChild(textarea)
108
+ textarea.select()
109
+ textarea.selectionStart = 0
110
+ textarea.selectionEnd = text.length
111
+ copied = document.execCommand('copy')
112
+ }
113
+ finally {
114
+ textarea.remove()
115
+ if (range && selection) {
116
+ selection.removeAllRanges()
117
+ selection.addRange(range)
118
+ }
119
+ focused?.focus()
120
+ }
121
+ if (!copied) {
122
+ throw new Error('Unable to copy code to the clipboard.')
123
+ }
124
+ }
125
+ }