Skip to content

Instantly share code, notes, and snippets.

@eric-burel
Created July 11, 2022 15:44
Show Gist options
  • Save eric-burel/e73f882169fc50ab734b4f0acceb9ec8 to your computer and use it in GitHub Desktop.
Save eric-burel/e73f882169fc50ab734b4f0acceb9ec8 to your computer and use it in GitHub Desktop.
Generate toc from sections a Slidev app - to be included in your index.html
/**
* Run this script manually in the console and copy-paste the result to generate
* a TOC based on "section" layout, instead of markdown titles (that are not helpful here)
*
* NOTE: this script is loaded in index.html,
* so you can call generateTocFromSections easily from the slidev app, in the browser console
*
* NOTE: this could also be adapted with Cheerio or an HTML/md parser to parse the markdown directly?
*/
function generateTocFromSections() {
// get all sections
const sectionElems = document.querySelectorAll(".slidev-layout.section");
// get title
const parsedSections = [];
sectionElems.forEach((sectionElem) => {
// Get the section slide number in order to generate links
const classes = [...sectionElem.classList];
const pageNbClass = classes.find((c) => c.startsWith("slidev-page-"));
const pageNb = pageNbClass.match(/slidev-page-(?<pgnumber>\d+)/)?.groups?.[
"pgnumber"
];
// TODO: we don't use pageNb yet but we could use Slidev Link component
const titleElem = sectionElem.querySelector("h1");
parsedSections.push({
titleElem: titleElem,
title: titleElem.getInnerHTML(),
pageNb: pageNb,
});
});
// Render
const sectionTitles = [];
parsedSections.forEach(({ title, pageNb, titleElem }, idx) => {
// this text can be pasted in a slide
sectionTitles.push(`<h2><Link to="${pageNb}">${
idx + 1
}. ${title}</Link></h2>
`);
});
console.log(...sectionTitles);
console.log("^ Copy paste this in your slides ^");
}
@eric-burel
Copy link
Author

Result is like this:
image

You can copy paste this code in your slide

Update is manual sadly but at least it works ok.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment