@@ -21,8 +21,19 @@ export function toc(this: Processor, opts?: Options): Transformer {
2121 throw new Error ( "`root` is not a Root hast node." ) ;
2222 }
2323
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+ }
2637
2738 // Find all heading elements
2839 let headings = findHeadings ( mainNode , options ) ;
@@ -33,16 +44,9 @@ export function toc(this: Processor, opts?: Options): Transformer {
3344 // Allow the user to customize the table of contents before we add it to the page
3445 let node = customizationHooks ( tocNode , options ) ;
3546
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-
4347 if ( node ) {
4448 // 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 } ) ;
4650 }
4751
4852 return root ;
0 commit comments