Files
lixiyu-net/lib/toc.ts

24 lines
707 B
TypeScript
Raw Normal View History

import type { TPostTOCItem } from "@/types/docs.type";
2023-12-25 17:21:39 +08:00
import { JSDOM } from "jsdom";
/**
* Generate the Table Of Content List by html code.
* It supports h1-h6 level headings at most.
* @param htmlCode
* @returns
*/
2024-04-03 22:08:27 +08:00
export const makeTOCTree = (htmlCode: string) => {
2023-12-25 17:21:39 +08:00
const doc_dom = new JSDOM(htmlCode);
const all_headers = doc_dom.window.document.querySelectorAll("h1,h2,h3,h4,h5,h6");
const result: TPostTOCItem[] = [];
2023-12-25 17:21:39 +08:00
for (let i = 0; i < all_headers.length; i++) {
const level = Number.parseInt(all_headers[i].tagName.replace("H", ""));
2023-12-25 17:21:39 +08:00
result.push({
level: level,
anchorId: all_headers[i].id,
title: all_headers[i].textContent!,
});
}
return result;
};