remark-flexible-toc 1.2.8 → 1.3.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/README.md +57 -4
- package/dist/index.d.ts +10 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +46 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -118,6 +118,7 @@ Now, running both `node example.js` you will see that the same table of contents
|
|
|
118
118
|
```javascript
|
|
119
119
|
[
|
|
120
120
|
{
|
|
121
|
+
content: [{ type: "text", value: "Section" }],
|
|
121
122
|
depth: 2,
|
|
122
123
|
href: "#section",
|
|
123
124
|
numbering: [1, 1],
|
|
@@ -125,6 +126,7 @@ Now, running both `node example.js` you will see that the same table of contents
|
|
|
125
126
|
value: "Section",
|
|
126
127
|
},
|
|
127
128
|
{
|
|
129
|
+
content: [{ type: "text", value: "Subheading 1" }],
|
|
128
130
|
depth: 3,
|
|
129
131
|
href: "#subheading-1",
|
|
130
132
|
numbering: [1, 1, 1],
|
|
@@ -132,6 +134,7 @@ Now, running both `node example.js` you will see that the same table of contents
|
|
|
132
134
|
value: "Subheading 1",
|
|
133
135
|
},
|
|
134
136
|
{
|
|
137
|
+
content: [{ type: "text", value: "Subheading 2" }],
|
|
135
138
|
depth: 3,
|
|
136
139
|
href: "#subheading-2",
|
|
137
140
|
numbering: [1, 1, 2],
|
|
@@ -159,13 +162,15 @@ console.log(tocItems);
|
|
|
159
162
|
|
|
160
163
|
The function returns `TocItem[]` and does not modify the MDAST tree.
|
|
161
164
|
|
|
162
|
-
The available options are `maxDepth`, `skipLevels`, `skipParents`, `exclude`, and `
|
|
165
|
+
The available options are `maxDepth`, `skipLevels`, `includeParents`, `skipParents`, `exclude`, `prefix`, and `after`.
|
|
163
166
|
|
|
164
167
|
## Options
|
|
165
168
|
|
|
166
169
|
All options are **optional**.
|
|
167
170
|
|
|
168
171
|
```typescript
|
|
172
|
+
import type { Test } from "unist-util-is";
|
|
173
|
+
|
|
169
174
|
type HeadingParent =
|
|
170
175
|
| "root"
|
|
171
176
|
| "blockquote"
|
|
@@ -181,9 +186,11 @@ use(remarkFlexibleToc, {
|
|
|
181
186
|
tocRef?: TocItem[]; // default: []
|
|
182
187
|
maxDepth?: HeadingDepth; // default: 6
|
|
183
188
|
skipLevels?: HeadingDepth[]; // default: [1]
|
|
184
|
-
|
|
189
|
+
includeParents?: Test;
|
|
190
|
+
skipParents?: Test;
|
|
185
191
|
exclude?: string | string[];
|
|
186
192
|
prefix?: string;
|
|
193
|
+
after?: string;
|
|
187
194
|
callback?: (toc: TocItem[]) => undefined;
|
|
188
195
|
} as FlexibleTocOptions);
|
|
189
196
|
```
|
|
@@ -193,7 +200,13 @@ use(remarkFlexibleToc, {
|
|
|
193
200
|
```ts
|
|
194
201
|
type GenerateTocItemsOptions = Pick<
|
|
195
202
|
FlexibleTocOptions,
|
|
196
|
-
|
|
203
|
+
| "maxDepth"
|
|
204
|
+
| "skipLevels"
|
|
205
|
+
| "includeParents"
|
|
206
|
+
| "skipParents"
|
|
207
|
+
| "exclude"
|
|
208
|
+
| "prefix"
|
|
209
|
+
| "after"
|
|
197
210
|
>;
|
|
198
211
|
|
|
199
212
|
```
|
|
@@ -257,9 +270,25 @@ use(remarkFlexibleToc, {
|
|
|
257
270
|
|
|
258
271
|
Now, the TOC consists only the third level headings.
|
|
259
272
|
|
|
273
|
+
#### `includeParents`
|
|
274
|
+
|
|
275
|
+
It uses a [`unist-util-is`][unist-util-is] compatible **`Test`** to allow headings to be children of certain nodes.
|
|
276
|
+
|
|
277
|
+
The option has no default value, meaningly there is no parent restriction by default.
|
|
278
|
+
|
|
279
|
+
```javascript
|
|
280
|
+
use(remarkFlexibleToc, {
|
|
281
|
+
includeParents: ["root", "listItem"];
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Now, only the headings whose immediate parent is the `root` or a `listItem` will be added into the TOC.
|
|
286
|
+
|
|
260
287
|
#### `skipParents`
|
|
261
288
|
|
|
262
|
-
|
|
289
|
+
It uses a [`unist-util-is`][unist-util-is] compatible **`Test`** to disallow headings to be children of certain nodes.
|
|
290
|
+
|
|
291
|
+
The option has no default value, meaningly there is no parent to be skipped by default.
|
|
263
292
|
|
|
264
293
|
```javascript
|
|
265
294
|
use(remarkFlexibleToc, {
|
|
@@ -269,6 +298,8 @@ use(remarkFlexibleToc, {
|
|
|
269
298
|
|
|
270
299
|
Now, the headings in the `<blockquote>` will not be added into the TOC.
|
|
271
300
|
|
|
301
|
+
If `includeParents` and `skipParents` match the same parent, `skipParents` wins. The `root` is not protected specially and can also be skipped.
|
|
302
|
+
|
|
272
303
|
#### `exclude`
|
|
273
304
|
|
|
274
305
|
It is a **string** or **string[]** option. The plugin wraps the string(s) in new RegExp('^(' + value + ')$', 'i'), so any heading matching this expression will not be present in the TOC. The RegExp checks exact (not contain) matching and case insensitive as you see.
|
|
@@ -295,6 +326,22 @@ use(remarkFlexibleToc, {
|
|
|
295
326
|
```
|
|
296
327
|
Now, all TOC items' `href`s will start with that prefix like `#text-prefix-the-subheading`.
|
|
297
328
|
|
|
329
|
+
#### `after`
|
|
330
|
+
|
|
331
|
+
It is a **string** option for indicating a heading section after which the TOC items will be generated.
|
|
332
|
+
|
|
333
|
+
The plugin wraps the string in new RegExp('^(' + value + ')$', 'i'), so the first heading matching this expression is used. The matched heading and its section are not included. The collection starts with the next heading having the same or a higher level, and continues with the following headings.
|
|
334
|
+
|
|
335
|
+
The option has no default value.
|
|
336
|
+
|
|
337
|
+
```javascript
|
|
338
|
+
use(remarkFlexibleToc, {
|
|
339
|
+
after: "(table[ -]of[ -])?contents?|toc";
|
|
340
|
+
});
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
This is useful when a table of contents heading already exists in the document and you want to generate the TOC items only for the headings after that section.
|
|
344
|
+
|
|
298
345
|
#### `callback`
|
|
299
346
|
|
|
300
347
|
It is a **callback function** `callback?: (toc: TocItem[]) => undefined;` which takes the TOC items as an argument and returns nothing. It is usefull for logging the TOC, forexample, or modifing the TOC. **It is allowed that the callback function is able to mutate the TOC items !**
|
|
@@ -314,8 +361,11 @@ Now, each time when you compile the source, the TOC will be logged into the cons
|
|
|
314
361
|
## A Table of Content (TOC) Item
|
|
315
362
|
|
|
316
363
|
```typescript
|
|
364
|
+
import type { PhrasingContent } from "mdast";
|
|
365
|
+
|
|
317
366
|
type TocItem = {
|
|
318
367
|
value: string; // heading text
|
|
368
|
+
content: PhrasingContent[]; // normalized rich heading content to be used safely inside a TOC link
|
|
319
369
|
href: string; // produced uniquely by "github-slugger" using the value of the heading
|
|
320
370
|
depth: HeadingDepth; // 1 | 2 | 3 | 4 | 5 | 6
|
|
321
371
|
numbering: number[]; // explained below
|
|
@@ -324,6 +374,8 @@ type TocItem = {
|
|
|
324
374
|
};
|
|
325
375
|
```
|
|
326
376
|
|
|
377
|
+
The `content` keeps the rich MDAST phrasing content of the heading. Links and link references are unwrapped to prevent nested links, footnote references are omitted, and position information is removed. The content is cloned, so mutating it does not mutate the heading in the MDAST tree.
|
|
378
|
+
|
|
327
379
|
> [!NOTE]
|
|
328
380
|
> If there is a remark plugin before **`remark-flexible-toc`** in the plugin chain like **`remark-heading-id`** or **`remark-custom-header-id`**, which provides custom id for headings, that custom id takes precedence for `href`.
|
|
329
381
|
|
|
@@ -506,6 +558,7 @@ I also build low-level utilities and plugins for the Unified ecosystem that can
|
|
|
506
558
|
[remark]: https://github.com/remarkjs/remark
|
|
507
559
|
[remarkplugins]: https://github.com/remarkjs/remark/blob/main/doc/plugins.md
|
|
508
560
|
[mdast]: https://github.com/syntax-tree/mdast
|
|
561
|
+
[unist-util-is]: https://github.com/syntax-tree/unist-util-is
|
|
509
562
|
[rehype-slug]: https://github.com/rehypejs/rehype-slug
|
|
510
563
|
[rehype-autolink-headings]: https://github.com/rehypejs/rehype-autolink-headings
|
|
511
564
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Plugin } from "unified";
|
|
2
|
-
import type { Root } from "mdast";
|
|
2
|
+
import type { PhrasingContent, Root } from "mdast";
|
|
3
|
+
import type { Test } from "unist-util-is";
|
|
3
4
|
export type Prettify<T> = {
|
|
4
5
|
[K in keyof T]: T[K];
|
|
5
6
|
} & {};
|
|
@@ -8,6 +9,7 @@ export type HeadingParent = "root" | "blockquote" | "footnoteDefinition" | "list
|
|
|
8
9
|
export type HeadingDepth = 1 | 2 | 3 | 4 | 5 | 6;
|
|
9
10
|
export type TocItem = {
|
|
10
11
|
value: string;
|
|
12
|
+
content: PhrasingContent[];
|
|
11
13
|
href: string;
|
|
12
14
|
depth: HeadingDepth;
|
|
13
15
|
numbering: number[];
|
|
@@ -21,9 +23,11 @@ export type TocItem = {
|
|
|
21
23
|
* tocRef (default: []) — another way of exposing the tocItems
|
|
22
24
|
* maxDepth (default: 6) — max heading depth to include in the table of contents; this is inclusive: when set to 3, level three headings are included
|
|
23
25
|
* skipLevels (default: [1]) — disallowed heading levels, by default the article h1 is not expected to be in the TOC
|
|
24
|
-
*
|
|
26
|
+
* includeParents — allow headings to be children of certain nodes; internally uses unist-util-is Test
|
|
27
|
+
* skipParents (default: []) — disallow headings to be children of certain nodes; internally uses unist-util-is Test
|
|
25
28
|
* exclude — headings to skip, wrapped in new RegExp('^(' + value + ')$', 'i'); any heading matching this expression will not be present in the table of contents
|
|
26
29
|
* prefix - the text that will be attached to headings as prefix, like "text-prefix-"
|
|
30
|
+
* after — heading to look for, wrapped in new RegExp('^(' + value + ')$', 'i'); the TOC items will be generated after that heading section
|
|
27
31
|
* callback - It is a callback function to take the array of toc items as an argument
|
|
28
32
|
*/
|
|
29
33
|
export type FlexibleTocOptions = {
|
|
@@ -31,12 +35,14 @@ export type FlexibleTocOptions = {
|
|
|
31
35
|
tocRef?: TocItem[];
|
|
32
36
|
maxDepth?: HeadingDepth;
|
|
33
37
|
skipLevels?: HeadingDepth[];
|
|
34
|
-
|
|
38
|
+
includeParents?: Test;
|
|
39
|
+
skipParents?: Test;
|
|
35
40
|
exclude?: string | string[];
|
|
36
41
|
prefix?: string;
|
|
42
|
+
after?: string;
|
|
37
43
|
callback?: (toc: TocItem[]) => undefined;
|
|
38
44
|
};
|
|
39
|
-
export type GenerateTocItemsOptions = Pick<FlexibleTocOptions, "maxDepth" | "skipLevels" | "skipParents" | "exclude" | "prefix">;
|
|
45
|
+
export type GenerateTocItemsOptions = Pick<FlexibleTocOptions, "maxDepth" | "skipLevels" | "includeParents" | "skipParents" | "exclude" | "prefix" | "after">;
|
|
40
46
|
export declare function generateTocItemsFromMdast(tree: Root, options?: GenerateTocItemsOptions): TocItem[];
|
|
41
47
|
declare const RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root>;
|
|
42
48
|
export default RemarkFlexibleToc;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AACnD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAO1C,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,EAAE,CAAC;AAExD,MAAM,MAAM,iBAAiB,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,QAAQ,CAAC,IAA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G,YAAY,GAAG,gBAAgB,GAAG,aAAa,GAAG,SAAS,GAAG,QAAQ,GAAG,OAAO,CAC9F,CAAC;AAgFF,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,EAAE,CAwFX;AAED,QAAA,MAAM,iBAAiB,EAAE,MAAM,CAAC,CAAC,kBAAkB,CAAC,CAAC,EAAE,IAAI,CA+B1D,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import structuredClone from "@ungap/structured-clone";
|
|
2
|
+
import { convert } from "unist-util-is";
|
|
1
3
|
import { visit, CONTINUE } from "unist-util-visit";
|
|
2
4
|
import GithubSlugger from "github-slugger";
|
|
3
5
|
import { toString } from "mdast-util-to-string";
|
|
@@ -6,7 +8,6 @@ const DEFAULT_SETTINGS = {
|
|
|
6
8
|
tocRef: [],
|
|
7
9
|
maxDepth: 6,
|
|
8
10
|
skipLevels: [1],
|
|
9
|
-
skipParents: [],
|
|
10
11
|
};
|
|
11
12
|
/**
|
|
12
13
|
* adds numberings to the TOC items.
|
|
@@ -47,14 +48,37 @@ function addNumbering(arr) {
|
|
|
47
48
|
tocItem.numbering = numbering;
|
|
48
49
|
}
|
|
49
50
|
}
|
|
51
|
+
function copyTocContent(nodes) {
|
|
52
|
+
const results = [];
|
|
53
|
+
for (const node of nodes) {
|
|
54
|
+
if (node.type === "footnoteReference")
|
|
55
|
+
continue;
|
|
56
|
+
if (node.type === "link" || node.type === "linkReference") {
|
|
57
|
+
results.push(...copyTocContent(node.children));
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const copy = structuredClone(node);
|
|
61
|
+
delete copy.position;
|
|
62
|
+
if ("children" in copy) {
|
|
63
|
+
copy.children = copyTocContent(copy.children);
|
|
64
|
+
}
|
|
65
|
+
results.push(copy);
|
|
66
|
+
}
|
|
67
|
+
return results;
|
|
68
|
+
}
|
|
50
69
|
export function generateTocItemsFromMdast(tree, options) {
|
|
51
70
|
const settings = Object.assign({}, DEFAULT_SETTINGS, options);
|
|
52
71
|
const exludeRegexFilter = settings.exclude &&
|
|
53
72
|
(Array.isArray(settings.exclude)
|
|
54
73
|
? new RegExp("^(" + settings.exclude.join("|") + ")$", "i")
|
|
55
74
|
: new RegExp("^(" + settings.exclude + ")$", "i"));
|
|
75
|
+
const afterRegexFilter = settings.after && new RegExp("^(" + settings.after + ")$", "i");
|
|
76
|
+
const includeParentsFilter = settings.includeParents && convert(settings.includeParents);
|
|
77
|
+
const skipParentsFilter = settings.skipParents && convert(settings.skipParents);
|
|
56
78
|
const slugger = new GithubSlugger();
|
|
57
79
|
const tocItems = [];
|
|
80
|
+
let afterHeadingDepth;
|
|
81
|
+
let afterSectionEnded = !afterRegexFilter;
|
|
58
82
|
visit(tree, "heading", (_node, _index, _parent) => {
|
|
59
83
|
/* v8 ignore next -- @preserve */
|
|
60
84
|
if (!_parent || typeof _index === "undefined")
|
|
@@ -63,14 +87,33 @@ export function generateTocItemsFromMdast(tree, options) {
|
|
|
63
87
|
const value = toString(_node, { includeImageAlt: false });
|
|
64
88
|
let href = `#${settings.prefix ?? ""}${slugger.slug(value)}`;
|
|
65
89
|
const parent = _parent.type;
|
|
90
|
+
const parentIncluded = !includeParentsFilter || includeParentsFilter(_parent);
|
|
91
|
+
const parentSkipped = !!skipParentsFilter && skipParentsFilter(_parent);
|
|
92
|
+
const parentAllowed = parentIncluded && !parentSkipped;
|
|
93
|
+
// after check
|
|
94
|
+
if (afterRegexFilter) {
|
|
95
|
+
if (!afterHeadingDepth) {
|
|
96
|
+
if (parentAllowed && afterRegexFilter.test(value))
|
|
97
|
+
afterHeadingDepth = depth;
|
|
98
|
+
return CONTINUE;
|
|
99
|
+
}
|
|
100
|
+
if (!afterSectionEnded) {
|
|
101
|
+
if (!parentAllowed || depth > afterHeadingDepth)
|
|
102
|
+
return CONTINUE;
|
|
103
|
+
afterSectionEnded = true;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
66
106
|
// maxDepth check
|
|
67
107
|
if (depth > settings.maxDepth)
|
|
68
108
|
return CONTINUE;
|
|
69
109
|
// skipLevels check
|
|
70
110
|
if (settings.skipLevels.includes(depth))
|
|
71
111
|
return CONTINUE;
|
|
112
|
+
// includeParents check
|
|
113
|
+
if (!parentIncluded)
|
|
114
|
+
return CONTINUE;
|
|
72
115
|
// skipParents check
|
|
73
|
-
if (
|
|
116
|
+
if (parentSkipped)
|
|
74
117
|
return CONTINUE;
|
|
75
118
|
// exclude check
|
|
76
119
|
if (exludeRegexFilter && exludeRegexFilter.test(value))
|
|
@@ -85,6 +128,7 @@ export function generateTocItemsFromMdast(tree, options) {
|
|
|
85
128
|
href = `#${data["id"]}`;
|
|
86
129
|
tocItems.push({
|
|
87
130
|
value,
|
|
131
|
+
content: copyTocContent(_node.children),
|
|
88
132
|
href,
|
|
89
133
|
depth,
|
|
90
134
|
numbering: [],
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAuDhD,MAAM,gBAAgB,GAAuB;IAC3C,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,CAAC;IACX,UAAU,EAAE,CAAC,CAAC,CAAC;IACf,WAAW,EAAE,EAAE;CAChB,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,YAAY,CAAC,GAAc;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACpC,MAAM,OAAO,GAAG,GAAG,CA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AC1D,2DAA2D;QAC3D,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC;QAE5C,6EAA6E;QAE7E,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;YACpB,6DAA6D;YAC7D,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;YAE3B,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC3B,yDAAyD;gBACzD,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,iBAAiB,CAAC","sourcesContent":["import type { Plugin } from \"unified\";\nimport type { Root } from \"mdast\";\nimport { visit, CONTINUE } from \"unist-util-visit\";\nimport GithubSlugger from \"github-slugger\";\nimport { toString } from \"mdast-util-to-string\";\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type PartiallyRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\n\nexport type HeadingParent =\n \"root\" | \"blockquote\" | \"footnoteDefinition\" | \"listItem\" | \"container\" | \"mdxJsxFlowElement\";\n\nexport type HeadingDepth = 1 | 2 | 3 | 4 | 5 | 6;\n\nexport type TocItem = {\n value: string;\n href: string;\n depth: HeadingDepth;\n numbering: number[];\n parent: HeadingParent;\n data?: {\n [PropertyName: string]: string | number | boolean | (string | number)[] | null | undefined;\n };\n};\n\n/**\n * tocName (default: \"toc\") - the key name which is attached into vfile.data\n * tocRef (default: []) — another way of exposing the tocItems\n * maxDepth (default: 6) — max heading depth to include in the table of contents; this is inclusive: when set to 3, level three headings are included\n * skipLevels (default: [1]) — disallowed heading levels, by default the article h1 is not expected to be in the TOC\n * skipParents (default: []) — disallow headings to be children of certain node types, (the \"root\" can not be skipped)\n * exclude — headings to skip, wrapped in new RegExp('^(' + value + ')$', 'i'); any heading matching this expression will not be present in the table of contents\n * prefix - the text that will be attached to headings as prefix, like \"text-prefix-\"\n * callback - It is a callback function to take the array of toc items as an argument\n */\nexport type FlexibleTocOptions = {\n tocName?: string;\n tocRef?: TocItem[];\n maxDepth?: HeadingDepth;\n skipLevels?: HeadingDepth[];\n skipParents?: Exclude<HeadingParent, \"root\">[];\n exclude?: string | string[];\n prefix?: string;\n callback?: (toc: TocItem[]) => undefined;\n};\n\nexport type GenerateTocItemsOptions = Pick<\n FlexibleTocOptions,\n \"maxDepth\" | \"skipLevels\" | \"skipParents\" | \"exclude\" | \"prefix\"\n>;\n\ntype PartiallyRequiredFlexibleTocOptions = Prettify<\n PartiallyRequired<\n FlexibleTocOptions,\n \"tocName\" | \"tocRef\" | \"maxDepth\" | \"skipLevels\" | \"skipParents\"\n >\n>;\n\nconst DEFAULT_SETTINGS: FlexibleTocOptions = {\n tocName: \"toc\",\n tocRef: [],\n maxDepth: 6,\n skipLevels: [1],\n skipParents: [],\n};\n\n/**\n * adds numberings to the TOC items.\n * why \"number[]\"? It is because up to you joining with dot or dash or slicing the first number (reserved for h1)\n *\n * [1]\n * [1,1]\n * [1,2]\n * [1,2,1]\n */\nfunction addNumbering(arr: TocItem[]) {\n for (let i = 0; i < arr.length; i++) {\n const tocItem = arr[i];\n const depth = tocItem.depth;\n\n let numbering: number[];\n\n const prevObj = i > 0 ? arr[i - 1] : undefined;\n const prevDepth = prevObj ? prevObj.depth : undefined;\n const prevNumbering = prevObj ? prevObj.numbering : undefined;\n\n if (!prevNumbering || !prevDepth) {\n numbering = Array.from({ length: depth }, () => 1);\n } else if (depth === prevDepth) {\n numbering = [...prevNumbering];\n numbering[depth - 1]++;\n } else if (depth > prevDepth) {\n numbering = [\n ...prevNumbering,\n ...(Array.from(\n { length: depth - prevDepth }, // if depth is more bigger than prevDepth, put more \"1\" inside the array\n () => 1,\n ) as HeadingDepth[]),\n ];\n } else {\n // if (depth < prevDepth)\n numbering = prevNumbering.slice(0, depth);\n numbering[depth - 1]++;\n }\n\n tocItem.numbering = numbering;\n }\n}\n\nexport function generateTocItemsFromMdast(\n tree: Root,\n options?: GenerateTocItemsOptions,\n): TocItem[] {\n const settings = Object.assign(\n {},\n DEFAULT_SETTINGS,\n options,\n ) as PartiallyRequiredFlexibleTocOptions;\n\n const exludeRegexFilter =\n settings.exclude &&\n (Array.isArray(settings.exclude)\n ? new RegExp(\"^(\" + settings.exclude.join(\"|\") + \")$\", \"i\")\n : new RegExp(\"^(\" + settings.exclude + \")$\", \"i\"));\n\n const slugger = new GithubSlugger();\n const tocItems: TocItem[] = [];\n\n visit(tree, \"heading\", (_node, _index, _parent) => {\n /* v8 ignore next -- @preserve */\n if (!_parent || typeof _index === \"undefined\") return;\n\n const depth = _node.depth;\n const value = toString(_node, { includeImageAlt: false });\n let href = `#${settings.prefix ?? \"\"}${slugger.slug(value)}`;\n const parent = _parent.type;\n\n // maxDepth check\n if (depth > settings.maxDepth) return CONTINUE;\n\n // skipLevels check\n if (settings.skipLevels.includes(depth)) return CONTINUE;\n\n // skipParents check\n if (parent !== \"root\" && settings.skipParents.includes(parent)) return CONTINUE;\n\n // exclude check\n if (exludeRegexFilter && exludeRegexFilter.test(value)) return CONTINUE;\n\n // Other remark plugins can store custom data in node.data.hProperties\n // I omitted node.data.hName and node.data.hChildren since not related with toc\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore, vscode resolves the type but tsc build raises an error awkwardly, saying \"hProperties\" does not exist in \"HeadingData\".\n const hProperties = _node.data?.hProperties;\n const data = hProperties ? { ...hProperties } : undefined;\n\n if (data?.[\"id\"]) href = `#${data[\"id\"]}`;\n\n tocItems.push({\n value,\n href,\n depth,\n numbering: [],\n parent,\n ...(data && { data }),\n });\n\n return CONTINUE;\n });\n\n addNumbering(tocItems);\n\n return tocItems;\n}\n\nconst RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root> = (options) => {\n const settings = Object.assign(\n {},\n DEFAULT_SETTINGS,\n options,\n ) as PartiallyRequiredFlexibleTocOptions;\n\n return (tree, file) => {\n const tocItems = generateTocItemsFromMdast(tree, options);\n\n // it is allowed to modify the TOC in the callback\n settings.callback?.(tocItems);\n\n // method - 1 for exposing the data via vfile.data **************************\n\n // other plugins are not allowed to mutate the exposed TOC\n // The spreading is slower than push but need to fresh copy\n file.data[settings.tocName] = [...tocItems];\n\n // method - 2 for exposing the data via reference array *********************\n\n if (options?.tocRef) {\n // prevent dublication if the plugin is called more than once\n settings.tocRef.length = 0;\n\n tocItems.forEach((tocItem) => {\n // the tocRef is not allowed to mutate the vfile.data.toc\n settings.tocRef.push(tocItem);\n });\n }\n };\n};\n\nexport default RemarkFlexibleToc;\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,eAAe,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAyDhD,MAAM,gBAAgB,GAAuB;IAC3C,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,CAAC;IACX,UAAU,EAAE,CAAC,CAAC,CAAC;CAChB,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,YAAY,CAAC,GAAc;IAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACpC,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;QACvB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAE5B,IAAI,SAAmB,CAAC;QAExB,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC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AED,MAAM,iBAAiB,GAAwC,CAAC,OAAO,EAAE,EAAE;IACzE,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAC5B,EAAE,EACF,gBAAgB,EAChB,OAAO,CAC+B,CAAC;IAEzC,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,QAAQ,GAAG,yBAAyB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAE1D,kDAAkD;QAClD,QAAQ,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QAE9B,6EAA6E;QAE7E,0DAA0D;QAC1D,2DAA2D;QAC3D,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC;QAE5C,6EAA6E;QAE7E,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;YACpB,6DAA6D;YAC7D,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;YAE3B,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC3B,yDAAyD;gBACzD,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,iBAAiB,CAAC","sourcesContent":["import type { Plugin } from \"unified\";\nimport type { PhrasingContent, Root } from \"mdast\";\nimport type { Test } from \"unist-util-is\";\nimport structuredClone from \"@ungap/structured-clone\";\nimport { convert } from \"unist-util-is\";\nimport { visit, CONTINUE } from \"unist-util-visit\";\nimport GithubSlugger from \"github-slugger\";\nimport { toString } from \"mdast-util-to-string\";\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type PartiallyRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\n\nexport type HeadingParent =\n \"root\" | \"blockquote\" | \"footnoteDefinition\" | \"listItem\" | \"container\" | \"mdxJsxFlowElement\";\n\nexport type HeadingDepth = 1 | 2 | 3 | 4 | 5 | 6;\n\nexport type TocItem = {\n value: string;\n content: PhrasingContent[];\n href: string;\n depth: HeadingDepth;\n numbering: number[];\n parent: HeadingParent;\n data?: {\n [PropertyName: string]: string | number | boolean | (string | number)[] | null | undefined;\n };\n};\n\n/**\n * tocName (default: \"toc\") - the key name which is attached into vfile.data\n * tocRef (default: []) — another way of exposing the tocItems\n * maxDepth (default: 6) — max heading depth to include in the table of contents; this is inclusive: when set to 3, level three headings are included\n * skipLevels (default: [1]) — disallowed heading levels, by default the article h1 is not expected to be in the TOC\n * includeParents — allow headings to be children of certain nodes; internally uses unist-util-is Test\n * skipParents (default: []) — disallow headings to be children of certain nodes; internally uses unist-util-is Test\n * exclude — headings to skip, wrapped in new RegExp('^(' + value + ')$', 'i'); any heading matching this expression will not be present in the table of contents\n * prefix - the text that will be attached to headings as prefix, like \"text-prefix-\"\n * after — heading to look for, wrapped in new RegExp('^(' + value + ')$', 'i'); the TOC items will be generated after that heading section\n * callback - It is a callback function to take the array of toc items as an argument\n */\nexport type FlexibleTocOptions = {\n tocName?: string;\n tocRef?: TocItem[];\n maxDepth?: HeadingDepth;\n skipLevels?: HeadingDepth[];\n includeParents?: Test;\n skipParents?: Test;\n exclude?: string | string[];\n prefix?: string;\n after?: string;\n callback?: (toc: TocItem[]) => undefined;\n};\n\nexport type GenerateTocItemsOptions = Pick<\n FlexibleTocOptions,\n \"maxDepth\" | \"skipLevels\" | \"includeParents\" | \"skipParents\" | \"exclude\" | \"prefix\" | \"after\"\n>;\n\ntype PartiallyRequiredFlexibleTocOptions = Prettify<\n PartiallyRequired<FlexibleTocOptions, \"tocName\" | \"tocRef\" | \"maxDepth\" | \"skipLevels\">\n>;\n\nconst DEFAULT_SETTINGS: FlexibleTocOptions = {\n tocName: \"toc\",\n tocRef: [],\n maxDepth: 6,\n skipLevels: [1],\n};\n\n/**\n * adds numberings to the TOC items.\n * why \"number[]\"? It is because up to you joining with dot or dash or slicing the first number (reserved for h1)\n *\n * [1]\n * [1,1]\n * [1,2]\n * [1,2,1]\n */\nfunction addNumbering(arr: TocItem[]) {\n for (let i = 0; i < arr.length; i++) {\n const tocItem = arr[i];\n const depth = tocItem.depth;\n\n let numbering: number[];\n\n const prevObj = i > 0 ? arr[i - 1] : undefined;\n const prevDepth = prevObj ? prevObj.depth : undefined;\n const prevNumbering = prevObj ? prevObj.numbering : undefined;\n\n if (!prevNumbering || !prevDepth) {\n numbering = Array.from({ length: depth }, () => 1);\n } else if (depth === prevDepth) {\n numbering = [...prevNumbering];\n numbering[depth - 1]++;\n } else if (depth > prevDepth) {\n numbering = [\n ...prevNumbering,\n ...(Array.from(\n { length: depth - prevDepth }, // if depth is more bigger than prevDepth, put more \"1\" inside the array\n () => 1,\n ) as HeadingDepth[]),\n ];\n } else {\n // if (depth < prevDepth)\n numbering = prevNumbering.slice(0, depth);\n numbering[depth - 1]++;\n }\n\n tocItem.numbering = numbering;\n }\n}\n\nfunction copyTocContent(nodes: PhrasingContent[]): PhrasingContent[] {\n const results: PhrasingContent[] = [];\n\n for (const node of nodes) {\n if (node.type === \"footnoteReference\") continue;\n\n if (node.type === \"link\" || node.type === \"linkReference\") {\n results.push(...copyTocContent(node.children));\n continue;\n }\n\n const copy = structuredClone(node);\n delete copy.position;\n\n if (\"children\" in copy) {\n copy.children = copyTocContent(copy.children);\n }\n\n results.push(copy);\n }\n\n return results;\n}\n\nexport function generateTocItemsFromMdast(\n tree: Root,\n options?: GenerateTocItemsOptions,\n): TocItem[] {\n const settings = Object.assign(\n {},\n DEFAULT_SETTINGS,\n options,\n ) as PartiallyRequiredFlexibleTocOptions;\n\n const exludeRegexFilter =\n settings.exclude &&\n (Array.isArray(settings.exclude)\n ? new RegExp(\"^(\" + settings.exclude.join(\"|\") + \")$\", \"i\")\n : new RegExp(\"^(\" + settings.exclude + \")$\", \"i\"));\n const afterRegexFilter = settings.after && new RegExp(\"^(\" + settings.after + \")$\", \"i\");\n\n const includeParentsFilter = settings.includeParents && convert(settings.includeParents);\n const skipParentsFilter = settings.skipParents && convert(settings.skipParents);\n\n const slugger = new GithubSlugger();\n const tocItems: TocItem[] = [];\n let afterHeadingDepth: HeadingDepth | undefined;\n let afterSectionEnded = !afterRegexFilter;\n\n visit(tree, \"heading\", (_node, _index, _parent) => {\n /* v8 ignore next -- @preserve */\n if (!_parent || typeof _index === \"undefined\") return;\n\n const depth = _node.depth;\n const value = toString(_node, { includeImageAlt: false });\n let href = `#${settings.prefix ?? \"\"}${slugger.slug(value)}`;\n const parent = _parent.type;\n const parentIncluded = !includeParentsFilter || includeParentsFilter(_parent);\n const parentSkipped = !!skipParentsFilter && skipParentsFilter(_parent);\n const parentAllowed = parentIncluded && !parentSkipped;\n\n // after check\n if (afterRegexFilter) {\n if (!afterHeadingDepth) {\n if (parentAllowed && afterRegexFilter.test(value)) afterHeadingDepth = depth;\n return CONTINUE;\n }\n\n if (!afterSectionEnded) {\n if (!parentAllowed || depth > afterHeadingDepth) return CONTINUE;\n afterSectionEnded = true;\n }\n }\n\n // maxDepth check\n if (depth > settings.maxDepth) return CONTINUE;\n\n // skipLevels check\n if (settings.skipLevels.includes(depth)) return CONTINUE;\n\n // includeParents check\n if (!parentIncluded) return CONTINUE;\n\n // skipParents check\n if (parentSkipped) return CONTINUE;\n\n // exclude check\n if (exludeRegexFilter && exludeRegexFilter.test(value)) return CONTINUE;\n\n // Other remark plugins can store custom data in node.data.hProperties\n // I omitted node.data.hName and node.data.hChildren since not related with toc\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore, vscode resolves the type but tsc build raises an error awkwardly, saying \"hProperties\" does not exist in \"HeadingData\".\n const hProperties = _node.data?.hProperties;\n const data = hProperties ? { ...hProperties } : undefined;\n\n if (data?.[\"id\"]) href = `#${data[\"id\"]}`;\n\n tocItems.push({\n value,\n content: copyTocContent(_node.children),\n href,\n depth,\n numbering: [],\n parent,\n ...(data && { data }),\n });\n\n return CONTINUE;\n });\n\n addNumbering(tocItems);\n\n return tocItems;\n}\n\nconst RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root> = (options) => {\n const settings = Object.assign(\n {},\n DEFAULT_SETTINGS,\n options,\n ) as PartiallyRequiredFlexibleTocOptions;\n\n return (tree, file) => {\n const tocItems = generateTocItemsFromMdast(tree, options);\n\n // it is allowed to modify the TOC in the callback\n settings.callback?.(tocItems);\n\n // method - 1 for exposing the data via vfile.data **************************\n\n // other plugins are not allowed to mutate the exposed TOC\n // The spreading is slower than push but need to fresh copy\n file.data[settings.tocName] = [...tocItems];\n\n // method - 2 for exposing the data via reference array *********************\n\n if (options?.tocRef) {\n // prevent dublication if the plugin is called more than once\n settings.tocRef.length = 0;\n\n tocItems.forEach((tocItem) => {\n // the tocRef is not allowed to mutate the vfile.data.toc\n settings.tocRef.push(tocItem);\n });\n }\n };\n};\n\nexport default RemarkFlexibleToc;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remark-flexible-toc",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Remark plugin to expose the table of contents via Vfile.data or via an option reference",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -55,6 +55,7 @@
|
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@eslint/js": "^10.0.1",
|
|
57
57
|
"@types/node": "^26.6.5",
|
|
58
|
+
"@types/ungap__structured-clone": "^1.0.0",
|
|
58
59
|
"@vitest/coverage-v8": "^4.1.12",
|
|
59
60
|
"@vitest/eslint-plugin": "^1.6.27",
|
|
60
61
|
"dedent": "^1.7.2",
|
|
@@ -79,8 +80,10 @@
|
|
|
79
80
|
},
|
|
80
81
|
"dependencies": {
|
|
81
82
|
"@types/mdast": "^4.0.4",
|
|
83
|
+
"@ungap/structured-clone": "^1.0.0",
|
|
82
84
|
"github-slugger": "^2.0.0",
|
|
83
85
|
"mdast-util-to-string": "^4.0.0",
|
|
86
|
+
"unist-util-is": "^6.0.0",
|
|
84
87
|
"unist-util-visit": "^5.1.0"
|
|
85
88
|
},
|
|
86
89
|
"peerDependencies": {
|