File tree Expand file tree Collapse file tree 2 files changed +43
-1
lines changed
packages/website/src/middleware Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change 11import { sequence } from 'astro/middleware' ;
22import { 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 ) ;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments