Generate post toc on build time

This commit is contained in:
DefectingCat
2022-08-19 10:50:02 +08:00
parent 03d6fd1a0f
commit f6cb2a8f74
7 changed files with 114 additions and 75 deletions

View File

@ -4,7 +4,7 @@ import matter from 'gray-matter';
import { MyMatters, Post } from 'types';
import { sortByDate } from 'lib/utils';
const dataPath = 'data/posts';
export const dataPath = 'data/posts';
/**
* Read post meta info with gray-matter.

View File

@ -33,3 +33,45 @@ export const getHeadings = (source: string) => {
};
});
};
export type SingleToc = {
level: number;
head: string;
link: string;
children: SingleToc[];
};
export const generateToc = (source: string) => {
const regex = /^#{2,3}(?!#)(.*)/gm;
let lastH2: SingleToc | null = null;
const toc: SingleToc[] = [];
source.match(regex)?.map((h) => {
const heading = h.split(' ');
const level = heading[0].length;
const head = h.substring(level + 1);
switch (level) {
case 2: {
lastH2 = {
level,
head,
link: `#${head.toLocaleLowerCase().replace(/ /g, '-')}`,
children: [],
};
toc.push(lastH2);
break;
}
case 3: {
lastH2?.children.push({
level,
head,
link: `#${head.toLocaleLowerCase().replace(/ /g, '-')}`,
children: [],
});
break;
}
}
});
return toc;
};