Skip to content

Commit 79b1ec7

Browse files
committed
feat: fill toc in middleware
1 parent 0fdc189 commit 79b1ec7

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { sequence } from 'astro/middleware';
22
import { onRequest as csp } from './csp';
3+
import { onRequest as toc } from './table-of-contents';
34

4-
export const onRequest = sequence(csp);
5+
export const onRequest = sequence(csp, toc);
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import * as cheerio from 'cheerio';
2+
3+
interface Item {
4+
label: string;
5+
id?: string;
6+
}
7+
8+
function buildTocItem(item: Item) {
9+
return item.id ? `<li><a href="#${item.id}">${item.label}</a></li>` : `<li>${item.label}</li>`;
10+
}
11+
12+
function buildToc(items: Item[]) {
13+
return items.map(buildTocItem).join('');
14+
}
15+
16+
export async function onRequest(context, next) {
17+
const response = await next();
18+
const html = await response.text();
19+
const $ = cheerio.load(html);
20+
21+
const tableOfContentsElement = $('ma-table-of-contents');
22+
23+
if (tableOfContentsElement.length) {
24+
const h2List = [];
25+
26+
$('main h2').each((index, element) => {
27+
const label = $(element).text();
28+
const id = $(element).attr('id');
29+
if (label.toLowerCase() !== 'inhoudsopgave') {
30+
h2List.push({ label, id });
31+
}
32+
});
33+
34+
$(tableOfContentsElement).find('ul').append(buildToc(h2List));
35+
}
36+
37+
return new Response($.html(), {
38+
status: 200,
39+
headers: response.headers,
40+
});
41+
}

0 commit comments

Comments
 (0)