1
0
mirror of https://github.com/sendevia/website.git synced 2026-03-05 23:32:45 +08:00
Files
website/.vitepress/theme/utils/mdSectionWrapper.ts

64 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type MarkdownIt from "markdown-it";
/**
* 将连续的标题块包裹为独立的 sectionheadline-block便于样式与交互处理
* @param mdit - MarkdownIt 实例
*/
export function sectionWrapper(mdit: MarkdownIt): void {
if (!mdit || !mdit.core || !mdit.core.ruler) {
console.warn("Invalid MarkdownIt instance provided");
return;
}
mdit.core.ruler.before("inline", "group_sections", (state) => {
const tokens = state.tokens;
const newTokens: any[] = [];
let inSection = false;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.type === "heading_open") {
// 如果已经在 section 中,先关闭前一个 section
if (inSection) {
newTokens.push({
type: "section_wrapper_close",
tag: "div",
nesting: -1,
level: 0,
});
}
// 打开新的 section
newTokens.push({
type: "section_wrapper_open",
tag: "div",
nesting: 1,
attrs: [["class", "headline-block"]],
level: 0,
});
newTokens.push(token);
inSection = true;
} else if (token.type === "heading_close") {
newTokens.push(token);
} else {
// 其他 token 根据是否在 section 中决定是否添加
newTokens.push(token);
}
}
// 如果循环结束后仍在 section 中,关闭最后一个 section
if (inSection) {
newTokens.push({
type: "section_wrapper_close",
tag: "div",
nesting: -1,
level: 0,
});
}
state.tokens = newTokens;
});
}