@md-plugins/md-plugin-headers 0.1.0-alpha.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.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024-present, Jeff Galbraith
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # @md-plugins/md-plugin-headers
2
+
3
+ A **Markdown-It** plugin that extracts and processes headers from Markdown content. This plugin is ideal for generating Table of Contents (ToC) or managing headers for documentation and static sites.
4
+
5
+ **NOTE:** When using with `vue-router` be sure to use `history` mode and not `hash` mode otherwise your hash links will not work as expected.
6
+
7
+ ## Features
8
+
9
+ - Extracts headers based on specified levels (e.g., `h1`, `h2`, `h3`).
10
+ - Supports custom slugification for header IDs.
11
+ - Allows custom formatting for header titles.
12
+ - Provides nested structure for headers (e.g., hierarchical ToC generation).
13
+ - Compatible with Markdown-It environments for additional flexibility.
14
+
15
+ ## Installation
16
+
17
+ Install the plugin via your preferred package manager:
18
+
19
+ ```bash
20
+ # With npm:
21
+ npm install @md-plugins/md-plugin-headers
22
+ # Or with Yarn:
23
+ yarn add @md-plugins/md-plugin-headers
24
+ # Or with pnpm:
25
+ pnpm add @md-plugins/md-plugin-headers
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ### Basic Setup
31
+
32
+ ```js
33
+ import MarkdownIt from 'markdown-it';
34
+ import { headersPlugin } from '@md-plugins/md-plugin-headers';
35
+ import type { MarkdownItEnv } from '@md-plugins/shared';
36
+
37
+ const md = new MarkdownIt();
38
+ md.use(headersPlugin, {
39
+ level: [1, 2, 3], // Extract h1, h2, and h3 headers
40
+ slugify: (str) => str.toLowerCase().replace(/\s+/g, '-'),
41
+ format: (title) => title.toUpperCase(),
42
+ });
43
+
44
+ const markdownContent = `
45
+ # Header 1
46
+
47
+ ## Subheader 1.1
48
+
49
+ ### Subheader 1.1.1
50
+ `;
51
+
52
+ const env: MarkdownItEnv = {};
53
+ const renderedOutput = md.render(markdownContent, env);
54
+
55
+ console.log('Rendered Output:', renderedOutput);
56
+ console.log('Extracted Headers:', env.toc);
57
+ ```
58
+
59
+ ### Example Output
60
+
61
+ The plugin processes headers and stores them in the `toc` property of the Markdown-It environment (`env`):
62
+
63
+ ```json
64
+ [
65
+ {
66
+ "level": 1,
67
+ "title": "HEADER 1",
68
+ "id": "header-1",
69
+ "link": "#header-1",
70
+ "children": [
71
+ {
72
+ "level": 2,
73
+ "title": "SUBHEADER 1.1",
74
+ "id": "subheader-1-1",
75
+ "link": "#subheader-1-1",
76
+ "children": [
77
+ {
78
+ "level": 3,
79
+ "title": "SUBHEADER 1.1.1",
80
+ "id": "subheader-1-1-1",
81
+ "link": "#subheader-1-1-1",
82
+ "children": []
83
+ }
84
+ ]
85
+ }
86
+ ]
87
+ }
88
+ ]
89
+ ```
90
+
91
+ ## Options
92
+
93
+ The `md-plugin-headers` plugin supports the following options:
94
+
95
+ | Option | Type | Default | Description |
96
+ | ----------------- | -------- | ------------ | -------------------------------------------------------------------- |
97
+ | level | number[] | [2, 3] | Heading levels to extract (e.g., [2, 3] for h2, h3). |
98
+ | slugify | function | (str) => str | Function to generate slugs for header IDs. |
99
+ | format | function | (str) => str | Function to format header titles. |
100
+ | shouldAllowNested | boolean | false | Whether to allow headers inside nested blocks (e.g., lists, quotes). |
101
+
102
+ ## Advanced Usage
103
+
104
+ ### Generating a Table of Contents (ToC)
105
+
106
+ With the `toc` property in `env`, you can build a ToC dynamically:
107
+
108
+ ```js
109
+ function generateToC(toc) {
110
+ const list = toc
111
+ .map((item) => {
112
+ const children = item.children
113
+ ? `<ul>${generateToC(item.children)}</ul>`
114
+ : '';
115
+ return `<li><a href="${item.link}">${item.title}</a>${children}</li>`;
116
+ })
117
+ .join('');
118
+ return `<ul>${list}</ul>`;
119
+ }
120
+
121
+ const tocHtml = generateToC(env.toc);
122
+ console.log('Generated ToC:', tocHtml);
123
+ ```
124
+
125
+ ### Custom Slugify Function
126
+
127
+ You can use your own slugification logic for header IDs:
128
+
129
+ ```js
130
+ md.use(headersPlugin, {
131
+ slugify: (str) => encodeURIComponent(str.replace(/\s+/g, '_')),
132
+ });
133
+ ```
134
+
135
+ Whatever you use on the backend, should be the same logic on the frontend for slugification so that they match when using hash links.
136
+
137
+ ### Nested Headers
138
+
139
+ Enable nested headers to include headers inside blockquotes or lists:
140
+
141
+ ```js
142
+ md.use(headersPlugin, {
143
+ shouldAllowNested: true,
144
+ });
145
+ ```
146
+
147
+ ## Testing
148
+
149
+ ```bash
150
+ pnpm test
151
+ ```
152
+
153
+ ## License
154
+
155
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE.md) file for details.
@@ -0,0 +1,53 @@
1
+ import { PluginWithOptions } from 'markdown-it';
2
+
3
+ /**
4
+ * Options of md-plugin-headers
5
+ */
6
+ interface HeadersPluginOptions {
7
+ /**
8
+ * A custom slugification function
9
+ *
10
+ * Should use the same slugify function with markdown-it-anchor
11
+ * to ensure the link is matched
12
+ */
13
+ slugify?: (str: string) => string;
14
+ /**
15
+ * A function for formatting header title
16
+ */
17
+ format?: (str: string) => string;
18
+ /**
19
+ * Heading level that going to be extracted
20
+ *
21
+ * Should be a subset of markdown-it-anchor's `level` option
22
+ * to ensure the slug is existed
23
+ *
24
+ * @default [2,3]
25
+ */
26
+ level?: number[];
27
+ /**
28
+ * Should allow headers inside nested blocks or not
29
+ *
30
+ * If set to `true`, headers inside blockquote, list, etc. would also be extracted.
31
+ *
32
+ * @default false
33
+ */
34
+ shouldAllowNested?: boolean;
35
+ }
36
+ interface TocItem {
37
+ id: string;
38
+ title: string;
39
+ sub?: boolean;
40
+ deep?: boolean;
41
+ }
42
+ declare module '@md-plugins/shared' {
43
+ interface MarkdownItEnv {
44
+ /**
45
+ * The toc that are extracted by `md-plugin-headers`
46
+ */
47
+ toc?: TocItem[];
48
+ }
49
+ }
50
+
51
+ declare const headersPlugin: PluginWithOptions<HeadersPluginOptions>;
52
+
53
+ export { type HeadersPluginOptions, type TocItem, headersPlugin };
@@ -0,0 +1,53 @@
1
+ import { PluginWithOptions } from 'markdown-it';
2
+
3
+ /**
4
+ * Options of md-plugin-headers
5
+ */
6
+ interface HeadersPluginOptions {
7
+ /**
8
+ * A custom slugification function
9
+ *
10
+ * Should use the same slugify function with markdown-it-anchor
11
+ * to ensure the link is matched
12
+ */
13
+ slugify?: (str: string) => string;
14
+ /**
15
+ * A function for formatting header title
16
+ */
17
+ format?: (str: string) => string;
18
+ /**
19
+ * Heading level that going to be extracted
20
+ *
21
+ * Should be a subset of markdown-it-anchor's `level` option
22
+ * to ensure the slug is existed
23
+ *
24
+ * @default [2,3]
25
+ */
26
+ level?: number[];
27
+ /**
28
+ * Should allow headers inside nested blocks or not
29
+ *
30
+ * If set to `true`, headers inside blockquote, list, etc. would also be extracted.
31
+ *
32
+ * @default false
33
+ */
34
+ shouldAllowNested?: boolean;
35
+ }
36
+ interface TocItem {
37
+ id: string;
38
+ title: string;
39
+ sub?: boolean;
40
+ deep?: boolean;
41
+ }
42
+ declare module '@md-plugins/shared' {
43
+ interface MarkdownItEnv {
44
+ /**
45
+ * The toc that are extracted by `md-plugin-headers`
46
+ */
47
+ toc?: TocItem[];
48
+ }
49
+ }
50
+
51
+ declare const headersPlugin: PluginWithOptions<HeadersPluginOptions>;
52
+
53
+ export { type HeadersPluginOptions, type TocItem, headersPlugin };
package/dist/index.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import { slugify } from '@md-plugins/shared';
2
+
3
+ const titleRE = /<\/?[^>]+(>|$)/g;
4
+ const apiRE = /^<MarkdownApi /;
5
+ const apiNameRE = /(?:file|name)="([^"]+)"/;
6
+ const installationRE = /^<MarkdownInstallation(?:\s+title="([^"]*)")?\s*/;
7
+ const exampleRE = /^<MarkdownExample(?:\s+title="([^"]*)")?\s*/;
8
+ function parseContent(str, slugify$1 = slugify, format = (_str) => _str) {
9
+ const title = String(str).replace(titleRE, "").trim();
10
+ return {
11
+ id: slugify$1(title),
12
+ title: format(title) ?? title
13
+ };
14
+ }
15
+ const headersPlugin = (md, {
16
+ level = [2, 3],
17
+ slugify: slugify$1 = slugify,
18
+ format
19
+ } = {}) => {
20
+ const originalHeadingOpen = md.renderer.rules.heading_open;
21
+ const originalHtmlBlock = md.renderer.rules.html_block;
22
+ md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
23
+ const token = tokens[idx];
24
+ if (!token) {
25
+ return self.renderToken(tokens, idx, options);
26
+ }
27
+ const headerLevel = Number.parseInt(token.tag.slice(1), 10);
28
+ const contentToken = tokens[idx + 1];
29
+ const content = contentToken && contentToken.children ? contentToken.children.reduce((acc, t) => acc + t.content, "") : "";
30
+ const { id, title } = parseContent(content, slugify$1, format);
31
+ token.attrSet("id", id);
32
+ token.attrSet("class", `markdown-heading markdown-${token.tag}`);
33
+ token.attrSet("@click", `copyHeading(\`${id}\`)`);
34
+ env.toc = env.toc || [];
35
+ if (level.includes(headerLevel)) {
36
+ if (headerLevel === level[0]) {
37
+ env.toc.push({ id, title });
38
+ } else {
39
+ env.toc.push({ id, title, sub: true });
40
+ }
41
+ }
42
+ if (typeof originalHeadingOpen === "function") {
43
+ return originalHeadingOpen(tokens, idx, options, env, self);
44
+ }
45
+ return self.renderToken(tokens, idx, options);
46
+ };
47
+ md.renderer.rules.html_block = (tokens, idx, options, env, self) => {
48
+ const token = tokens[idx];
49
+ if (!token) {
50
+ return "";
51
+ }
52
+ env.toc = env.toc || [];
53
+ if (apiRE.test(token.content)) {
54
+ const match2 = apiNameRE.exec(token.content);
55
+ if (match2 !== null) {
56
+ const title = `${match2[1]} API`;
57
+ env.toc.push({ id: slugify$1(title), title, deep: true });
58
+ }
59
+ }
60
+ let match = token.content.match(installationRE);
61
+ if (match !== null) {
62
+ const title = match[1] ?? "Installation";
63
+ env.toc.push({ id: slugify$1(title), title, deep: true });
64
+ }
65
+ match = token.content.match(exampleRE);
66
+ if (match !== null) {
67
+ const title = match[1] ?? "Example";
68
+ env.toc.push({ id: slugify$1(title), title, deep: true });
69
+ }
70
+ if (typeof originalHtmlBlock === "function") {
71
+ return originalHtmlBlock(tokens, idx, options, env, self);
72
+ }
73
+ return token.content;
74
+ };
75
+ };
76
+
77
+ export { headersPlugin };
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@md-plugins/md-plugin-headers",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "A markdown-it plugin for handling headers (H1-H6).",
5
+ "keywords": [
6
+ "markdown-it",
7
+ "quasarframework",
8
+ "vue",
9
+ "types"
10
+ ],
11
+ "homepage": "https://github.com/md-plugins",
12
+ "bugs": {
13
+ "url": "https://github.com/md-plugins/md-plugins/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/md-plugins/md-plugins.git"
18
+ },
19
+ "license": "MIT",
20
+ "author": "hawkeye64 <galbraith64@gmail.com>",
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "import": {
25
+ "types": "./dist/index.d.mts",
26
+ "default": "./dist/index.mjs"
27
+ }
28
+ }
29
+ },
30
+ "module": "./dist/index.mjs",
31
+ "types": "./dist/index.d.ts",
32
+ "files": [
33
+ "./dist"
34
+ ],
35
+ "dependencies": {
36
+ "@types/markdown-it": "^14.1.2",
37
+ "markdown-it": "^14.1.0",
38
+ "@md-plugins/shared": "0.1.0-alpha.1"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "unbuild",
45
+ "clean": "rm -rf dist",
46
+ "test": "vitest"
47
+ }
48
+ }