@@ -21,8 +21,19 @@ export function toc(this: Processor, opts?: Options): Transformer {
21
21
throw new Error ( "`root` is not a Root hast node." ) ;
22
22
}
23
23
24
- // Find the <main> or <body> element
25
- let [ mainNode , mainParent ] = findMainNode ( root ) ;
24
+ let mainNode : Element | undefined ;
25
+ let mainParent : Parent | undefined ;
26
+
27
+ if ( options . placeholder ) {
28
+ // Find the <target> element if option is given
29
+ [ mainNode , mainParent ] = findPlaceholderNode ( root , options . placeholder ) ;
30
+
31
+ if ( ! mainNode || ! mainParent ) { return root ; }
32
+ }
33
+ else {
34
+ // Find the <main> or <body> element
35
+ [ mainNode , mainParent ] = findMainNode ( root ) ;
36
+ }
26
37
27
38
// Find all heading elements
28
39
let headings = findHeadings ( mainNode , options ) ;
@@ -33,16 +44,9 @@ export function toc(this: Processor, opts?: Options): Transformer {
33
44
// Allow the user to customize the table of contents before we add it to the page
34
45
let node = customizationHooks ( tocNode , options ) ;
35
46
36
- // Find the <target> element is option is given
37
- let target : Element | undefined ;
38
- let parent : Parent | undefined ;
39
- if ( options . placeholder ) {
40
- [ target , parent ] = findPlaceholderNode ( root , options . placeholder ) ;
41
- }
42
-
43
47
if ( node ) {
44
48
// Add the table of contents to the <main> element
45
- insertTOC ( node , target || mainNode , parent || mainParent , { ...options , replace : ! ! target && ! ! parent } ) ;
49
+ insertTOC ( node , mainNode , mainParent , { ...options , replace : ! ! options . placeholder } ) ;
46
50
}
47
51
48
52
return root ;
0 commit comments