remark-flexible-toc 1.2.7 → 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 CHANGED
@@ -20,6 +20,8 @@ A warm thanks 🙌 to [@ErfanEbrahimnia](https://github.com/ErfanEbrahimnia), [@
20
20
 
21
21
  This package is a [**unified**][unified] ([**remark**][remark]) plugin **to expose the table of contents via `Vfile.data` or via an option reference in markdown.**
22
22
 
23
+ **`remark-flexible-toc`** also exports `generateTocItemsFromMdast` to generate the table of contents items directly from an MDAST tree without requiring a unified processor or a VFile.
24
+
23
25
  [**unified**][unified] is a project that transforms content with abstract syntax trees (ASTs) using the new parser [**micromark**][micromark]. [**remark**][remark] adds support for markdown to unified. [**mdast**][mdast] is the Markdown Abstract Syntax Tree (AST) which is a specification for representing markdown in a syntax tree.
24
26
 
25
27
  **This plugin is a remark plugin that doesn't transform the MDAST but gets info from the MDAST.**
@@ -29,6 +31,7 @@ This package is a [**unified**][unified] ([**remark**][remark]) plugin **to expo
29
31
  **`remark-flexible-toc`** is useful if you want to get the table of contents (TOC) from the markdown/MDX document. It exposes the table of contents (TOC) in two ways:
30
32
  + by adding a `toc` object into `Vfile.data`
31
33
  + by mutating a reference array if provided in the options
34
+ + by generating `TocItem[]` directly from an MDAST tree with `generateTocItemsFromMdast`
32
35
 
33
36
  ## Installation
34
37
 
@@ -115,6 +118,7 @@ Now, running both `node example.js` you will see that the same table of contents
115
118
  ```javascript
116
119
  [
117
120
  {
121
+ content: [{ type: "text", value: "Section" }],
118
122
  depth: 2,
119
123
  href: "#section",
120
124
  numbering: [1, 1],
@@ -122,6 +126,7 @@ Now, running both `node example.js` you will see that the same table of contents
122
126
  value: "Section",
123
127
  },
124
128
  {
129
+ content: [{ type: "text", value: "Subheading 1" }],
125
130
  depth: 3,
126
131
  href: "#subheading-1",
127
132
  numbering: [1, 1, 1],
@@ -129,6 +134,7 @@ Now, running both `node example.js` you will see that the same table of contents
129
134
  value: "Subheading 1",
130
135
  },
131
136
  {
137
+ content: [{ type: "text", value: "Subheading 2" }],
132
138
  depth: 3,
133
139
  href: "#subheading-2",
134
140
  numbering: [1, 1, 2],
@@ -140,11 +146,31 @@ Now, running both `node example.js` you will see that the same table of contents
140
146
 
141
147
  Without **`remark-flexible-toc`**, there wouldn't be any `toc` key in the `file.data`:
142
148
 
149
+ #### Generating TOC items directly from MDAST
150
+
151
+ If you already have an MDAST tree, you can generate the table of contents items directly without using the remark plugin, a unified processor, or a VFile.
152
+
153
+ ```js
154
+ import { generateTocItemsFromMdast } from "remark-flexible-toc";
155
+
156
+ const tocItems = generateTocItemsFromMdast(tree, {
157
+ maxDepth: 4,
158
+ });
159
+
160
+ console.log(tocItems);
161
+ ```
162
+
163
+ The function returns `TocItem[]` and does not modify the MDAST tree.
164
+
165
+ The available options are `maxDepth`, `skipLevels`, `includeParents`, `skipParents`, `exclude`, `prefix`, and `after`.
166
+
143
167
  ## Options
144
168
 
145
169
  All options are **optional**.
146
170
 
147
171
  ```typescript
172
+ import type { Test } from "unist-util-is";
173
+
148
174
  type HeadingParent =
149
175
  | "root"
150
176
  | "blockquote"
@@ -160,13 +186,31 @@ use(remarkFlexibleToc, {
160
186
  tocRef?: TocItem[]; // default: []
161
187
  maxDepth?: HeadingDepth; // default: 6
162
188
  skipLevels?: HeadingDepth[]; // default: [1]
163
- skipParents?: Exclude<HeadingParent, "root">[]; // default: []
189
+ includeParents?: Test;
190
+ skipParents?: Test;
164
191
  exclude?: string | string[];
165
192
  prefix?: string;
193
+ after?: string;
166
194
  callback?: (toc: TocItem[]) => undefined;
167
195
  } as FlexibleTocOptions);
168
196
  ```
169
197
 
198
+ `generateTocItemsFromMdast` accepts only the options related to generating the TOC items. The plugin-specific `tocName`, `tocRef`, and `callback` options are not applicable.
199
+
200
+ ```ts
201
+ type GenerateTocItemsOptions = Pick<
202
+ FlexibleTocOptions,
203
+ | "maxDepth"
204
+ | "skipLevels"
205
+ | "includeParents"
206
+ | "skipParents"
207
+ | "exclude"
208
+ | "prefix"
209
+ | "after"
210
+ >;
211
+
212
+ ```
213
+
170
214
  #### `tocName`
171
215
 
172
216
  It is a **string** option in which the table of contents (TOC) is placed in the `vfile.data`.
@@ -226,9 +270,25 @@ use(remarkFlexibleToc, {
226
270
 
227
271
  Now, the TOC consists only the third level headings.
228
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
+
229
287
  #### `skipParents`
230
288
 
231
- By default it is an empty array `[]`. The array may contain the parent values `blockquote`, `footnoteDefinition`, `listItem`, `container`, `mdxJsxFlowElement`.
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.
232
292
 
233
293
  ```javascript
234
294
  use(remarkFlexibleToc, {
@@ -238,6 +298,8 @@ use(remarkFlexibleToc, {
238
298
 
239
299
  Now, the headings in the `<blockquote>` will not be added into the TOC.
240
300
 
301
+ If `includeParents` and `skipParents` match the same parent, `skipParents` wins. The `root` is not protected specially and can also be skipped.
302
+
241
303
  #### `exclude`
242
304
 
243
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.
@@ -264,6 +326,22 @@ use(remarkFlexibleToc, {
264
326
  ```
265
327
  Now, all TOC items' `href`s will start with that prefix like `#text-prefix-the-subheading`.
266
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
+
267
345
  #### `callback`
268
346
 
269
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 !**
@@ -283,8 +361,11 @@ Now, each time when you compile the source, the TOC will be logged into the cons
283
361
  ## A Table of Content (TOC) Item
284
362
 
285
363
  ```typescript
364
+ import type { PhrasingContent } from "mdast";
365
+
286
366
  type TocItem = {
287
367
  value: string; // heading text
368
+ content: PhrasingContent[]; // normalized rich heading content to be used safely inside a TOC link
288
369
  href: string; // produced uniquely by "github-slugger" using the value of the heading
289
370
  depth: HeadingDepth; // 1 | 2 | 3 | 4 | 5 | 6
290
371
  numbering: number[]; // explained below
@@ -293,6 +374,8 @@ type TocItem = {
293
374
  };
294
375
  ```
295
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
+
296
379
  > [!NOTE]
297
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`.
298
381
 
@@ -382,9 +465,13 @@ tocItem.numbering.join("-");
382
465
 
383
466
  This plugin does not modify the `mdast` (markdown abstract syntax tree), collects data from the `mdast` and adds information into the `vfile.data` if required.
384
467
 
468
+ `generateTocItemsFromMdast` also does not modify the provided MDAST tree.
469
+
385
470
  ## Types
386
471
 
387
- This package is fully typed with [TypeScript][url-typescript]. The plugin exports the types `FlexibleTocOptions`, `HeadingParent`, `HeadingDepth`, `TocItem`.
472
+ This package is fully typed with [TypeScript][url-typescript] and also exports the `generateTocItemsFromMdast` utility function.
473
+
474
+ The plugin exports the types `FlexibleTocOptions`, `HeadingParent`, `HeadingDepth`, `TocItem` and `GenerateTocItemsOptions`.
388
475
 
389
476
  ## Compatibility
390
477
 
@@ -471,6 +558,7 @@ I also build low-level utilities and plugins for the Unified ecosystem that can
471
558
  [remark]: https://github.com/remarkjs/remark
472
559
  [remarkplugins]: https://github.com/remarkjs/remark/blob/main/doc/plugins.md
473
560
  [mdast]: https://github.com/syntax-tree/mdast
561
+ [unist-util-is]: https://github.com/syntax-tree/unist-util-is
474
562
  [rehype-slug]: https://github.com/rehypejs/rehype-slug
475
563
  [rehype-autolink-headings]: https://github.com/rehypejs/rehype-autolink-headings
476
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
- * skipParents (default: []) — disallow headings to be children of certain node types, (the "root" can not be skipped)
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,11 +35,15 @@ export type FlexibleTocOptions = {
31
35
  tocRef?: TocItem[];
32
36
  maxDepth?: HeadingDepth;
33
37
  skipLevels?: HeadingDepth[];
34
- skipParents?: Exclude<HeadingParent, "root">[];
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
  };
45
+ export type GenerateTocItemsOptions = Pick<FlexibleTocOptions, "maxDepth" | "skipLevels" | "includeParents" | "skipParents" | "exclude" | "prefix" | "after">;
46
+ export declare function generateTocItemsFromMdast(tree: Root, options?: GenerateTocItemsOptions): TocItem[];
39
47
  declare const RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root>;
40
48
  export default RemarkFlexibleToc;
41
49
  //# sourceMappingURL=index.d.ts.map
@@ -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;AAKlC,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,IAAI,CAAC,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B,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;IACnB,QAAQ,CAAC,EAAE,YAAY,CAAC;IACxB,UAAU,CAAC,EAAE,YAAY,EAAE,CAAC;IAC5B,cAAc,CAAC,EAAE,IAAI,CAAC;IACtB,WAAW,CAAC,EAAE,IAAI,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,SAAS,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG,IAAI,CACxC,kBAAkB,EAClB,UAAU,GAAG,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,54 +48,102 @@ function addNumbering(arr) {
47
48
  tocItem.numbering = numbering;
48
49
  }
49
50
  }
50
- const RemarkFlexibleToc = (options) => {
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
+ }
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"));
56
- return (tree, file) => {
57
- const slugger = new GithubSlugger();
58
- const tocItems = [];
59
- visit(tree, "heading", (_node, _index, _parent) => {
60
- /* v8 ignore next -- @preserve */
61
- if (!_parent || typeof _index === "undefined")
62
- return;
63
- const depth = _node.depth;
64
- const value = toString(_node, { includeImageAlt: false });
65
- let href = `#${settings.prefix ?? ""}${slugger.slug(value)}`;
66
- const parent = _parent.type;
67
- // maxDepth check
68
- if (depth > settings.maxDepth)
69
- return CONTINUE;
70
- // skipLevels check
71
- if (settings.skipLevels.includes(depth))
72
- return CONTINUE;
73
- // skipParents check
74
- if (parent !== "root" && settings.skipParents.includes(parent))
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);
78
+ const slugger = new GithubSlugger();
79
+ const tocItems = [];
80
+ let afterHeadingDepth;
81
+ let afterSectionEnded = !afterRegexFilter;
82
+ visit(tree, "heading", (_node, _index, _parent) => {
83
+ /* v8 ignore next -- @preserve */
84
+ if (!_parent || typeof _index === "undefined")
85
+ return;
86
+ const depth = _node.depth;
87
+ const value = toString(_node, { includeImageAlt: false });
88
+ let href = `#${settings.prefix ?? ""}${slugger.slug(value)}`;
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;
75
98
  return CONTINUE;
76
- // exclude check
77
- if (exludeRegexFilter && exludeRegexFilter.test(value))
78
- return CONTINUE;
79
- // Other remark plugins can store custom data in node.data.hProperties
80
- // I omitted node.data.hName and node.data.hChildren since not related with toc
81
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
82
- // @ts-ignore, vscode resolves the type but tsc build raises an error awkwardly, saying "hProperties" does not exist in "HeadingData".
83
- const hProperties = _node.data?.hProperties;
84
- const data = hProperties ? { ...hProperties } : undefined;
85
- if (data?.["id"])
86
- href = `#${data["id"]}`;
87
- tocItems.push({
88
- value,
89
- href,
90
- depth,
91
- numbering: [],
92
- parent,
93
- ...(data && { data }),
94
- });
99
+ }
100
+ if (!afterSectionEnded) {
101
+ if (!parentAllowed || depth > afterHeadingDepth)
102
+ return CONTINUE;
103
+ afterSectionEnded = true;
104
+ }
105
+ }
106
+ // maxDepth check
107
+ if (depth > settings.maxDepth)
108
+ return CONTINUE;
109
+ // skipLevels check
110
+ if (settings.skipLevels.includes(depth))
111
+ return CONTINUE;
112
+ // includeParents check
113
+ if (!parentIncluded)
114
+ return CONTINUE;
115
+ // skipParents check
116
+ if (parentSkipped)
117
+ return CONTINUE;
118
+ // exclude check
119
+ if (exludeRegexFilter && exludeRegexFilter.test(value))
95
120
  return CONTINUE;
121
+ // Other remark plugins can store custom data in node.data.hProperties
122
+ // I omitted node.data.hName and node.data.hChildren since not related with toc
123
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
124
+ // @ts-ignore, vscode resolves the type but tsc build raises an error awkwardly, saying "hProperties" does not exist in "HeadingData".
125
+ const hProperties = _node.data?.hProperties;
126
+ const data = hProperties ? { ...hProperties } : undefined;
127
+ if (data?.["id"])
128
+ href = `#${data["id"]}`;
129
+ tocItems.push({
130
+ value,
131
+ content: copyTocContent(_node.children),
132
+ href,
133
+ depth,
134
+ numbering: [],
135
+ parent,
136
+ ...(data && { data }),
96
137
  });
97
- addNumbering(tocItems);
138
+ return CONTINUE;
139
+ });
140
+ addNumbering(tocItems);
141
+ return tocItems;
142
+ }
143
+ const RemarkFlexibleToc = (options) => {
144
+ const settings = Object.assign({}, DEFAULT_SETTINGS, options);
145
+ return (tree, file) => {
146
+ const tocItems = generateTocItemsFromMdast(tree, options);
98
147
  // it is allowed to modify the TOC in the callback
99
148
  settings.callback?.(tocItems);
100
149
  // method - 1 for exposing the data via vfile.data **************************
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,CAAC,CAAC,CAAC,CAAC;QACvB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAE5B,IAAI,SAAmB,CAAC;QAEx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AC,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\"\n | \"blockquote\"\n | \"footnoteDefinition\"\n | \"listItem\"\n | \"container\"\n | \"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\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\nconst RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root> = (options) => {\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 return (tree, file) => {\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 // 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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AAO,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.2.7",
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",
@@ -54,15 +54,17 @@
54
54
  },
55
55
  "devDependencies": {
56
56
  "@eslint/js": "^10.0.1",
57
- "@types/node": "^26.2.0",
58
- "@vitest/coverage-v8": "^4.1.11",
57
+ "@types/node": "^26.6.5",
58
+ "@types/ungap__structured-clone": "^1.0.0",
59
+ "@vitest/coverage-v8": "^4.1.12",
59
60
  "@vitest/eslint-plugin": "^1.6.27",
60
61
  "dedent": "^1.7.2",
61
- "eslint": "^10.8.1",
62
+ "eslint": "^10.13.0",
62
63
  "eslint-config-prettier": "^10.1.8",
63
- "eslint-plugin-prettier": "^5.5.6",
64
- "globals": "^17.11.0",
65
- "prettier": "^3.9.6",
64
+ "eslint-plugin-prettier": "^5.5.7",
65
+ "globals": "^17.13.0",
66
+ "mdast-util-from-markdown": "^2.1.0",
67
+ "prettier": "^3.9.10",
66
68
  "rehype-format": "^5.0.1",
67
69
  "rehype-stringify": "^10.0.1",
68
70
  "remark-custom-header-id": "^1.0.0",
@@ -70,16 +72,18 @@
70
72
  "remark-parse": "^11.0.0",
71
73
  "remark-rehype": "^11.1.2",
72
74
  "rimraf": "^6.1.3",
73
- "type-coverage": "^2.30.1",
75
+ "type-coverage": "^2.30.4",
74
76
  "typescript": "^5.9.3",
75
- "typescript-eslint": "^8.67.0",
77
+ "typescript-eslint": "^8.71.2",
76
78
  "unified": "^11.0.5",
77
- "vitest": "^4.1.11"
79
+ "vitest": "^4.1.12"
78
80
  },
79
81
  "dependencies": {
80
82
  "@types/mdast": "^4.0.4",
83
+ "@ungap/structured-clone": "^1.0.0",
81
84
  "github-slugger": "^2.0.0",
82
85
  "mdast-util-to-string": "^4.0.0",
86
+ "unist-util-is": "^6.0.0",
83
87
  "unist-util-visit": "^5.1.0"
84
88
  },
85
89
  "peerDependencies": {