1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | const htmlparser2_1 = require("htmlparser2");
|
6 | const escape_html_1 = __importDefault(require("./escape_html"));
|
7 | const nonWord = /^\s*[^a-zA-Z0-9]\s*$/;
|
8 | const parseHtml = (html) => {
|
9 | const handler = new htmlparser2_1.DomHandler(null, {});
|
10 | new htmlparser2_1.Parser(handler, {}).end(html);
|
11 | return handler.dom;
|
12 | };
|
13 | const getId = ({ attribs = {}, parent }) => {
|
14 | return attribs.id || (!parent ? '' : getId(parent));
|
15 | };
|
16 |
|
17 |
|
18 |
|
19 | const isUnnumbered = ({ attribs = {} }) => {
|
20 | return attribs['data-toc-unnumbered'] === 'true';
|
21 | };
|
22 | function tocObj(str, options = {}) {
|
23 | const { min_depth, max_depth } = Object.assign({
|
24 | min_depth: 1,
|
25 | max_depth: 6
|
26 | }, options);
|
27 | const headingsSelector = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].slice(min_depth - 1, max_depth);
|
28 | const headings = htmlparser2_1.DomUtils.find(element => 'tagName' in element && headingsSelector.includes(element.tagName), parseHtml(str), true, Infinity);
|
29 | const headingsLen = headings.length;
|
30 | if (!headingsLen)
|
31 | return [];
|
32 | const result = [];
|
33 | for (let i = 0; i < headingsLen; i++) {
|
34 | const el = headings[i];
|
35 | const level = +el.name[1];
|
36 | const id = getId(el);
|
37 | const unnumbered = isUnnumbered(el);
|
38 | let text = '';
|
39 | for (const element of el.children) {
|
40 | const elText = htmlparser2_1.DomUtils.textContent(element);
|
41 |
|
42 |
|
43 |
|
44 | if (!('name' in element) || element.name !== 'a' || !nonWord.test(elText)) {
|
45 | text += (0, escape_html_1.default)(elText);
|
46 | }
|
47 | }
|
48 | if (!text)
|
49 | text = (0, escape_html_1.default)(htmlparser2_1.DomUtils.textContent(el));
|
50 | const res = { text, id, level };
|
51 | if (unnumbered)
|
52 | res.unnumbered = true;
|
53 | result.push(res);
|
54 | }
|
55 | return result;
|
56 | }
|
57 | module.exports = tocObj;
|
58 |
|
\ | No newline at end of file |