import { esc } from './util.js';
const NAME = 15;
const ROOT_NAME = 17;
const NOTE = 11;
const CHIP = 11.5;
const CHIP_H = 17;
const CHIP_GAP = 4;
const ROW_H = 19;
const PAD_TOP = 9;
const MAX_W = 268;
const MIN_W = 92;
const MIN_ROOT = 150;
const GAP_X = 18;
const GAP_Y = 46;
const CANVAS = 18;
function textWidth(text, size) {
let w = 0;
for (const ch of String(text)) {
if (/[\u4e00-\u9fa5]/.test(ch)) w += size;
else if (/[A-Za-z0-9]/.test(ch)) w += size * 0.56;
else if (ch === '·' || ch === '—' || ch === '(' || ch === ')') w += size * 0.92;
else w += size * 0.46;
}
return w;
}
function build(raw, depth, isRoot) {
const node = {
...raw,
depth,
isRoot,
nameSize: isRoot ? ROOT_NAME : NAME,
children: (raw.children || []).map((c) => build(c, depth + 1, false)),
};
const nameW = textWidth(node.name, node.nameSize);
const noteW = node.note ? textWidth(node.note, NOTE) : 0;
const chips = (node.items || []).map((text) => ({
text,
w: textWidth(text, CHIP) + 14,
}));
const rows = [];
let row = [];
let rowW = 0;
let maxRowW = 0;
for (const chip of chips) {
if (row.length && rowW + CHIP_GAP + chip.w > MAX_W - 24) {
rows.push({ items: row, w: rowW });
maxRowW = Math.max(maxRowW, rowW);
row = [];
rowW = 0;
}
rowW += (row.length ? CHIP_GAP : 0) + chip.w;
row.push(chip);
}
if (row.length) {
rows.push({ items: row, w: rowW });
maxRowW = Math.max(maxRowW, rowW);
}
node.rows = rows;
node.w = Math.max(isRoot ? MIN_ROOT : MIN_W, nameW + 26, noteW + 20, maxRowW + 24);
node.w = Math.min(node.w, MAX_W);
node.h = PAD_TOP + 21 + (node.note ? 14 : 0) + (rows.length ? rows.length * ROW_H + 4 : 0) + 9;
const childTotal = node.children.length
? node.children.reduce((sum, c) => sum + c.sw, 0) + GAP_X * (node.children.length - 1)
: 0;
node.sw = Math.max(node.w, childTotal);
return node;
}
function walk(node, fn) {
fn(node);
for (const child of node.children) walk(child, fn);
}
function linkPath(parent, child) {
const x1 = parent.x + parent.w / 2;
const y1 = parent.y + parent.h;
const x2 = child.x + child.w / 2;
const y2 = child.y;
const mid = y1 + (y2 - y1) / 2;
if (Math.abs(x2 - x1) < 1) return `M${x1} ${y1}V${y2}`;
const r = 7;
const dir = x2 > x1 ? 1 : -1;
return `M${x1} ${y1}V${mid - r}Q${x1} ${mid} ${x1 + dir * r} ${mid}H${x2 - dir * r}Q${x2} ${mid} ${x2} ${mid + r}V${y2}`;
}
function nodeSvg(node) {
const chipsY = PAD_TOP + 21 + (node.note ? 14 : 0) + 3;
const nameY = PAD_TOP + (node.isRoot ? 17 : 15);
const parts = [];
parts.push(`
结构图ORG CHART
${esc(chart.caption || '')}图为权力关系简示,不表示品级高低;具体职掌见下方逐层说明。图较宽,共 ${root.children.length} 个分支;可按住左右拖动,或用两侧箭头查看全图。按隶属关系缩进;金底为中枢,绿底为监察,虚线框为地方。