added ToC min+maxLevel (#1258)

Added option to ToC to define minimum and maximum displayed levels.
pull/1263/head
Nico S. 2025-02-23 20:45:58 +01:00 committed by GitHub
parent 58556f8e6d
commit 60dea56020
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 8 deletions

View File

@ -16,6 +16,8 @@ type TocConfig = {
maxHeaders?: number;
header?: boolean;
headerText?: string;
maxLevel?: number;
minLevel?: number;
};
export async function widget(
@ -65,16 +67,18 @@ export async function widget(
}
// console.log("Headers", headers);
// Adjust level down if only sub-headers are used
const minLevel = headers.reduce(
let minLevel = headers.reduce(
(min, header) => Math.min(min, header.level),
6,
);
const renderedMd = headerText +
headers.map((header) =>
`${
" ".repeat((header.level - minLevel) * 2)
}* [[${page}@${header.pos}|${header.name}]]`
).join("\n");
if (config.minLevel && config.minLevel > minLevel) { minLevel = config.minLevel ;}
let renderedMd = headerText + "\n";
for (const header of headers) {
if (config.maxLevel && header.level > config.maxLevel || (config.minLevel && header.level < config.minLevel)) { continue; }
renderedMd = renderedMd + " ".repeat((header.level - minLevel) * 2) + "[[" + page + "@" + header.pos + "|" + header.name + "]]\n";
}
// console.log("Markdown", renderedMd);
return {
markdown: renderedMd,

View File

@ -19,6 +19,8 @@ In the body of the `toc` code widget you can configure a few options:
* `headerText`: by default "# Table of Contents\n". Change it to change the rendering of this header
* `minHeaders`: only renders a ToC if the number of headers in the current page exceeds this number, otherwise renders an empty widget
* `maxHeaders`: only renders a ToC if the number of headers in the current page is below this number, otherwise renders an empty widget
* `minLevel`: only renders a ToC for headers below that level (if you do not want to display e.g. the first header)
* `maxLevel`: only renders a ToC down to this level (e.g. if you have too many sublevels.)
Example:
```toc
@ -26,4 +28,4 @@ header: false
minHeaders: 1
```
Want to add a table of contents to all your pages automatically? You can — thats functionality available via the [[Library/Core]] library.
Want to add a table of contents to all your pages automatically? You can — thats functionality available via the [[Library/Core]] library.