Skip to content

Commit

Permalink
适配 TOC
Browse files Browse the repository at this point in the history
  • Loading branch information
qianmoQ committed Dec 30, 2024
1 parent 3ed1563 commit 00c9e8f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 16 deletions.
25 changes: 11 additions & 14 deletions lib/extension/marked/pageforge-toc.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
const {marked} = require('marked');
const {pinyin} = require('pinyin');
const marked = require('./pageforge-marked');

function formatTOC(markdown) {
// 创建一个新的 marked 解析器实例
const parser = new marked.Parser();

const tokens = marked.lexer(markdown);
const headings = tokens.filter(token => token.type === 'heading');
const headings = tokens.filter(token => token.type === 'pageforgeHeading')
.map(token => ({
...token,
text: parser.parseInline(token.tokens) // 使用解析器实例来处理
}));

function buildTree(headings) {
const result = [];
let stack = [{level: 0, children: result}];

headings.forEach(heading => {
const node = {
level: heading.depth,
text: heading.text,
slug: pinyin(heading.text.replace(/\s+/g, ''), {
style: pinyin.STYLE_NORMAL,
segment: true
}).flat().join('-'),
...heading,
children: []
};

// 找到合适的父节点
while (stack[stack.length - 1].level >= heading.depth) {
while (stack[stack.length - 1].level >= heading.level) {
stack.pop();
}

// 添加到父节点的children中
stack[stack.length - 1].children.push(node);

// 将当前节点加入stack
stack.push(node);
});

Expand Down
2 changes: 1 addition & 1 deletion templates/components/p.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = function h1(item) {
return `
<p class="text-base text-gray-700 leading-7 mb-4">
<p class="text-base text-gray-700 leading-7">
${item.text}
</p>
`;
Expand Down
2 changes: 1 addition & 1 deletion templates/includes/toc.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<a href="#<%= item.slug %>"
class="block py-2 px-3 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-md transition-colors duration-150 toc-link"
data-slug="<%= item.slug %>">
<%= item.text %>
<%- item.text %>
</a>
</div>
<% if (item.children && item.children.length > 0) { %>
Expand Down

0 comments on commit 00c9e8f

Please sign in to comment.