1
1
/**
2
- * @typedef {import('mdast').Root|import('mdast').Content } Node
2
+ * @typedef {import('mdast').Root } Root
3
+ * @typedef {import('mdast').Content } Content
3
4
* @typedef {import('mdast').Heading } Heading
4
5
*/
5
6
7
+ /**
8
+ * @typedef {Content | Root } Node
9
+ */
10
+
6
11
import { visit } from 'unist-util-visit'
7
12
8
13
const max = 6
@@ -11,19 +16,27 @@ const max = 6
11
16
* Make sure that there is only one top-level heading in the document by
12
17
* adjusting headings depths accordingly.
13
18
*
14
- * @template {Node} T
15
- * @param {T } tree
16
- * @returns {T }
19
+ * @template {Node} Tree
20
+ * Node type.
21
+ * @param {Tree } tree
22
+ * Tree to change.
23
+ * @returns {Tree }
24
+ * Given, modified, `tree`.
17
25
*/
26
+ // To do: next major: don’t return `tree`.
18
27
export function normalizeHeadings ( tree ) {
19
- /** @type {boolean|undefined } */
28
+ /** @type {Array<Heading> } */
29
+ const all = [ ]
30
+ /** @type {boolean | undefined } */
20
31
let multiple
21
- /** @type {Heading| undefined } */
32
+ /** @type {Heading | undefined } */
22
33
let first
23
- /** @type {Heading| undefined } */
34
+ /** @type {Heading | undefined } */
24
35
let title
25
36
26
37
visit ( tree , 'heading' , ( node ) => {
38
+ all . push ( node )
39
+
27
40
if ( ! first ) {
28
41
first = node
29
42
}
@@ -44,11 +57,13 @@ export function normalizeHeadings(tree) {
44
57
45
58
// If there are multiple titles.
46
59
if ( multiple ) {
47
- visit ( tree , 'heading' , ( node ) => {
48
- if ( node !== title && node . depth < max ) {
49
- node . depth ++
60
+ let index = - 1
61
+ while ( ++ index < all . length ) {
62
+ const heading = all [ index ]
63
+ if ( heading !== title && heading . depth < max ) {
64
+ heading . depth ++
50
65
}
51
- } )
66
+ }
52
67
}
53
68
54
69
return tree
0 commit comments