Files
Agent-System/web/src/engine/autoNumber.ts
T

50 lines
1.4 KiB
TypeScript

import { DocumentBlock } from '../types/block';
/**
* recomputeNumbering: 动态单遍重算整个文档块树的章节多级编号及图表题注
* - 标题层级栈:1 -> 1.1 -> 1.1.1
* - 图表计数器:表 1-1、图 1-1
*/
export function recomputeNumbering(root: DocumentBlock): DocumentBlock {
const chapterStack: number[] = [0, 0, 0, 0, 0, 0];
let currentTopChapter = 1;
let tableCounter = 1;
let figureCounter = 1;
function traverse(block: DocumentBlock) {
if (block.type === 'heading') {
const level = Math.max(1, Math.min(6, block.level || 1));
chapterStack[level - 1] += 1;
for (let i = level; i < chapterStack.length; i++) {
chapterStack[i] = 0;
}
const numStr = chapterStack.slice(0, level).join('.');
block.numbering = numStr;
if (level === 1) {
currentTopChapter = chapterStack[0];
tableCounter = 1;
figureCounter = 1;
}
} else if (block.type === 'table') {
block.numbering = `表 ${currentTopChapter}-${tableCounter++}`;
} else if (block.type === 'mermaid') {
block.numbering = `图 ${currentTopChapter}-${figureCounter++}`;
}
if (block.children && block.children.length > 0) {
for (const child of block.children) {
traverse(child);
}
}
}
if (root.children) {
for (const child of root.children) {
traverse(child);
}
}
return root;
}