@kawapress/plugin-toc 0.0.0-stage → 0.4.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.
@@ -0,0 +1,58 @@
1
+ # @kawapress/plugin-toc
2
+
3
+ 为 KawaPress 页面提供 `[[toc]]` 页内目录。
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@kawapress/plugin-toc?label=npm&color=42b883)](https://www.npmjs.com/package/@kawapress/plugin-toc) · [English](https://github.com/kawapress/kawapress/blob/main/packages/plugin-toc/README.md)
6
+
7
+ `@kawapress/plugin-toc` 是 [KawaPress](https://github.com/kawapress/kawapress) 的一部分。KawaPress 是一个以 Vue 为核心的静态站点生成器。
8
+
9
+ ## 特性
10
+
11
+ - 把单独一行的 `[[toc]]`(不区分大小写)替换成 `<nav class="kawa-toc">` 包裹的嵌套章节列表。
12
+ - 默认收录页面顶层的 `h2` 和 `h3` 标题,不收录容器或引用块内部的标题。
13
+ - 链接指向标题的最终锚点 ID(包含 `{#id}` 自定义锚点),文字与右侧大纲和搜索索引保持一致。
14
+
15
+ ## 安装
16
+
17
+ 这个包已经包含在 `kawapress` 里。使用 `kawapress/nagi` 的站点自带它,不需要再安装。
18
+
19
+ 只有不使用 nagi 预设搭建站点,或需要自定义收录的标题级别时,才需要单独安装它。
20
+
21
+ ```sh
22
+ npm install --save-dev @kawapress/plugin-toc
23
+ ```
24
+
25
+ 也可以用 `pnpm add --save-dev @kawapress/plugin-toc` 或 `yarn add --dev @kawapress/plugin-toc`。
26
+
27
+ ## 使用
28
+
29
+ ```md
30
+ [[toc]]
31
+ ```
32
+
33
+ ```ts
34
+ import tocPlugin from '@kawapress/plugin-toc'
35
+ import { defineConfig } from 'kawapress'
36
+
37
+ export default defineConfig({
38
+ plugins: [
39
+ tocPlugin({
40
+ level: [2, 3],
41
+ }),
42
+ ],
43
+ })
44
+ ```
45
+
46
+ ## 配置项
47
+
48
+ | 选项 | 说明 |
49
+ | --- | --- |
50
+ | `level` | 收录的标题级别,默认 `[2, 3]`。 |
51
+
52
+ ## 文档
53
+
54
+ [文档](https://kawapress.dev/guide/markdown-extensions#table-of-contents) · [反馈问题](https://github.com/kawapress/kawapress/issues)
55
+
56
+ ## 许可证
57
+
58
+ [MIT](https://github.com/kawapress/kawapress/blob/main/LICENSE) © KawaPress contributors
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @kawapress/plugin-toc
2
2
 
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.
3
+ `[[toc]]` table of contents for KawaPress pages.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@kawapress/plugin-toc?label=npm&color=42b883)](https://www.npmjs.com/package/@kawapress/plugin-toc) · [简体中文](https://github.com/kawapress/kawapress/blob/main/packages/plugin-toc/README-zh-CN.md)
6
+
7
+ `@kawapress/plugin-toc` is part of [KawaPress](https://github.com/kawapress/kawapress), a Vue-first static site generator.
8
+
9
+ ## Features
10
+
11
+ - Turns a line that holds only `[[toc]]` (case-insensitive) into a nested `<nav class="kawa-toc">` list of the page's headings.
12
+ - Lists `h2` and `h3` top-level headings by default; headings inside containers or blockquotes are excluded.
13
+ - Uses the final heading anchor IDs (including custom `{#id}` anchors) and the same plain-text heading titles as the outline and search index.
14
+
15
+ ## Install
16
+
17
+ This package is already included in `kawapress`. A site that uses `kawapress/nagi` has it, so there is nothing to install.
18
+
19
+ Install it yourself only when you build a site without the nagi preset or when you want to configure custom heading levels.
20
+
21
+ ```sh
22
+ npm install --save-dev @kawapress/plugin-toc
23
+ ```
24
+
25
+ `pnpm add --save-dev @kawapress/plugin-toc` and `yarn add --dev @kawapress/plugin-toc` work too.
26
+
27
+ ## Usage
28
+
29
+ ```md
30
+ [[toc]]
31
+ ```
32
+
33
+ ```ts
34
+ import tocPlugin from '@kawapress/plugin-toc'
35
+ import { defineConfig } from 'kawapress'
36
+
37
+ export default defineConfig({
38
+ plugins: [
39
+ tocPlugin({
40
+ level: [2, 3],
41
+ }),
42
+ ],
43
+ })
44
+ ```
45
+
46
+ ## Options
47
+
48
+ | Option | Description |
49
+ | --- | --- |
50
+ | `level` | Heading levels the table lists. Default `[2, 3]`. |
51
+
52
+ ## Documentation
53
+
54
+ [Documentation](https://kawapress.dev/en/guide/markdown-extensions#table-of-contents) · [Report a problem](https://github.com/kawapress/kawapress/issues)
55
+
56
+ ## License
57
+
58
+ [MIT](https://github.com/kawapress/kawapress/blob/main/LICENSE) © KawaPress contributors
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@kawapress/plugin-toc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.4.0",
5
+ "description": "[[toc]] table of contents for KawaPress pages",
6
+ "license": "MIT",
7
+ "homepage": "https://kawapress.dev/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kawapress/kawapress.git",
11
+ "directory": "packages/plugin-toc"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/kawapress/kawapress/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.ts",
19
+ "import": "./src/index.ts",
20
+ "default": "./src/index.ts"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "README-zh-CN.md",
26
+ "src/**/!(*.test.*)"
27
+ ],
28
+ "engines": {
29
+ "node": ">=22.12.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org/"
34
+ },
35
+ "peerDependencies": {
36
+ "kawapress": "^0.4.0"
37
+ },
38
+ "dependencies": {
39
+ "markdown-exit": "^1.3.0"
40
+ },
41
+ "devDependencies": {
42
+ "@mdit/plugin-attrs": "1.1.1",
43
+ "markdown-it-anchor": "^9.2.0"
44
+ }
6
45
  }
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { KawaPressPlugin } from 'kawapress'
2
+ import type { TocOptions } from './toc'
3
+ import { definePlugin } from 'kawapress'
4
+ import { installToc } from './toc'
5
+
6
+ export type TocPluginOptions = TocOptions
7
+
8
+ /**
9
+ * Turns a line that only holds `[[toc]]` into a table of contents of the page,
10
+ * the same syntax as VitePress.
11
+ */
12
+ export function tocPlugin(options: TocPluginOptions = {}): KawaPressPlugin {
13
+ return definePlugin({
14
+ name: '@kawapress/plugin-toc',
15
+ setup(api) {
16
+ api.markdown((markdown) => {
17
+ installToc(markdown, options)
18
+ })
19
+ },
20
+ })
21
+ }
22
+
23
+ export default tocPlugin
24
+
25
+ export { installToc, TOC_MARKER_RE } from './toc'
26
+ export type { TocOptions } from './toc'
package/src/toc.ts ADDED
@@ -0,0 +1,112 @@
1
+ import type { MarkdownExit, RuleBlock, Token } from 'markdown-exit'
2
+ import { resolveHeadingTitle } from 'kawapress'
3
+
4
+ export interface TocOptions {
5
+ /**
6
+ * Heading levels the table lists.
7
+ * @default [2, 3]
8
+ */
9
+ level?: number[]
10
+ }
11
+
12
+ interface TocEntry {
13
+ level: number
14
+ id: string
15
+ title: string
16
+ children: TocEntry[]
17
+ }
18
+
19
+ /** A line that holds only the marker, in any letter case. */
20
+ export const TOC_MARKER_RE = /^\[\[toc\]\]$/i
21
+
22
+ const TOC_TOKEN = 'kawa_toc'
23
+
24
+ const tocBlockRule: RuleBlock = (state, startLine, _endLine, silent) => {
25
+ // Four spaces of indent make an indented code block, not a marker.
26
+ if (state.sCount[startLine] - state.blkIndent >= 4) {
27
+ return false
28
+ }
29
+ const start = state.bMarks[startLine] + state.tShift[startLine]
30
+ const line = state.src.slice(start, state.eMarks[startLine]).trim()
31
+ if (!TOC_MARKER_RE.test(line)) {
32
+ return false
33
+ }
34
+ if (!silent) {
35
+ const token = state.push(TOC_TOKEN, 'nav', 0)
36
+ token.map = [startLine, startLine + 1]
37
+ token.markup = line
38
+ }
39
+ state.line = startLine + 1
40
+ return true
41
+ }
42
+
43
+ export function installToc(markdown: MarkdownExit, options: TocOptions = {}): void {
44
+ const levels = new Set(options.level ?? [2, 3])
45
+
46
+ markdown.block.ruler.before('paragraph', TOC_TOKEN, tocBlockRule)
47
+ markdown.renderer.rules[TOC_TOKEN] = (tokens) => {
48
+ const entries = nestEntries(collectEntries(tokens, levels))
49
+ return entries.length > 0
50
+ ? `<nav class="kawa-toc">${renderEntries(entries, markdown.utils.escapeHtml)}</nav>\n`
51
+ : ''
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Reads the headings at the top level of the page, so a heading inside a
57
+ * container or a block quote stays out of the table. The ID is the final
58
+ * anchor ID and the title follows the heading title rule of KawaPress, the
59
+ * same title the outline and the search index show.
60
+ */
61
+ function collectEntries(tokens: readonly Token[], levels: ReadonlySet<number>): TocEntry[] {
62
+ const entries: TocEntry[] = []
63
+
64
+ for (const [index, token] of tokens.entries()) {
65
+ if (token.type !== 'heading_open' || token.level !== 0) {
66
+ continue
67
+ }
68
+ const level = Number.parseInt(token.tag.slice(1), 10)
69
+ const id = token.attrGet('id')
70
+ const inline = tokens[index + 1]
71
+ if (!levels.has(level) || !id || inline?.type !== 'inline') {
72
+ continue
73
+ }
74
+ const title = resolveHeadingTitle(inline)
75
+ if (title) {
76
+ entries.push({ level, id, title, children: [] })
77
+ }
78
+ }
79
+
80
+ return entries
81
+ }
82
+
83
+ /** Puts each heading under the closest earlier heading of a higher level. */
84
+ function nestEntries(entries: TocEntry[]): TocEntry[] {
85
+ const root: TocEntry[] = []
86
+ const stack: TocEntry[] = []
87
+
88
+ for (const entry of entries) {
89
+ while (stack.length > 0 && stack.at(-1)!.level >= entry.level) {
90
+ stack.pop()
91
+ }
92
+ const parent = stack.at(-1)
93
+ if (parent) {
94
+ parent.children.push(entry)
95
+ }
96
+ else {
97
+ root.push(entry)
98
+ }
99
+ stack.push(entry)
100
+ }
101
+
102
+ return root
103
+ }
104
+
105
+ function renderEntries(entries: readonly TocEntry[], escapeHtml: (text: string) => string): string {
106
+ const items = entries.map((entry) => {
107
+ const link = `<a href="#${escapeHtml(entry.id)}">${escapeHtml(entry.title)}</a>`
108
+ const children = entry.children.length > 0 ? renderEntries(entry.children, escapeHtml) : ''
109
+ return `<li>${link}${children}</li>`
110
+ })
111
+ return `<ul>${items.join('')}</ul>`
112
+ }