| 10 | * @returns |
| 11 | */ |
| 12 | export function parseMarkdownToJSON(markdown: string): MarkdownNode[] { |
| 13 | const lines = markdown.split("\n"); |
| 14 | const root: MarkdownNode[] = []; |
| 15 | const stack: { node: MarkdownNode; level: number }[] = []; |
| 16 | |
| 17 | for (const line of lines) { |
| 18 | // 匹配标题(如 #, ##, ### 等) |
| 19 | const titleMatch = line.match(/^(#+)\s*(.*)/); |
| 20 | if (titleMatch) { |
| 21 | const level = titleMatch[1].length; // 标题层级 |
| 22 | const title = titleMatch[2].trim(); // 标题内容 |
| 23 | |
| 24 | const newNode: MarkdownNode = { |
| 25 | title, |
| 26 | content: "", |
| 27 | children: [], |
| 28 | }; |
| 29 | |
| 30 | // 根据层级找到父节点 |
| 31 | while (stack.length > 0 && stack[stack.length - 1].level >= level) { |
| 32 | stack.pop(); |
| 33 | } |
| 34 | |
| 35 | if (stack.length === 0) { |
| 36 | // 根节点 |
| 37 | root.push(newNode); |
| 38 | } else { |
| 39 | // 添加到父节点的 children 中 |
| 40 | stack[stack.length - 1].node.children.push(newNode); |
| 41 | } |
| 42 | |
| 43 | // 将当前节点推入栈中 |
| 44 | stack.push({ node: newNode, level }); |
| 45 | } else if (line.trim()) { |
| 46 | // 非标题行,作为内容处理 |
| 47 | if (stack.length > 0) { |
| 48 | stack[stack.length - 1].node.content += line + "\n"; |
| 49 | // 再去除一下最终的换行符 |
| 50 | stack[stack.length - 1].node.content = stack[stack.length - 1].node.content.trim(); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | return root; |
| 56 | } |