UNPKG

2.31 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5const htmlparser2_1 = require("htmlparser2");
6const escape_html_1 = __importDefault(require("./escape_html"));
7const nonWord = /^\s*[^a-zA-Z0-9]\s*$/;
8const parseHtml = (html) => {
9 const handler = new htmlparser2_1.DomHandler(null, {});
10 new htmlparser2_1.Parser(handler, {}).end(html);
11 return handler.dom;
12};
13const getId = ({ attribs = {}, parent }) => {
14 return attribs.id || (!parent ? '' : getId(parent));
15};
16/**
17 * Identify a heading that to be unnumbered or not.
18 */
19const isUnnumbered = ({ attribs = {} }) => {
20 return attribs['data-toc-unnumbered'] === 'true';
21};
22function 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 // Skip permalink symbol wrapped in <a>
42 // permalink is a single non-word character, word = [a-Z0-9]
43 // permalink may be wrapped in whitespace(s)
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}
57module.exports = tocObj;
58//# sourceMappingURL=toc_obj.js.map
\No newline at end of file