import test from 'node:test'; import assert from 'node:assert/strict'; import * as echarts from 'echarts/core'; import { BarChart, LineChart } from 'echarts/charts'; import { GridComponent, LegendComponent, TooltipComponent, GraphicComponent, TitleComponent } from 'echarts/components'; import { SVGRenderer } from 'echarts/renderers'; import { buildAnalysisVisualExportOption, parseAnalysisVisuals, visualParetoPoints, } from '../src/analysisVisualsModel.ts'; echarts.use([BarChart, LineChart, GridComponent, LegendComponent, TooltipComponent, GraphicComponent, TitleComponent, SVGRenderer]); const WIDTH = 900; const LONG_LABEL_CHARS = 160; const FOOTER = '累计占比=所列累计重量÷同范围全部重量;Top未覆盖全量时不补足100%'; function productNames() { const alphabet = [...'高性能新能源汽车驱动电机磁钢规格型号材料检验工艺质量稳定强度']; const names = Array.from({ length: 10 }, (_, index) => { const marker = [...'一二三四五六七八九十'][index]; const body = Array.from({ length: LONG_LABEL_CHARS - 1 }, (_unused, offset) => alphabet[(offset * 7 + index * 3) % alphabet.length]).join(''); return marker + body; }); assert.ok(names.every(name => name.length === LONG_LABEL_CHARS)); return names; } function rankingVisual(names, weights) { return { id: 'ranking-long-labels', type: 'pareto', title: '黑片投入重量排名', subtitle: '按规格全量排名', unit: 'kg', categories: names.map((label, index) => ({ key: `product-${index + 1}`, label })), series: [{ key: 'black_total_weight', label: '黑片投入重量', values: weights }], evidenceRefs: ['Q12345678'], requiredFields: ['black_total_weight'], scope: { department: '新能源汽车磁钢' }, period: { year: 2026 }, stage: 'black', metric: 'black_total_weight', dimension: 'product', coverage: { totalRows: 24, returnedRows: 10, truncated: true, shareBasis: 'all_scope_weight', denominator: 10000 }, originTurnId: 'ranking-svg-layout-turn', }; } function boundsInCanvas(element) { const rect = element.getBoundingRect(); const transform = element.getComputedTransform(); assert.ok(rect && transform, 'SSR text display item must expose a rectangle and transform'); const [a, b, c, d, e, f] = transform; const corners = [ [rect.x, rect.y], [rect.x + rect.width, rect.y], [rect.x, rect.y + rect.height], [rect.x + rect.width, rect.y + rect.height], ].map(([x, y]) => [a * x + c * y + e, b * x + d * y + f]); return { left: Math.min(...corners.map(([x]) => x)), right: Math.max(...corners.map(([x]) => x)), top: Math.min(...corners.map(([_x, y]) => y)), bottom: Math.max(...corners.map(([_x, y]) => y)), centerX: e, }; } function svgTextBoxes(chart, option, footerText = FOOTER) { const displayList = chart.getZr().storage.getDisplayList(true); const textElements = displayList.filter(element => element.type === 'tspan' && typeof element.style?.text === 'string'); const footer = textElements.find(element => element.style.text === footerText); assert.ok(footer, `SVG SSR displayList must contain footer text: ${footerText}`); const footerBounds = boundsInCanvas(footer); const grid = option.grid; const plotBottom = Number(grid.top) + Number(grid.height); const plotLeft = Number(grid.left); const plotRight = WIDTH - Number(grid.right); const labels = textElements.flatMap(element => { const text = element.style.text; if (!/[\u3400-\u9fff]/u.test(text)) return []; const bounds = boundsInCanvas(element); if (bounds.top < plotBottom - 2 || bounds.top >= footerBounds.top || bounds.left < plotLeft - 1 || bounds.right > plotRight + 1) return []; return [{ text, bounds }]; }); const byCategoryCenter = new Map(); for (const label of labels) { const key = Math.round(label.bounds.centerX * 100) / 100; const existing = byCategoryCenter.get(key) || []; existing.push(label); byCategoryCenter.set(key, existing); } const categories = [...byCategoryCenter.entries()].sort(([left], [right]) => left - right).map(([center, lines]) => ({ center, text: lines.sort((left, right) => left.bounds.top - right.bounds.top).map(line => line.text).join(''), left: Math.min(...lines.map(line => line.bounds.left)), right: Math.max(...lines.map(line => line.bounds.right)), top: Math.min(...lines.map(line => line.bounds.top)), bottom: Math.max(...lines.map(line => line.bounds.bottom)), })); return { categories, footerBounds, displayList }; } function renderExport(visual, width = WIDTH) { const exported = buildAnalysisVisualExportOption(visual, width, 'report'); const chart = echarts.init(null, undefined, { renderer: 'svg', width, height: exported.height, ssr: true, }); chart.setOption(exported.option, { notMerge: true, lazyUpdate: false }); return { ...exported, chart, svg: chart.renderToSVGString() }; } function displayedCategoryVisual() { const labels = productNames().slice(0, 3); return { id: 'displayed-category-pareto', type: 'pareto', title: '黑片来源类别重量柏拉图', subtitle: '仅显示全部正式类别', unit: 'kg', categories: [ { key: 'black_responsibility_scrap', label: labels[0] }, { key: 'black_material_scrap', label: labels[1] }, { key: 'black_external_scrap', label: labels[2] }, ], series: [{ key: 'source_defect_weight', label: '类别重量', values: [80, 15, 5] }], evidenceRefs: ['Q12345678'], requiredFields: ['source_defect_weight'], scope: { department: '新能源汽车磁钢' }, period: { year: 2026 }, stage: 'black', metric: 'source_defect_weight', coverage: { totalRows: 3, returnedRows: 3, truncated: false, shareBasis: 'displayed_categories' }, originTurnId: 'ranking-svg-layout-turn', }; } test('900px SVG SSR wraps 160-character Pareto labels without overlap or footer collision', () => { const names = productNames(); const weights = [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100]; const parsed = parseAnalysisVisuals([rankingVisual(names, weights)]); assert.equal(parsed.visuals.length, 1); const model = parsed.visuals[0]; assert.equal(model.chartable, true); const rendered = renderExport(model); try { assert.match(rendered.svg, new RegExp(` label.replaceAll('\n', '')), names); assert.deepEqual(rendered.option.series[0].data, weights); assert.deepEqual(visualParetoPoints(model).map(point => point.valueKg), weights); assert.deepEqual(visualParetoPoints(model).map(point => point.cumulativeShare), weights.map((_weight, index) => weights.slice(0, index + 1).reduce((sum, value) => sum + value, 0) / 10000)); const { categories, footerBounds } = svgTextBoxes(rendered.chart, rendered.option); assert.equal(categories.length, 10, 'SSR must render one positioned label group per product'); assert.deepEqual(categories.map(category => category.text), names, 'all full product names must survive SVG layout'); assert.ok(footerBounds.top >= 0 && footerBounds.bottom <= rendered.height, 'export footer stays inside the SVG canvas'); const maxLabelBottom = Math.max(...categories.map(category => category.bottom)); assert.ok(maxLabelBottom < footerBounds.top && maxLabelBottom <= rendered.height, 'all axis text ends above the footer and within the SVG canvas'); for (const [index, category] of categories.entries()) { assert.ok(category.left >= -0.5, `label ${index} starts beyond the left canvas edge`); assert.ok(category.right <= WIDTH + 0.5, `label ${index} ends beyond the right canvas edge`); assert.ok(category.bottom < footerBounds.top, `label ${index} collides with the export footer`); if (index > 0) { assert.ok(categories[index - 1].right <= category.left + 0.5, `labels ${index - 1} and ${index} overlap horizontally`); } } const axisTitle = rendered.chart.getZr().storage.getDisplayList(true).filter(element => element.type === 'tspan' && element.style?.text === '累计占全部重量'); assert.ok(axisTitle.length >= 1, 'full cumulative-weight axis title remains in SVG'); for (const item of axisTitle) { const box = boundsInCanvas(item); assert.ok(box.left >= 0 && box.right <= WIDTH && box.top >= 0 && box.bottom < footerBounds.top, 'axis title remains inside canvas and above the footer'); } } finally { rendered.chart.dispose(); } }); test('all-scope export keeps denominator semantics and displayed_categories arithmetic unchanged', () => { const names = productNames(); const weights = [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100]; const allScope = parseAnalysisVisuals([rankingVisual(names, weights)]).visuals[0]; assert.equal(allScope.coverage.shareBasis, 'all_scope_weight'); assert.equal(allScope.coverage.denominator, 10000); assert.equal(visualParetoPoints(allScope)[0].share, 1000 / 10000); const displayed = parseAnalysisVisuals([displayedCategoryVisual()]).visuals[0]; const exportResult = buildAnalysisVisualExportOption(displayed, WIDTH, 'report'); const points = visualParetoPoints(displayed); assert.equal(displayed.coverage.shareBasis, 'displayed_categories'); assert.equal(displayed.coverage.denominator, undefined); assert.deepEqual(exportResult.option.xAxis.data.map(label => label.replaceAll('\n', '')), displayed.categories.map(category => category.label)); assert.deepEqual(exportResult.option.series[0].data, [80, 15, 5]); assert.equal(points[0].share, 80 / 100); assert.deepEqual(points.map(point => point.cumulativeShare), [0.8, 0.95, 1]); assert.deepEqual(exportResult.option.series[1].data, [80, 95, 100]); assert.equal(points.at(-1).cumulativeShare, 1); });