diff --git a/src/options.ts b/src/options.ts index b82f0f1..4d40a02 100644 --- a/src/options.ts +++ b/src/options.ts @@ -32,9 +32,9 @@ export interface Options { /** * The optional placeholder string to replace with the table of contents. * - * Defaults to "{{TOC}}"; + * Defaults to `undefined`; */ - placeholder?: string; + placeholder?: string | undefined; /** * HTML heading elements to include in the table of contents. @@ -113,7 +113,7 @@ export class NormalizedOptions { public readonly position: InsertPosition; public readonly headings: HeadingTagName[]; public readonly cssClasses: Required; - public readonly placeholder?: string; + public readonly placeholder?: string | undefined; public readonly customizeTOC?: CustomizationHook; public readonly customizeTOCItem?: CustomizationHook; @@ -125,7 +125,7 @@ export class NormalizedOptions { this.nav = options.nav === undefined ? true : Boolean(options.nav); this.position = options.position || "afterbegin"; - this.placeholder = options.placeholder || "{{TOC}}"; + this.placeholder = options.placeholder; this.headings = options.headings || ["h1", "h2", "h3", "h4", "h5", "h6"]; this.cssClasses = { toc: cssClasses.toc === undefined ? "toc" : cssClasses.toc, diff --git a/src/rehype-toc.ts b/src/rehype-toc.ts index 7ed8b77..ffa5634 100644 --- a/src/rehype-toc.ts +++ b/src/rehype-toc.ts @@ -21,8 +21,19 @@ export function toc(this: Processor, opts?: Options): Transformer { throw new Error("`root` is not a Root hast node."); } - // Find the
or element - let [mainNode, mainParent] = findMainNode(root); + let mainNode: Element | undefined; + let mainParent: Parent | undefined; + + if (options.placeholder) { + // Find the element if option is given + [mainNode, mainParent] = findPlaceholderNode(root, options.placeholder); + + if (!mainNode || !mainParent) { return root; } + } + else { + // Find the
or element + [mainNode, mainParent] = findMainNode(root); + } // Find all heading elements let headings = findHeadings(mainNode, options); @@ -33,16 +44,9 @@ export function toc(this: Processor, opts?: Options): Transformer { // Allow the user to customize the table of contents before we add it to the page let node = customizationHooks(tocNode, options); - // Find the element is option is given - let target: Element | undefined; - let parent: Parent | undefined; - if (options.placeholder) { - [target, parent] = findPlaceholderNode(root, options.placeholder); - } - if (node) { // Add the table of contents to the
element - insertTOC(node, target || mainNode, parent || mainParent, { ...options, replace: !!target && !!parent }); + insertTOC(node, mainNode, mainParent, { ...options, replace: !!options.placeholder }); } return root;