SmartXAxis 完整工具函数
function getVisualWidth(str) {
let width = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode >= 0x4E00 && charCode <= 0x9FFF ||
charCode >= 0x3000 && charCode <= 0x303F ||
charCode >= 0xFF00 && charCode <= 0xFFEF) {
width += 2;
} else {
width += 1;
}
}
return width;
}
const SmartXAxis = {
getConfig(data, xField, options = {}) {
const {
maxTruncate = 8,
minTruncate = 6,
} = options;
const maxWidth = Math.max(...data.map(d =>
getVisualWidth(String(d[xField] || ''))
));
const count = data.length;
let rotate, truncateAt;
if (maxWidth <= 4 && count <= 8) {
rotate = 0;
truncateAt = null;
} else if (maxWidth <= 8 && count <= 12) {
rotate = -Math.PI / 4;
truncateAt = null;
} else if (maxWidth >= 50) {
rotate = -Math.PI / 2;
truncateAt = minTruncate;
} else {
rotate = -Math.PI / 4;
truncateAt = count >= 15 ? minTruncate : maxTruncate;
}
return {
label: {
autoRotate: false,
rotate,
formatter: (text) => {
const str = String(text || '');
if (truncateAt && str.length > truncateAt) {
return str.substring(0, truncateAt) + '...';
}
return str;
},
style: {
fontSize: 11,
fill: '#1D1D1F',
textAlign: rotate === 0 ? 'center' : 'end',
},
},
};
},
};