remark-flexible-toc 1.2.8 → 1.3.2

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
@@ -118,24 +118,30 @@ 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],
124
125
  parent: "root",
126
+ parentPath: [],
125
127
  value: "Section",
126
128
  },
127
129
  {
130
+ content: [{ type: "text", value: "Subheading 1" }],
128
131
  depth: 3,
129
132
  href: "#subheading-1",
130
133
  numbering: [1, 1, 1],
131
134
  parent: "root",
135
+ parentPath: [],
132
136
  value: "Subheading 1",
133
137
  },
134
138
  {
139
+ content: [{ type: "text", value: "Subheading 2" }],
135
140
  depth: 3,
136
141
  href: "#subheading-2",
137
142
  numbering: [1, 1, 2],
138
143
  parent: "root",
144
+ parentPath: [],
139
145
  value: "Subheading 2",
140
146
  },
141
147
  ]
@@ -159,13 +165,15 @@ console.log(tocItems);
159
165
 
160
166
  The function returns `TocItem[]` and does not modify the MDAST tree.
161
167
 
162
- The available options are `maxDepth`, `skipLevels`, `skipParents`, `exclude`, and `prefix`.
168
+ The available options are `maxDepth`, `skipLevels`, `includeParents`, `skipParents`, `exclude`, `prefix`, and `after`.
163
169
 
164
170
  ## Options
165
171
 
166
172
  All options are **optional**.
167
173
 
168
174
  ```typescript
175
+ import type { Test } from "unist-util-is";
176
+
169
177
  type HeadingParent =
170
178
  | "root"
171
179
  | "blockquote"
@@ -181,9 +189,11 @@ use(remarkFlexibleToc, {
181
189
  tocRef?: TocItem[]; // default: []
182
190
  maxDepth?: HeadingDepth; // default: 6
183
191
  skipLevels?: HeadingDepth[]; // default: [1]
184
- skipParents?: Exclude<HeadingParent, "root">[]; // default: []
192
+ includeParents?: Test;
193
+ skipParents?: Test;
185
194
  exclude?: string | string[];
186
195
  prefix?: string;
196
+ after?: string;
187
197
  callback?: (toc: TocItem[]) => undefined;
188
198
  } as FlexibleTocOptions);
189
199
  ```
