Skip to content

Commit

Permalink
refactor(toc): avoid using htmlTag (#4183)
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Mar 12, 2020
1 parent 0fd5736 commit d835578
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions lib/plugins/helper/toc.js
@@ -1,6 +1,6 @@
'use strict';

const { htmlTag, tocObj } = require('hexo-util');
const { tocObj, escapeHTML, encodeURL } = require('hexo-util');

function tocHelper(str, options = {}) {
options = Object.assign({
Expand All @@ -14,18 +14,19 @@ function tocHelper(str, options = {}) {

if (!data.length) return '';

const className = options.class;
const className = escapeHTML(options.class);
const listNumber = options.list_number;

let result = htmlTag('ol', { class: className });
let result = `<ol class="${className}">`;

const lastNumber = [0, 0, 0, 0, 0, 0];
let firstLevel = 0;
let lastLevel = 0;

for (let i = 0, len = data.length; i < len; i++) {
const el = data[i];
const { level, id, text } = el;
const href = id ? `#${id}` : id;
const href = id ? `#${encodeURL(id)}` : null;

lastNumber[level - 1]++;

Expand All @@ -39,19 +40,24 @@ function tocHelper(str, options = {}) {
}

if (level > lastLevel) {
result += htmlTag('ol', { class: `${className}-child` });
result += `<ol class="${className}-child">`;
} else {
result += '</li>';
}
} else {
firstLevel = level;
}

result += htmlTag('li', { class: `${className}-item ${className}-level-${level}` });
result += htmlTag('a', { class: `${className}-link`, href });
result += `<li class="${className}-item ${className}-level-${level}">`;
if (href) {
result += `<a class="${className}-link" href="${href}">`;
} else {
result += `<a class="${className}-link">`;
}


if (listNumber) {
result += htmlTag('span', { class: `${className}-number` });
result += `<span class="${className}-number">`;

for (let i = firstLevel - 1; i < level; i++) {
result += `${lastNumber[i]}.`;
Expand All @@ -60,7 +66,7 @@ function tocHelper(str, options = {}) {
result += '</span> ';
}

result += htmlTag('span', { class: `${className}-text` }, text) + '</a>';
result += `<span class="${className}-text">${text}</span></a>`;

lastLevel = level;
}
Expand Down

0 comments on commit d835578

Please sign in to comment.