training-kit: Searching the Slides from the Starlight Search Box with Pagefind
How training-kit makes the slides of a Slidev deck searchable from the Starlight workshops site: one Pagefind record per slide, built from the Markdown, then merged into the site's own index.
In a previous article, I presented training-kit, the tool I use to build my trainings: a folder of numbered slides becomes a Slidev deck, a folder of numbered workshops becomes a Starlight site, and both are published side by side.
During a training, learners often ask for something they saw on a slide: “where was the slide about computed?”. The workshops site has a search box, so that’s where they type it. But until recently, the search only knew the workshop pages. The slides were not in it.
In this article, I’ll explain how I made the slides searchable from the Starlight search box.
Why the Slides Were Not Searchable
Starlight’s search is powered by Pagefind. After astro build, Pagefind crawls the generated HTML files, extracts their text, and writes a static index in a pagefind/ folder. In the browser, the search box downloads only the parts of the index it needs. There is no server and no external service.
The deck is built separately by Slidev, into build/slides/. So the first idea is to let Pagefind crawl it as well. It doesn’t work: Slidev builds a single-page application. Its index.html is an empty shell, and the slides are rendered in the browser by JavaScript. Pagefind reads HTML, not JavaScript, so there is no text for it to index.
There were other options: prerendering every slide in a headless browser, or exporting the deck to HTML before indexing it. Both are slow and fragile. But training-kit already has something better than the rendered HTML: the Markdown sources of the slides.
The Plan: One Record per Slide, Merged into the Site’s Index
The solution has three parts:
- During the build, read the deck’s Markdown with Slidev’s own parser, and turn every slide into a search record: its text, its title, and the URL of its route (
/slides/<n>). - Write these records into a separate Pagefind index, with Pagefind’s Node.js API, in
build/slides/pagefind/. - Tell Starlight to merge this index into its own, so a single search box looks in both.
build/
pagefind/ the index of the workshops site, crawled by Starlight
slides/
index.html the Slidev single-page app
pagefind/ the index of the slides, written from the Markdown
Step 1: Turning Slides into Records
To read the deck, I use @slidev/parser, the parser of Slidev itself. That way, the slides training-kit indexes are the same slides Slidev builds, in the same order. Hidden slides (hide: true) are dropped by the parser, like Slidev drops them from the routes, so the numbers stay correct.
import { dirname } from "node:path";
import { load } from "@slidev/parser/fs";
export async function slideRecords({ deckFile, base, lang }) {
const { slides } = await load(dirname(deckFile), deckFile);
return slides.map((slide, index) => {
const no = index + 1;
return {
url: `${base}${no}`,
content: plainText(slide.content),
language: lang,
meta: {
title: slide.title ? `Slide ${no} — ${slide.title}` : `Slide ${no}`,
source: "Slides",
},
};
});
}
Each record has:
- a
url: the route of the slide in the deck,/slides/1,/slides/2… Clicking a result opens the deck directly on the right slide; - a
content: the text of the slide, without its Markdown; - a
meta.title: the title shown in the results, with the slide number; - a
meta.source: Pagefind shows any extra meta as a tag under the result. “Source: Slides” tells a slide apart from a page of the site.
Extracting the Text
A slide’s content is Markdown, and the index should only contain words. Instead of writing my own Markdown stripper, I render the Markdown to HTML with marked, then remove the tags:
import { marked } from "marked";
// Inside a sentence: removed without leaving a space.
const INLINE_TAG = /<\/?(a|abbr|b|code|del|em|i|kbd|mark|s|small|span|strong|sub|sup|u)\b[^>]*>/gi;
function plainText(markdown) {
return marked
.parse(markdown)
.replace(INLINE_TAG, "")
.replace(/<[^>]*>/g, " ")
.replace(/&(amp|lt|gt|quot|#39);/g, (entity) => ENTITIES[entity])
.replace(/\s+/g, " ")
.trim();
}
There is one detail: inline tags and block tags are not removed the same way. A block tag (<p>, <h1>, <li>) is replaced with a space, so two paragraphs don’t stick together. An inline tag (<strong>, <code>, <a>) is removed without a space, otherwise Hello **world**, would become Hello world ,.
For example, this chapter:
# Intro
Hello **world**, see [the docs](https://x.y)
---
## Second
```js
const x = 1;
```
gives these records (the cover of the deck is slide 1):
[
{
url: "/slides/2",
content: "Intro Hello world, see the docs",
meta: { title: "Slide 2 — Intro", source: "Slides" },
},
{
url: "/slides/3",
content: "Second const x = 1;",
meta: { title: "Slide 3 — Second", source: "Slides" },
},
];
The code blocks are kept on purpose: in a technical training, learners often search for an API name they saw in an example.
Step 2: Writing the Index with Pagefind’s Node.js API
Pagefind is usually used as a CLI that crawls a folder. But it also has a Node.js API, which can index records that don’t come from any HTML file: addCustomRecord.
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { close, createIndex } from "pagefind";
export async function writeSlidesIndex({ deckFile, base, lang, outDir }) {
const records = await slideRecords({ deckFile, base, lang });
const { index, errors } = await createIndex({ forceLanguage: lang });
try {
if (errors.length) throw new Error(`pagefind: ${errors.join("; ")}`);
for (const record of records) {
const added = await index.addCustomRecord(record);
if (added.errors.length) throw new Error(`pagefind: ${added.errors.join("; ")}`);
}
const { files, errors: getErrors } = await index.getFiles();
if (getErrors.length) throw new Error(`pagefind: ${getErrors.join("; ")}`);
for (const { path, content } of files) {
const target = join(outDir, path);
await mkdir(dirname(target), { recursive: true });
await writeFile(target, content);
}
return { pages: records.length };
} finally {
await close();
}
}
Three things are worth explaining.
forceLanguage: Pagefind keeps one index per language, and only merges indexes of the same language. The language of the training comes from its configuration, and the same value is set on the Starlight site. Without it, a French training would produce an index that the French site ignores.
getFiles() instead of writeFiles(): the API has a writeFiles() method, and it was my first version. But from time to time, the build produced an empty pagefind-entry.json, and the search of the slides was broken. The promise returned by writeFiles() resolves before the Pagefind backend has flushed every file, and close(), called right after, stops the backend in the middle of a write. Since then, training-kit takes the files in memory with getFiles() and writes them itself. When the function returns, every file is on disk.
close() in the finally: Pagefind’s Node.js API starts a backend process, and without close(), the build never exits, even when the indexing fails.
Step 3: Merging the Index into Starlight
Pagefind can search several indexes at the same time with mergeIndex, and Starlight passes its pagefind option to Pagefind. training-kit generates the astro.config.mjs of the site, so it only has to add one line when the slides index exists:
starlight({
title: "Advanced Vue.js",
// ...
pagefind: {
mergeIndex: [{ bundlePath: "/slides/pagefind/", baseUrl: "/" }],
},
});
The baseUrl: '/' is the trap here. By default, Pagefind prefixes the URLs of a merged index with the folder of that index. The records already contain /slides/2, so without this option the links would become /slides/slides/2, and every result would lead to a 404.
Keeping the Build Robust
The search of the slides is a nice addition, but it should never break a training. In the build, the index is written right after the deck, as a non-fatal step: if something fails, the build reports it and carries on without it.
await nonFatal(
"the search index of the slides",
async () => {
const { pages } = await writeSlidesIndex({
deckFile: file,
base: "/slides/",
lang: config.lang,
outDir: join(out, "slides", "pagefind"),
});
log(`✔ slides/pagefind/ ${pages} slides searchable from the site`);
},
log,
);
Then, the site only adds the mergeIndex option when the index is really on disk:
const { siteDir } = await writeSite(config, {
downloadsDir,
// `--only site` keeps the deck of a previous build, and its index with it.
slidesSearch: existsSync(join(out, "slides", "pagefind", "pagefind-entry.json")),
});
If the index was not written, the site keeps its own search, and the search box doesn’t try to load a bundle that doesn’t exist. And with training-kit build --only site, which rebuilds the site on top of a previous build, the existing index is reused.
Testing It
Everything is covered by tests with Vitest, on real temporary decks, without mocks:
- one record per slide, with its route, its text without the Markdown, and the “Slides” tag;
- a hidden slide is not searchable, and the next slide takes its number;
- a slide without a heading is named by its number alone;
- the index really is written:
pagefind-entry.jsonexists and counts the expected number of pages; - the generated
astro.config.mjsis a valid module, contains themergeIndexwithbaseUrl: '/'when the index exists, and doesn’t contain it otherwise.
Conclusion
The slides were not searchable because Slidev builds a single-page application, and Pagefind needs HTML. Instead of rendering the deck to give Pagefind something to crawl, training-kit indexes the Markdown sources directly with addCustomRecord, and Starlight merges the result with mergeIndex.
Now, when a learner types computed in the search box of the workshops site, the results show the workshop pages and the slides, each with its number, and a click opens the deck on the right slide.
The whole feature is about a hundred lines of code, and it comes for free in every training built with training-kit. To try it:
npm create training-kit my-training
cd my-training
npm install
npm run build