Skip to content

Commit

Permalink
refactor(toc_helper): utilize tocObj
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Dec 20, 2019
1 parent bf30257 commit df7ebcb
Showing 1 changed file with 13 additions and 27 deletions.
40 changes: 13 additions & 27 deletions lib/plugins/helper/toc.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,29 @@
'use strict';

const { escapeHTML } = require('hexo-util');
const { DomHandler, DomUtils, Parser } = require('htmlparser2');

const parseHtml = (html) => {
const handler = new DomHandler(null, {});
new Parser(handler, {}).end(html);
return handler.dom;
};
const { tocObj } = require('hexo-util');

function tocHelper(str, options = {}) {
const dom = parseHtml(str);
options = Object.assign({
max_depth: 6,
class: 'toc',
list_number: true
}, options);

const headingsMaxDepth = Object.prototype.hasOwnProperty.call(options, 'max_depth') ? options.max_depth : 6;
const headingsSelector = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].slice(0, headingsMaxDepth).join(',');
const data = tocObj(str, { max_depth: options.max_depth });

const headings = DomUtils.find(el => headingsSelector.includes(el.tagName), dom, true);
if (!data.length) return '';

if (!headings.length) return '';
const className = options.class;
const listNumber = options.list_number;

const className = options.class || 'toc';
const listNumber = Object.prototype.hasOwnProperty.call(options, 'list_number') ? options.list_number : true;
let result = `<ol class="${className}">`;
const lastNumber = [0, 0, 0, 0, 0, 0];
let firstLevel = 0;
let lastLevel = 0;

function getId(ele) {
const { id } = ele.attribs;
const { parent } = ele;
return id || (parent.length < 1 ? null : getId(parent));
}

const headingLen = headings.length;
for (let i = 0; i < headingLen; i++) {
const el = headings[i];
const level = +el.name[1];
const id = getId(el);
const text = escapeHTML(DomUtils.getText(el));
for (let i = 0, len = data.length; i < len; i++) {
const el = data[i];
const { level, id, text } = el;

lastNumber[level - 1]++;

Expand Down

0 comments on commit df7ebcb

Please sign in to comment.