@@ -193,7 +203,13 @@ use(remarkFlexibleToc, {
193
203
  ```ts
194
204
  type GenerateTocItemsOptions = Pick<
195
205
  FlexibleTocOptions,
196
- "maxDepth" | "skipLevels" | "skipParents" | "exclude" | "prefix"
206
+ | "maxDepth"
207
+ | "skipLevels"
208
+ | "includeParents"
209
+ | "skipParents"
210
+ | "exclude"
211
+ | "prefix"
212
+ | "after"
197
213
  >;
198
214
 
199
215
  ```
@@ -257,9 +273,25 @@ use(remarkFlexibleToc, {
257
273
 
258
274
  Now, the TOC consists only the third level headings.
259
275
 
276
+ #### `includeParents`
277
+
278
+ It uses a [`unist-util-is`][unist-util-is] compatible **`Test`** to allow headings to be children of certain nodes.
279
+
280
+ The option has no default value, meaningly there is no parent restriction by default.
281
+
282
+ ```javascript
283
+ use(remarkFlexibleToc, {
284
+ includeParents: ["root", "listItem"];
285
+ });
286
+ ```
287
+
288
+ Now, only the headings whose immediate parent is the `root` or a `listItem` will be added into the TOC.
289
+
260
290
  #### `skipParents`
261
291
 
262
- By default it is an empty array `[]`. The array may contain the parent values `blockquote`, `footnoteDefinition`, `listItem`, `container`, `mdxJsxFlowElement`.
292
+ It uses a [`unist-util-is`][unist-util-is] compatible **`Test`** to disallow headings to be children of certain nodes.
293
+
294
+ The option has no default value, meaningly there is no parent to be skipped by default.
263
295
 
264
296
  ```javascript
265
297
  use(remarkFlexibleToc, {
@@ -269,6 +301,8 @@ use(remarkFlexibleToc, {
269
301
 
270
302
  Now, the headings in the `<blockquote>` will not be added into the TOC.
271
303
 
304
+ If `includeParents` and `skipParents` match the same parent, `skipParents` wins. The `root` is not protected specially and can also be skipped.
305
+
272
306
  #### `exclude`
273
307
 
274
308
  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 +329,22 @@ use(remarkFlexibleToc, {
295
329
  ```
296
330
  Now, all TOC items' `href`s will start with that prefix like `#text-prefix-the-subheading`.
297
331
 
332
+ #### `after`
333
+
334
+ It is a **string** option for indicating a heading section after which the TOC items will be generated.
335
+
336
+ 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.
337
+
338
+ The option has no default value.
339
+
340
+ ```javascript
341
+ use(remarkFlexibleToc, {
342
+ after: "(table[ -]of[ -])?contents?|toc";
343
+ });
344
+ ```
345
+
346
+ 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.
347
+
298
348
  #### `callback`
299
349
 
300
350
  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,16 +364,26 @@ Now, each time when you compile the source, the TOC will be logged into the cons
314
364
  ## A Table of Content (TOC) Item
315
365
 
316
366
  ```typescript
367
+ import type { PhrasingContent } from "mdast";
368
+
317
369
  type TocItem = {
318
370
  value: string; // heading text
371
+ content: PhrasingContent[]; // normalized rich heading content to be used safely inside a TOC link
319
372
  href: string; // produced uniquely by "github-slugger" using the value of the heading
320
373
  depth: HeadingDepth; // 1 | 2 | 3 | 4 | 5 | 6
321
374
  numbering: number[]; // explained below
322
375
  parent: HeadingParent; // "root"| "blockquote" | "footnoteDefinition" | "listItem" | "container" | "mdxJsxFlowElement"
376
+ parentPath: number[]; // child-index path from the MDAST root to the heading's immediate parent
323
377
  data?: Record<string, unknown>; // Other remark plugins may store custom data in "node.data.hProperties" like "id" etc.
324
378
  };
325
379
  ```
326
380
 
381
+ 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.
382
+
383
+ The `parentPath` identifies the heading's exact structural parent in the input MDAST tree by child indexes. A heading whose immediate parent is the root has `parentPath: []`. For example, if a heading is inside the second root child and that child is its immediate parent, the path is `[1]`; if its immediate parent is the first child of that node, the path is `[1, 0]`. The path is computed from the input MDAST structure before TOC filtering, so options such as `skipLevels`, `exclude`, `maxDepth`, and `after` do not renumber or rebase it.
384
+
385
+ Regional or section-specific tables of contents can be implemented using `parentPath`.
386
+
327
387
  > [!NOTE]
328
388
  > 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
389
 
@@ -352,6 +412,7 @@ The `github-slugger` produces unique links with using a counter mechanism intern
352
412
  href: "#section",
353
413
  numbering: [1, 1],
354
414
  parent: "root",
415
+ parentPath: [],
355
416
  value: "Section",
356
417
  },
357
418
  {
@@ -359,6 +420,7 @@ The `github-slugger` produces unique links with using a counter mechanism intern
359
420
  href: "#subheading",
360
421
  numbering: [1, 1, 1],
361
422
  parent: "root",
423
+ parentPath: [],
362
424
  value: "Subheading",
363
425
  },
364
426
  {
@@ -366,6 +428,7 @@ The `github-slugger` produces unique links with using a counter mechanism intern
366
428
  href: "#section-1",
367
429
  numbering: [1, 2],
368
430
  parent: "root",
431
+ parentPath: [],
369
432
  value: "Section",
370
433
  },
371
434
  {
@@ -373,6 +436,7 @@ The `github-slugger` produces unique links with using a counter mechanism intern
373
436
  href: "#subheading-1",
374
437
  numbering: [1, 2, 1],
375
438
  parent: "root",
439
+ parentPath: [],
376
440
  value: "Subheading",
377
441
  },
378
442
  ]
@@ -506,6 +570,7 @@ I also build low-level utilities and plugins for the Unified ecosystem that can
506
570
  [remark]: https://github.com/remarkjs/remark
507
571
  [remarkplugins]: https://github.com/remarkjs/remark/blob/main/doc/plugins.md
508
572
  [mdast]: https://github.com/syntax-tree/mdast
573
+ [unist-util-is]: https://github.com/syntax-tree/unist-util-is
509
574
  [rehype-slug]: https://github.com/rehypejs/rehype-slug
510
575
  [rehype-autolink-headings]: https://github.com/rehypejs/rehype-autolink-headings
511
576
 
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,10 +9,12 @@ 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[];
14
16
  parent: HeadingParent;
17
+ parentPath: number[];
15
18
  data?: {
16
19
  [PropertyName: string]: string | number | boolean | (string | number)[] | null | undefined;
17
20
  };
@@ -21,9 +24,11 @@ export type TocItem = {
21
24
  * tocRef (default: []) — another way of exposing the tocItems
22
25
  * 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
26
  * 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)
27
+ * includeParents — allow headings to be children of certain nodes; internally uses unist-util-is Test
28
+ * skipParents (default: []) — disallow headings to be children of certain nodes; internally uses unist-util-is Test
25
29
  * 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
30
  * prefix - the text that will be attached to headings as prefix, like "text-prefix-"
31
+ * after — heading to look for, wrapped in new RegExp('^(' + value + ')$', 'i'); the TOC items will be generated after that heading section
27
32
  * callback - It is a callback function to take the array of toc items as an argument
28
33
  */
29
34
  export type FlexibleTocOptions = {
@@ -31,12 +36,14 @@ export type FlexibleTocOptions = {
31
36
  tocRef?: TocItem[];
32
37
  maxDepth?: HeadingDepth;
33
38
  skipLevels?: HeadingDepth[];
34
- skipParents?: Exclude<HeadingParent, "root">[];
39
+ includeParents?: Test;
40
+ skipParents?: Test;
35
41
  exclude?: string | string[];
36
42
  prefix?: string;
43
+ after?: string;
37
44
  callback?: (toc: TocItem[]) => undefined;
38
45
  };
39
- export type GenerateTocItemsOptions = Pick<FlexibleTocOptions, "maxDepth" | "skipLevels" | "skipParents" | "exclude" | "prefix">;
46
+ export type GenerateTocItemsOptions = Pick<FlexibleTocOptions, "maxDepth" | "skipLevels" | "includeParents" | "skipParents" | "exclude" | "prefix" | "after">;
40
47
  export declare function generateTocItemsFromMdast(tree: Root, options?: GenerateTocItemsOptions): TocItem[];
41
48
  declare const RemarkFlexibleToc: Plugin<[FlexibleTocOptions?], Root>;
42
49
  export default RemarkFlexibleToc;
@@ -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,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAExF,MAAM,MAAM,aAAa,GACvB,MAAM,GAAG,YAAY,GAAG,oBAAoB,GAAG,UAAU,GAAG,WAAW,GAAG,mBAAmB,CAAC;AAEhG,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAEjD,MAAM,MAAM,OAAO,GAAG;IACpB,KAAK,EAAE,MAAM,CAAC;I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ACnB,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;AAqGF,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,EAAE,CA4FX;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,55 @@ function addNumbering(arr) {
47
48
  tocItem.numbering = numbering;
48
49
  }
49
50
  }
51
+ function createNodePathMap(tree) {
52
+ const paths = new WeakMap();
53
+ const visitNode = (node, path) => {
54
+ /* v8 ignore next -- @preserve */
55
+ if (!node || typeof node !== "object")
56
+ return;
57
+ paths.set(node, path);
58
+ const children = node.children;
59
+ if (!Array.isArray(children))
60
+ return;
61
+ children.forEach((child, index) => {
62
+ visitNode(child, [...path, index]);
63
+ });
64
+ };
65
+ visitNode(tree, []);
66
+ return paths;
67
+ }
68
+ function copyTocContent(nodes) {
69
+ const results = [];
70
+ for (const node of nodes) {
71
+ if (node.type === "footnoteReference")
72
+ continue;
73
+ if (node.type === "link" || node.type === "linkReference") {
74
+ results.push(...copyTocContent(node.children));
75
+ continue;
76
+ }
77
+ const copy = structuredClone(node);
78
+ delete copy.position;
79
+ if ("children" in copy) {
80
+ copy.children = copyTocContent(copy.children);
81
+ }
82
+ results.push(copy);
83
+ }
84
+ return results;
85
+ }
50
86
  export function generateTocItemsFromMdast(tree, options) {
51
87
  const settings = Object.assign({}, DEFAULT_SETTINGS, options);
52
88
  const exludeRegexFilter = settings.exclude &&
53
89
  (Array.isArray(settings.exclude)
54
90
  ? new RegExp("^(" + settings.exclude.join("|") + ")$", "i")
55
91
  : new RegExp("^(" + settings.exclude + ")$", "i"));
92
+ const afterRegexFilter = settings.after && new RegExp("^(" + settings.after + ")$", "i");
93
+ const includeParentsFilter = settings.includeParents && convert(settings.includeParents);
94
+ const skipParentsFilter = settings.skipParents && convert(settings.skipParents);
56
95
  const slugger = new GithubSlugger();
96
+ const parentPaths = createNodePathMap(tree);
57
97
  const tocItems = [];
98
+ let afterHeadingDepth;
99
+ let afterSectionEnded = !afterRegexFilter;
58
100
  visit(tree, "heading", (_node, _index, _parent) => {
59
101
  /* v8 ignore next -- @preserve */
60
102
  if (!_parent || typeof _index === "undefined")
@@ -63,14 +105,35 @@ export function generateTocItemsFromMdast(tree, options) {
63
105
  const value = toString(_node, { includeImageAlt: false });
64
106
  let href = `#${settings.prefix ?? ""}${slugger.slug(value)}`;
65
107
  const parent = _parent.type;
108
+ /* v8 ignore next -- @preserve */
109
+ const parentPath = parentPaths.get(_parent) ?? [];
110
+ const parentIncluded = !includeParentsFilter || includeParentsFilter(_parent);
111
+ const parentSkipped = !!skipParentsFilter && skipParentsFilter(_parent);
112
+ const parentAllowed = parentIncluded && !parentSkipped;
113
+ // after check
114
+ if (afterRegexFilter) {
115
+ if (!afterHeadingDepth) {
116
+ if (parentAllowed && afterRegexFilter.test(value))
117
+ afterHeadingDepth = depth;
118
+ return CONTINUE;
119
+ }
120
+ if (!afterSectionEnded) {
121
+ if (!parentAllowed || depth > afterHeadingDepth)
122
+ return CONTINUE;
123
+ afterSectionEnded = true;
124
+ }
125
+ }
66
126
  // maxDepth check
67
127
  if (depth > settings.maxDepth)
68
128
  return CONTINUE;
69
129
  // skipLevels check
70
130
  if (settings.skipLevels.includes(depth))
71
131
  return CONTINUE;
132
+ // includeParents check
133
+ if (!parentIncluded)
134
+ return CONTINUE;
72
135
  // skipParents check
73
- if (parent !== "root" && settings.skipParents.includes(parent))
136
+ if (parentSkipped)
74
137
  return CONTINUE;
75
138
  // exclude check
76
139
  if (exludeRegexFilter && exludeRegexFilter.test(value))
@@ -85,10 +148,12 @@ export function generateTocItemsFromMdast(tree, options) {
85
148
  href = `#${data["id"]}`;
86
149
  tocItems.push({
87
150
  value,
151
+ content: copyTocContent(_node.children),
88
152
  href,
89
153
  depth,
90
154
  numbering: [],
91
155
  parent,
156
+ parentPath,
92
157
  ...(data && { data }),
93
158
  });
94
159
  return CONTINUE;
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,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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 { 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;AA0DhD,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,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,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 parentPath: number[];\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 createNodePathMap(tree: Root): WeakMap<object, number[]> {\n const paths = new WeakMap<object, number[]>();\n\n const visitNode = (node: unknown, path: number[]) => {\n /* v8 ignore next -- @preserve */\n if (!node || typeof node !== \"object\") return;\n\n paths.set(node, path);\n\n const children = (node as { children?: unknown }).children;\n if (!Array.isArray(children)) return;\n\n (children as unknown[]).forEach((child, index) => {\n visitNode(child, [...path, index]);\n });\n };\n\n visitNode(tree, []);\n return paths;\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 parentPaths = createNodePathMap(tree);\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 /* v8 ignore next -- @preserve */\n const parentPath = parentPaths.get(_parent) ?? [];\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 parentPath,\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.8",
3
+ "version": "1.3.2",
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": {