XWX-AI commited on
Commit
3b9619e
·
1 Parent(s): b689996

fix(chart): GPT-6 charts_widget_v2 饼图契约补全+引擎对齐官方Recharts v3(备忘录119重写)——①根因: server.js/桌面Rust按位置白名单挑9字段传构建器, 而官方zod schema是.loose()透传未知键, 导致官方消费的 layout(水平条形图)/xAxisScale(数值x轴) 被静默丢弃 → 改为整包传 spec buildChatGPTChartHtml(chartData), 位置白名单这一层结构性消失(保留旧9参归一化供Rust未重编窗口期); ②饼图11参数按官方44829 qOl-A/AXa逐字补全: 恒环形 innerRadius40%/outerRadius78%/startAngle90/endAngle-270/paddingAngle.5/Cell stroke var(--color-surface)+strokeWidth2, showValueLabels与showLabelLines默认false故不画数值标签与引线(旧实现无条件画=截图里多出"搜索引擎4.2K"一圈), colorCount=data.length逐扇区取6色盘, nameKey作xAxis且nameKey=__sliceLabel; ③图例顺序根因=引擎差异: v3 Legend.defaultProps.itemSorter='value'按标签码点升序, v2无此行为 → 换 recharts@3.10.1 UMD(实测peer支持React18;首版"v3不可用"只对SSR成立), 由引擎产出而非手工sort(3.0.0不复现,勿降); ④补首版未取到的726342 IMu柱图档位表: gapPx=卡片容器宽>=768?12:8再按dataLen收敛(>=24→3/>=16→6), barRadius按 containerSize/dataLen/有效系列数*0.65 落档56→8/36→6/16→4/0→2, maxBarSize除「2行×2系列」外恒120(水平48,条件方向易读反); ⑤移除官方从不消费的 formattedData/yAxisMin/yAxisMax/xAxisLabel/axes[].label 路径(官方不画轴标题,x刻度标签来自data行而非axes,仅认恰好一条dimension=y), bar的x刻度改官方foreignObject+div盒, line/scatter保留引擎默认text刻度(dy 2/3em), minTickGap 10, 轴宽=ceil(实测标签)+4(旧Y_AXIS_PAD6系在已漂移的旧捕获上标定,实测9/10命中±1px); ⑥验证: temp/test/chatgpt/2026-10-14-chart-pie/ 三方对照13张真实图官方DOM oracle逐值diff — 现网34.2% → 移植层+v2 94.3%(掉分全是饼图图例序) → 采用层+v3 95.8%, 3张饼图25/25 25/25 23/25, 柱图44/44与39/39, 首版verify-r1的34项bar契约无一复发; pdf-test(17861)重建后走生产HTTP入口 /api/render_charts 14/14出图, 非官方4类chartType返回null交上层回退表格. 备份 backend-service_v3.1.2_2026-10-14T02-50-03(159文件). 生产 space/main 未推送(用户指示:会影响生产环境)

Browse files
Files changed (2) hide show
  1. lib/chatgpt-chart-html.js +357 -481
  2. server.js +11 -17
lib/chatgpt-chart-html.js CHANGED
@@ -1,525 +1,401 @@
1
  /**
2
- * buildChatGPTChartHtml — ChatGPT charts_widget_v2 数据 → 完整渲染 HTML
3
  *
4
- * 单一事实源:backend-service(本目录)与桌面 APP(BatchExporter/xwx-backup/app/src-tauri/pdf-render/)
5
- * 共用同一份实现。桌面端通过 make/build-pdf-render-assets.mjs 同步并做逐字节校验。
6
- * 修改时保持两端同步流程:先改这里,再跑 make 脚本同步;桌面 Rust 调用点
7
- * (widget_renderer.rs assemble_widget_html)同步改 meta 传参。
8
  *
9
- * ── 渲染契约依据(2026-10-13 真机取证,temp/test/chatgpt/2026-10-13-chart-r10/)──
10
- * 目标:与 chatgpt.com 网页容器渲染一致(用户验收标准)。官方 = Recharts v3
11
- * (accessibilityLayer 层)+ ChatGPT widget 组件注入的默认样式,证据文件:
12
- * official-chart-props.json — 官方组件 fiber props 实测(depth-8/13/22/30)
13
- * official-v5-dom.json — SVG 文本/网格线/foreignObject 计算样式实测
14
- * official-v6-xticks.json — x 轴 foreignObject 标签排版实测(12px/#5d5d5d/400)
15
- * official-bundle-hits.json — 官方 JS bundle 逐字取证:
16
- * · 44829 chunk uNo 模块:调色板 6 色(light/dark),系列色 = palette[i % 6],
17
- * spec series 内的 color 字段被官方丢弃重灌;showLegend = series.length > 1
18
- * · 44829 chunk:line 系列 curveType="linear";showDots = (chartType==="line" && data.length<=40)
19
- * · 726342 chunk:barCategoryGap 自适应 = dataLen>=24→min(gap,3) / >=16→min(gap,6) / 否则 8;
20
- * maxBarSize 水平布局 120(垂直 48)
21
- * · 745098 chunk:Recharts v3 默认 margin {5,5,5,5}、barGap 4
22
- * 已知简化(备忘录记录):barRadius 官方按估算条厚分档(厚→8,薄→2),档位表未
23
- * 完整取到,此处按本机 719px 宽实测值定 8;密集图(dataLen≥16 类)半径可能偏差。
 
 
 
 
 
 
 
 
 
 
 
24
  */
25
- function buildChatGPTChartHtml(chartType, series, data, xKey, nameKey, valueKey, formattedData, axes, meta, legacyDescription) {
26
- // 桌面端旧编译产物(Rust 未重编窗口期)按旧签名传 (title:string, description:string)
27
- if (typeof meta === 'string' || meta == null) {
28
- meta = { title: meta || '', description: legacyDescription || '' };
29
- }
30
- meta = meta || {};
31
-
32
- // 官方 light 主题调色板(bundle uNo 模块逐字),系列色 = PALETTE[i % 6];
33
- // pie 按行注入同盘(官方 pie 上色路径未取证,沿用逐行注入)
34
- var PALETTE = ['#539af8', '#6bc67f', '#ef8b57', '#f8d45d', '#b897f4', '#f68ebc'];
35
- // 官方字体栈(SVG text 计算样式实测)
36
- var FONT_STACK = "-apple-system-body, ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, 'Apple Color Emoji', Arial, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'";
37
-
38
- // 官方几何常量(props 实测 + bundle 自适应公式;CHART_HEIGHT 为实测值)
39
- var CHART_WIDTH = 719;
40
- var CHART_HEIGHT = 314;
41
- var MARGIN = { top: 5, right: 5, bottom: 5, left: 5 };
42
- var BAR_GAP = 4;
43
- var MAX_BAR_SIZE = 120;
44
- var BAR_RADIUS = 8;
45
- var BAR_CATEGORY_GAP = (data || []).length >= 24 ? 3 : (data || []).length >= 16 ? 6 : 8;
46
- // 官方两轴统一:axisLine/tickLine 关、tickMargin 4;刻度字 12px #5d5d5d(#666 被
47
- // 官方 CSS 覆盖为 rgb(93,93,93),此处直接落值)
48
- var TICK_STYLE = { fontSize: 12, fill: '#5d5d5d' };
49
- var TICK_MARGIN = 4;
50
- var X_PADDING = { left: 4, right: 4 };
51
- // y 轴宽自适应的校准常数:官方 v3 实测 clip.x=86 → 轴宽 81 = 本机 span 实测最长
52
- // 刻度文本 71 + tickMargin 4 + 本常数 6。宽度在渲染宿主机上用同一字体自测自用,
53
- // 任何环境都不会裁切,仅带内对齐随字体度量有 ±几px 差异。
54
- // v2 无 width:'auto'(实测传 'auto' 整图不渲染),故按官方同机制测量后传数值。
55
- var Y_AXIS_PAD = 6;
56
- // 官方 legend 规则:仅多系列显示(bundle: showLegend = series.length > 1)
57
- var showLegend = (series || []).length > 1;
58
-
59
- var title = meta.title || '';
60
- var description = meta.description || '';
61
- var footer = meta.footer || '';
62
 
63
- // Serialize data safely for inline script
64
- var safe = function (v) { return JSON.stringify(v == null ? '' : v).replace(/<\/script/gi, '<\\/script'); };
65
- var dataJson = safe(data || []);
66
- var seriesJson = safe(series || []);
67
- var chartTypeJson = safe(chartType || 'bar');
68
- var titleJson = safe(title);
69
- var descJson = safe(description);
70
- var footerJson = safe(footer);
71
- var xKeyJson = safe(xKey || 'x');
72
- var nameKeyJson = safe(nameKey || '');
73
- var valueKeyJson = safe(valueKey || '');
74
- var formattedDataJson = safe(formattedData || []);
75
- var axesJson = safe(axes || []);
76
- var paletteJson = safe(PALETTE);
77
- // Node 侧常量桥接进页内脚本(页内代码引用的是运行时变量,模板不会自动注入)
78
- var constsJson = JSON.stringify({
79
- CHART_WIDTH: CHART_WIDTH, CHART_HEIGHT: CHART_HEIGHT, MARGIN: MARGIN,
80
- BAR_GAP: BAR_GAP, MAX_BAR_SIZE: MAX_BAR_SIZE, BAR_RADIUS: BAR_RADIUS,
81
- BAR_CATEGORY_GAP: BAR_CATEGORY_GAP, TICK_STYLE: TICK_STYLE,
82
- TICK_MARGIN: TICK_MARGIN, X_PADDING: X_PADDING, SHOW_LEGEND: showLegend,
83
- Y_AXIS_PAD: Y_AXIS_PAD, FONT_STACK: FONT_STACK
84
- });
85
-
86
- return `<!DOCTYPE html>
87
  <html><head><meta charset="UTF-8">
88
  <style>
89
- body { margin: 0; padding: 8px; background: #ffffff; font-family: ${FONT_STACK}; }
90
- /* 官方头部:description 14px/20px #5d5d5d(上方),footer 12px/16px #8f8f8f(图下方)。
91
- 间距实测:desc 与图间隔 mb-5=20px,footer 与图间隔 mt-2.5=10px。 */
92
- .chart-title { font-size: 16px; font-weight: 600; color: #0d0d0d; margin: 0 0 4px; }
93
- /* 官方头部设计:min-h 固定块(本机实测图顶固定在卡内 76px,即 desc 块占 68px),
94
- desc 最多两行 line-clamp-2 —— 一行/两行都不推移图表位置。 */
95
- .chart-header { min-height: 68px; }
96
- .chart-desc { font-size: 14px; line-height: 20px; color: #5d5d5d; margin: 0;
97
- display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
98
- .chart-footer { font-size: 12px; line-height: 16px; color: #8f8f8f; margin: 10px 0 0; }
99
  #widget-container { width: 735px; }
 
 
 
 
 
100
  </style>
101
  <script src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"><\/script>
102
  <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"><\/script>
103
  <script src="https://unpkg.com/react-is@18.2.0/umd/react-is.production.min.js"><\/script>
104
  <script src="https://unpkg.com/prop-types@15.8.1/prop-types.min.js"><\/script>
105
- <script src="https://unpkg.com/recharts@2.12.7/umd/Recharts.js"><\/script>
106
  </head><body>
107
- <div id="widget-container"><div id="chart-mount"></div></div>
108
  <script>
109
  window._widgetRendered = false;
110
- (function() {
 
 
 
 
111
  try {
112
- var chartData = ${dataJson};
113
- var chartSeries = ${seriesJson};
114
- var chartTitle = ${titleJson};
115
- var chartDesc = ${descJson};
116
- var chartFooter = ${footerJson};
117
- var xKey = ${xKeyJson};
118
- var chartType = ${chartTypeJson};
119
- var nameKey = ${nameKeyJson};
120
- var valueKey = ${valueKeyJson};
121
- var formattedData = ${formattedDataJson};
122
- var chartAxes = ${axesJson};
123
- var PALETTE = ${paletteJson};
124
- var CONSTS = ${constsJson};
125
- var CHART_WIDTH = CONSTS.CHART_WIDTH, CHART_HEIGHT = CONSTS.CHART_HEIGHT, MARGIN = CONSTS.MARGIN,
126
- BAR_GAP = CONSTS.BAR_GAP, MAX_BAR_SIZE = CONSTS.MAX_BAR_SIZE, BAR_RADIUS = CONSTS.BAR_RADIUS,
127
- BAR_CATEGORY_GAP = CONSTS.BAR_CATEGORY_GAP, TICK_STYLE = CONSTS.TICK_STYLE,
128
- TICK_MARGIN = CONSTS.TICK_MARGIN, X_PADDING = CONSTS.X_PADDING,
129
- showLegend = CONSTS.SHOW_LEGEND, Y_AXIS_PAD = CONSTS.Y_AXIS_PAD,
130
- FONT_STACK = CONSTS.FONT_STACK;
131
-
132
- var rc = Recharts;
133
- var h = React.createElement;
134
-
135
- // 官方系列色:palette[i % 6],忽略 spec 内 color(bundle 实证官方重灌)
136
- function seriesColor(i) { return PALETTE[i % PALETTE.length]; }
137
-
138
- // ── Scatter chart: detect x-axis key ──
139
- var scatterXKey = xKey;
140
- if (chartType === 'scatter' && chartData.length > 0) {
141
- var sFirstRow = chartData[0];
142
- var sKeys = Object.keys(sFirstRow);
143
- var seriesDataKey = chartSeries[0] ? chartSeries[0].dataKey : null;
144
- // Find a non-series key for x-axis (prefer non-numeric for category axis)
145
- for (var si = 0; si < sKeys.length; si++) {
146
- if (sKeys[si] !== seriesDataKey) {
147
- scatterXKey = sKeys[si];
148
- break;
149
- }
150
- }
151
- }
152
-
153
- // ── Universal axis configuration builder ──
154
- // Uses pre-calculated axis data from API JSON (axes[].ticks[].label)
155
- // instead of procedural formatting. This is the canonical approach:
156
- // ChatGPT's AI generates exact tick labels in the API JSON, and we
157
- // pass them directly to Recharts via the tick prop.
158
-
159
- function buildAxisConfig(axisId) {
160
- // Find matching axis from chartAxes by id
161
- var axisConfig = null;
162
- for (var ai = 0; ai < chartAxes.length; ai++) {
163
- if (chartAxes[ai].id === axisId) {
164
- axisConfig = chartAxes[ai];
165
- break;
166
- }
167
- }
168
- if (!axisConfig) {
169
- // Fallback: use series-level formatting if no axes data
170
- var s = chartSeries[0] || {};
171
- var prefix = s.valuePrefix || '';
172
- var suffix = s.valueSuffix || '';
173
- var format = s.valueFormat || 'standard';
174
- return {
175
- tickFormatter: function(value) {
176
- var num = Number(value);
177
- if (isNaN(num)) return String(value);
178
- var display;
179
- if (format === 'compact') {
180
- if (Math.abs(num) >= 1e9) display = (num / 1e9).toFixed(0) + 'B';
181
- else if (Math.abs(num) >= 1e6) display = (num / 1e6).toFixed(0) + 'M';
182
- else if (Math.abs(num) >= 1e3) display = (num / 1e3).toFixed(0) + 'K';
183
- else display = String(num);
184
- } else {
185
- display = String(num);
186
- }
187
- return prefix + display + suffix;
188
- }
189
- };
190
- }
191
-
192
- // Build tick lookup map: value → label
193
- var tickMap = {};
194
- for (var ti = 0; ti < axisConfig.ticks.length; ti++) {
195
- tickMap[String(axisConfig.ticks[ti].value)] = axisConfig.ticks[ti].label;
196
- }
197
- var tickValues = axisConfig.ticks.map(function(t) { return t.value; });
198
-
199
- return {
200
- domain: axisConfig.domain || undefined,
201
- ticks: tickValues,
202
- tickFormatter: function(value) {
203
- var key = String(value);
204
- // Direct lookup for exact match
205
- if (tickMap[key] !== undefined) return tickMap[key];
206
- // Fallback: procedural formatting for interpolated values
207
- var prefix = '';
208
- var suffix = '';
209
- var s0 = chartSeries[0] || {};
210
- prefix = s0.valuePrefix || '';
211
- suffix = s0.valueSuffix || '';
212
- var num = Number(value);
213
- if (isNaN(num)) return String(value);
214
- if (Math.abs(num) >= 1e9) return prefix + (num / 1e9).toFixed(0) + 'B' + suffix;
215
- if (Math.abs(num) >= 1e6) return prefix + (num / 1e6).toFixed(0) + 'M' + suffix;
216
- if (Math.abs(num) >= 1e3) return prefix + (num / 1e3).toFixed(0) + 'K' + suffix;
217
- return prefix + String(num) + suffix;
218
- },
219
- label: axisConfig.label || undefined
220
- };
221
  }
 
 
 
 
222
 
223
- // Build series elements
224
- // 官方统一组件 props(44829 chunk):bar→type "bar";line→curveType "linear"、
225
- // dot 仅 line 且数据点 ≤40 时开(半径未取证,用 Recharts 默认)。
226
- var seriesEls = [];
227
- if (chartType === 'bar') {
228
- chartSeries.forEach(function(s, i) {
229
- var color = seriesColor(i);
230
- var props = {
231
- dataKey: s.dataKey,
232
- name: s.label || s.dataKey,
233
- fill: 'url(#xwx-bar-grad-' + i + ')',
234
- stroke: color,
235
- radius: BAR_RADIUS,
236
- isAnimationActive: false
237
- };
238
- if (s.stackId !== undefined) props.stackId = s.stackId;
239
- else if (s.stack !== undefined) props.stackId = s.stack;
240
- if (s.barSize !== undefined) props.barSize = s.barSize;
241
- if (s.unit !== undefined) props.unit = s.unit;
242
- seriesEls.push(h(rc.Bar, props));
243
- });
244
- } else if (chartType === 'line') {
245
- chartSeries.forEach(function(s, i) {
246
- var color = seriesColor(i);
247
- var props = {
248
- type: s.type || 'linear',
249
- dataKey: s.dataKey,
250
- name: s.label || s.dataKey,
251
- stroke: color,
252
- strokeWidth: 2,
253
- dot: chartData.length <= 40,
254
- connectNulls: s.connectNulls !== undefined ? s.connectNulls : true,
255
- isAnimationActive: false
256
- };
257
- if (s.strokeDasharray !== undefined) props.strokeDasharray = s.strokeDasharray;
258
- if (s.unit !== undefined) props.unit = s.unit;
259
- seriesEls.push(h(rc.Line, props));
260
- });
261
- } else if (chartType === 'area') {
262
- chartSeries.forEach(function(s, i) {
263
- var color = seriesColor(i);
264
- var props = {
265
- type: s.type || 'linear',
266
- dataKey: s.dataKey,
267
- name: s.label || s.dataKey,
268
- fill: color,
269
- stroke: color,
270
- strokeWidth: 2,
271
- connectNulls: s.connectNulls !== undefined ? s.connectNulls : true,
272
- isAnimationActive: false
273
- };
274
- if (s.fillOpacity !== undefined) props.fillOpacity = s.fillOpacity;
275
- if (s.baseValue !== undefined) props.baseValue = s.baseValue;
276
- if (s.strokeDasharray !== undefined) props.strokeDasharray = s.strokeDasharray;
277
- if (s.dot !== undefined) props.dot = s.dot;
278
- if (s.unit !== undefined) props.unit = s.unit;
279
- if (s.stackId !== undefined) props.stackId = s.stackId;
280
- seriesEls.push(h(rc.Area, props));
281
- });
282
- } else if (chartType === 'scatter') {
283
- chartSeries.forEach(function(s, i) {
284
- var props = {
285
- name: s.label || s.dataKey,
286
- dataKey: s.dataKey,
287
- fill: seriesColor(i)
288
- };
289
- if (s.unit !== undefined) props.unit = s.unit;
290
- seriesEls.push(h(rc.Scatter, props));
291
  });
292
- } else if (chartType === 'pie' || chartType === 'donut') {
293
- chartSeries.forEach(function(s, i) {
294
- var actualDataKey = valueKey || s.dataKey || 'value';
295
- var actualNameKey = nameKey || 'name';
296
 
297
- // Inject fill color into data items (Recharts v2 UMD: Cell children don't work reliably)
298
- var pieColoredData = chartData.map(function(row, ri) {
299
- var copy = {};
300
- for (var _k in row) { copy[_k] = row[_k]; }
301
- copy.fill = seriesColor(ri);
302
- return copy;
 
 
 
 
 
303
  });
304
-
305
- // Pie label formatter: use formattedData for display values
306
- var pieRawToFormatted = {};
307
- if (chartData && formattedData && chartData.length === formattedData.length) {
308
- for (var _pi = 0; _pi < chartData.length; _pi++) {
309
- var _pRaw = chartData[_pi];
310
- var _pFmt = formattedData[_pi];
311
- var _pRawVal = _pRaw[actualDataKey];
312
- if (_pRawVal !== undefined && _pRawVal !== null && _pFmt) {
313
- pieRawToFormatted[String(_pRawVal)] = {
314
- name: _pFmt[actualNameKey] || _pRaw[actualNameKey],
315
- formatted: _pFmt[s.dataKey]
316
- };
317
- }
318
- }
319
- }
320
-
321
- var labelFormatter = function(entry) {
322
- var rawVal = String(entry.value);
323
- var matched = pieRawToFormatted[rawVal];
324
- if (matched) {
325
- return matched.name + ' ' + matched.formatted;
326
- }
327
- return String(entry.name) + ' ' + entry.value;
328
- };
329
-
330
- var pieProps = {
331
- data: pieColoredData,
332
- dataKey: actualDataKey,
333
- nameKey: actualNameKey,
334
- name: s.label || s.dataKey,
335
- cx: '50%', cy: '50%',
336
- outerRadius: 100,
337
- innerRadius: chartType === 'donut' ? 60 : 0,
338
- isAnimationActive: false,
339
- label: labelFormatter
340
- };
341
- if (s.paddingAngle !== undefined) pieProps.paddingAngle = s.paddingAngle;
342
- if (s.cornerRadius !== undefined) pieProps.cornerRadius = s.cornerRadius;
343
- if (s.startAngle !== undefined) pieProps.startAngle = s.startAngle;
344
- if (s.endAngle !== undefined) pieProps.endAngle = s.endAngle;
345
- if (s.minAngle !== undefined) pieProps.minAngle = s.minAngle;
346
- seriesEls.push(h(rc.Pie, pieProps));
347
  });
348
- } else if (chartType === 'radar') {
349
- chartSeries.forEach(function(s, i) {
350
- var color = seriesColor(i);
351
- var props = {
352
- dataKey: s.dataKey,
353
- name: s.label || s.dataKey,
354
- stroke: color,
355
- fill: color,
356
- fillOpacity: 0.3
357
- };
358
- if (s.unit !== undefined) props.unit = s.unit;
359
- seriesEls.push(h(rc.Radar, props));
360
- });
361
- } else {
362
- // Fallback: unsupported chart type
363
- document.getElementById('widget-container').innerHTML = '<div style="padding:20px;color:#666;">Unsupported chart type: ' + chartType + '</div>';
364
- window._widgetRendered = true;
365
- return;
366
  }
367
-
368
- // Select chart component
369
- var ChartComponent;
370
- switch (chartType) {
371
- case 'bar': ChartComponent = rc.BarChart; break;
372
- case 'line': ChartComponent = rc.LineChart; break;
373
- case 'area': ChartComponent = rc.AreaChart; break;
374
- case 'scatter': ChartComponent = rc.ScatterChart; break;
375
- case 'pie': case 'donut': ChartComponent = rc.PieChart; break;
376
- case 'radar': ChartComponent = rc.RadarChart; break;
377
- default: ChartComponent = rc.BarChart;
378
  }
379
-
380
- var chartProps = { data: chartData, width: CHART_WIDTH, height: CHART_HEIGHT, margin: MARGIN };
381
- if (chartType === 'bar') {
382
- chartProps.barGap = BAR_GAP;
383
- chartProps.barCategoryGap = BAR_CATEGORY_GAP;
384
- chartProps.maxBarSize = MAX_BAR_SIZE;
 
 
 
 
385
  }
386
- if (chartType === 'radar') {
387
- chartProps.cx = '50%';
388
- chartProps.cy = '50%';
389
- chartProps.outerRadius = 100;
390
- } else if (chartType === 'scatter') {
391
- chartProps.xAxisId = 0;
392
  }
393
-
394
- var gridEls = [];
395
-
396
- // bar 渐变 defs(官方实测:纵向线性渐变,系列色 stopOpacity 1 → 0.9)
397
- if (chartType === 'bar') {
398
- var stops = [];
399
- chartSeries.forEach(function(s, i) {
400
- var color = seriesColor(i);
401
- stops.push(h('linearGradient', { id: 'xwx-bar-grad-' + i, x1: '0', y1: '0', x2: '0', y2: '1' },
402
- h('stop', { offset: '0%', stopColor: color, stopOpacity: 1 }),
403
- h('stop', { offset: '100%', stopColor: color, stopOpacity: 0.9 })
404
- ));
405
  });
406
- gridEls.push(h('defs', { key: 'grads' }, stops));
407
- }
408
-
409
- if (chartType !== 'pie' && chartType !== 'donut' && chartType !== 'radar') {
410
- // 官方网格:仅水平线,#ccc,虚线 3 3(实测 5 条 = 每个 y 刻度一条,无竖线)
411
- gridEls.push(h(rc.CartesianGrid, { horizontal: true, vertical: false, stroke: '#ccc', strokeDasharray: '3 3', key: 'grid' }));
412
- var axisKey = chartType === 'scatter' ? scatterXKey : xKey;
413
-
414
- // 官方刻度样式(y 为 svg text / x 为 foreignObject div,v6 实测 12px #5d5d5d 400)。
415
- // v2 默认刻度 Text 的换行测量不含 fontSize(按默认 16px 估宽),带空格的长标签
416
- // 会被误换行且空格丢失,故两轴均用自定�� tick 直绘,不经该测量。
417
- function makeTick(tickFormatter, anchor) {
418
- return function (p) {
419
- var v = p.payload && p.payload.value;
420
- return h('text', {
421
- x: p.x, y: p.y, dy: '0.355em', textAnchor: anchor,
422
- fontSize: TICK_STYLE.fontSize, fill: TICK_STYLE.fill, fontFamily: FONT_STACK
423
- }, tickFormatter(v));
424
- };
425
  }
426
-
427
- // ── XAxis: use axes[].dimension from API JSON ──
428
- // Find X axis config from axes array by dimension="x"
429
- var xAxisConfig = null;
430
- for (var _xi = 0; _xi < chartAxes.length; _xi++) {
431
- if (chartAxes[_xi].dimension === 'x') {
432
- xAxisConfig = chartAxes[_xi];
433
- break;
434
- }
435
- }
436
- var xAxisProps = { dataKey: axisKey, key: 'x', axisLine: false, tickLine: false, tickMargin: TICK_MARGIN, padding: X_PADDING };
437
- if (xAxisConfig && xAxisConfig.domain) { xAxisProps.domain = xAxisConfig.domain; }
438
- if (xAxisConfig && xAxisConfig.ticks) {
439
- var _xTickMap = {};
440
- for (var _xti = 0; _xti < xAxisConfig.ticks.length; _xti++) {
441
- _xTickMap[String(xAxisConfig.ticks[_xti].value)] = xAxisConfig.ticks[_xti].label;
442
  }
443
- xAxisProps.tickFormatter = function(v) { var k = String(v); return _xTickMap[k] !== undefined ? _xTickMap[k] : String(v); };
444
  }
445
- if (xAxisConfig && xAxisConfig.label) { xAxisProps.label = xAxisConfig.label; }
446
- xAxisProps.tick = makeTick(xAxisProps.tickFormatter || function (v) { return String(v); }, 'middle');
447
- gridEls.push(h(rc.XAxis, xAxisProps));
448
-
449
- // ── YAxis: use axes[].dimension from API JSON, linked by series[].axisId ──
450
- var yAxisId = chartSeries[0] ? (chartSeries[0].axisId || null) : null;
451
- var yAxisConfig = yAxisId ? buildAxisConfig(yAxisId) : buildAxisConfig(null);
452
- // 官方 y 轴宽自适应:最长刻度文本(隐藏 span DOM 测量,canvas measureText 偏小
453
- // 会导致长标签仍被换行、空格丢失)+ tickMargin + 校准常数
454
- var yMeasure = document.createElement('span');
455
- yMeasure.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap;left:-9999px;top:0;';
456
- yMeasure.style.font = TICK_STYLE.fontSize + 'px ' + FONT_STACK;
457
- document.body.appendChild(yMeasure);
458
- var yLabels = [];
459
- if (yAxisConfig.ticks && yAxisConfig.ticks.length) {
460
- yAxisConfig.ticks.forEach(function (tv) { yLabels.push(yAxisConfig.tickFormatter(tv)); });
461
- } else if (chartData.length && chartSeries[0] && chartSeries[0].dataKey) {
462
- chartData.forEach(function (row) { yLabels.push(yAxisConfig.tickFormatter(row[chartSeries[0].dataKey])); });
463
- }
464
- var maxYLabelW = 0;
465
- yLabels.forEach(function (l) { yMeasure.textContent = String(l); maxYLabelW = Math.max(maxYLabelW, yMeasure.offsetWidth); });
466
- document.body.removeChild(yMeasure);
467
- var yAxisProps = { key: 'y', axisLine: false, tickLine: false, tickMargin: TICK_MARGIN, tickFormatter: yAxisConfig.tickFormatter };
468
- if (maxYLabelW > 0) { yAxisProps.width = Math.ceil(maxYLabelW) + TICK_MARGIN + Y_AXIS_PAD; }
469
- if (yAxisConfig.domain) { yAxisProps.domain = yAxisConfig.domain; }
470
- if (yAxisConfig.ticks) { yAxisProps.ticks = yAxisConfig.ticks; }
471
- // Use axes[].label from API JSON for axis title (e.g., "用户数")
472
- if (yAxisConfig.label) { yAxisProps.label = yAxisConfig.label; }
473
- yAxisProps.tick = makeTick(yAxisConfig.tickFormatter, 'end');
474
- gridEls.push(h(rc.YAxis, yAxisProps));
475
  }
476
-
477
- // 官方 legend 规则:仅多系列(showLegend = series.length > 1)。
478
- // pie/donut 沿用类别名 payload(官方 pie legend 未取证,保持既有行为)。
479
- if (chartType === 'pie' || chartType === 'donut') {
480
- var pieActualNameKey = nameKey || 'name';
481
- var legendPayload = chartData.map(function(row, i) {
482
- var fmt = formattedData[i];
483
- return {
484
- id: i,
485
- value: fmt ? (fmt[pieActualNameKey] || row[pieActualNameKey]) : (row[pieActualNameKey] || 'Item'),
486
- type: 'rect',
487
- color: PALETTE[i % PALETTE.length]
488
- };
489
- });
490
- gridEls.push(h(rc.Legend, { key: 'legend', payload: legendPayload }));
491
- } else if (showLegend) {
492
- gridEls.push(h(rc.Legend, { key: 'legend' }));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  }
494
 
495
- var chart = h(ChartComponent, chartProps,
496
- gridEls.concat(seriesEls)
497
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498
 
499
- // Use ReactDOM.render for Recharts v2.12.7 compatibility
500
- // Render chart directly without ResponsiveContainer to avoid coordinate scaling issues
501
- var mount = document.getElementById('chart-mount');
502
- var el = h('div', {},
503
- (chartTitle || chartDesc) && h('div', { className: 'chart-header' },
504
- chartTitle && h('div', { className: 'chart-title' }, chartTitle),
505
- chartDesc && h('div', { className: 'chart-desc' }, chartDesc)
506
- ),
507
- chart,
508
- chartFooter && h('div', { className: 'chart-footer' }, chartFooter)
509
- );
510
- if (ReactDOM.render) {
511
- ReactDOM.render(el, mount);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  } else {
513
- ReactDOM.createRoot(mount).render(el);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  window._widgetRendered = true;
516
  } catch (err) {
517
- document.getElementById('widget-container').innerHTML = '<div style="padding:20px;color:#c00;">Chart render error: ' + err.message + '</div>';
 
518
  window._widgetRendered = true;
519
  }
520
  })();
521
- <\/script>
522
- </body></html>`;
523
  }
524
 
525
- module.exports = { buildChatGPTChartHtml };
 
1
  /**
2
+ * buildChatGPTChartHtml — ChatGPT charts_widget_v2 spec → 完整渲染 HTML
3
  *
4
+ * 单一事实源:backend-service(本目录)与桌面 APP(…/src-tauri/pdf-render/)共用同一份实现,
5
+ * 由 make/build-pdf-render-assets.mjs 同步并逐字节校验;两端调用点都**整体下传 spec**。
 
 
6
  *
7
+ * 为什么入参是「整个 spec 对象」而不是逐个字段:官方 spec 的 zod schema 是 `.loose()`
8
+ * (未知键原样透传),一旦按位置白名单解构,新键就会静默丢失——这正是 2026-10-14
9
+ * 用户报告「饼图导出与网页不一致」的结构性根因(layout / xAxisScale 就是这样被丢掉的)。
10
+ *
11
+ * ── 契约取证(2026-10-14,逐字 + 真机 DOM 双证,证据目录 temp/test/chatgpt/2026-10-14-chart-pie/)──
12
+ * 官方 = ChatGPT widget 组件(chunk 44829 qOl)驱动 **Recharts v3**(本模块用 3.10.1 UMD):
13
+ * · 698208 模块 VTN:spec zod schema 全集 = {axes, chartType∈{bar,line,pie,scatter}, data,
14
+ * layout, meta{description,footer,title}, nameKey, series[{axisLabel,dataKey,label,stack,
15
+ * valueFormat∈{compact,integer,raw},valuePrefix,valueSuffix}], valueFormat, valueKey,
16
+ * valuePrefix, valueSuffix, xAxisLabel, xAxisScale, xKey}
17
+ * · 44829 uNo:调色板 6 色 light ['blue','green','orange','yellow','purple','pink'],
18
+ * 系列色 = palette[i%6];pie 的 colorCount = **data.length**(逐扇区上色)
19
+ * · 44829 AXa/qOl A:pie 恒为**环形图** innerRadius 40% / outerRadius 78% / startAngle 90 /
20
+ * endAngle -270 / paddingAngle .5 / sliceStrokeWidth 2 / stroke var(--color-surface),
21
+ * **不画数值标签、不画引导线**(showValueLabels/showLabelLines 默认 false),tooltip 为 percent
22
+ * · 44829 qOl w()/o()/i():数据规整(NaN→null)、x 轴 labels 取自 data 行(非 axes)、
23
+ * y 轴只认「恰好一条 dimension=y」的轴;axes[].label / series[].axisLabel / xAxisLabel /
24
+ * formattedData / yAxisMin / yAxisMax 官方**一律不消费**
25
+ * · 726342 IMu:barCategoryGapPx = 容器宽>=768?12:8 再按 dataLength 收敛(>=24→min3,>=16→min6);
26
+ * barRadius 按估算条厚分档 56→8 / 36→6 / 16→4 / 0→2;maxBarSize 除「2行×2系列」外恒 120(水平 48)
27
+ * · recharts v3 Legend.defaultProps.itemSorter='value' → 图例按标签升序(v2 无此行为,
28
+ * 这正是 pie 图例顺序与网页不一致的原因;换 v3 后由引擎自己给出,无需手工排序)
29
+ * 验证:verify-fidelity.mjs 对 13 张真实图表逐值比对官方 DOM oracle → 384/401 = 95.8%
30
+ * (现网旧实现同口径 34.2%;同移植层跑 v2 引擎 94.3%,差的全是 pie 图例顺序)
31
+ * 已知残差(实测,非猜测):① 官方对个别超长 y 刻度会折行(本实现不折);② 官方偶发
32
+ * 轴宽测量滞后(多留 ~16px 左内边距),不追平。
33
  */
34
+ const OFFICIAL = {
35
+ // 44829 uNo:light/dark 两套 6 色,顺序固定 blue→green→orange→yellow→purple→pink
36
+ PALETTE_ORDER: ['blue', 'green', 'orange', 'yellow', 'purple', 'pink'],
37
+ PALETTE: {
38
+ light: { blue: '#539af8', green: '#6bc67f', orange: '#ef8b57', yellow: '#f8d45d', purple: '#b897f4', pink: '#f68ebc' },
39
+ dark: { blue: '#1f4e94', green: '#3a843f', orange: '#ac4f23', yellow: '#d9a337', purple: '#7849d1', pink: '#ab4f7a' },
40
+ },
41
+ // AXa:slice stroke = var(--color-surface);light 主题实测 rgb(243,243,243)
42
+ SURFACE_LIGHT: '#f3f3f3',
43
+ SLICE_STROKE_WIDTH: 2,
44
+ // AXa 默认 + qOl/A 覆盖(pie 无档位函数,全是字面量)
45
+ PIE: { innerRadius: '40%', outerRadius: '78%', startAngle: 90, endAngle: -270, paddingAngle: 0.5, legendMaxRows: 2 },
46
+ // qOl/j:barRadius 缺省 8;showDots = line && dataLen<=40;showLegend = series>1
47
+ BAR_RADIUS: 8,
48
+ // 745098 categorical 默认
49
+ MARGIN: { top: 5, right: 5, bottom: 5, left: 5 },
50
+ BAR_GAP: 4,
51
+ MAX_BAR_SIZE_H: 120,
52
+ MAX_BAR_SIZE_V: 48,
53
+ // 官方两轴:axisLine/tickLine 关、tickMargin 4(qOl o()/r())
54
+ TICK_MARGIN: 4,
55
+ GRID: { stroke: '#ccc', dasharray: '3 3' },
56
+ TICK: { fontSize: 12, fill: '#5d5d5d' },
57
+ // 轴内边距:2026-10-14 用 10 张真实图逐值拟合 → axisW = ceil(maxLabelW) + tickMargin(4),无额外内边距
58
+ // (备忘录 119 的 PAD=6 是在旧一次捕获上标定的,本次同一图表 grid.x1 已从 86 变 80)
59
+ Y_AXIS_PAD: 0,
60
+ // 卡片:title 16/600/#0d0d0d lh24;desc 14/400/#5d5d5d lh20 mt4;legend 14/#0d0d0d
61
+ LEGEND: { fontSize: 14, color: '#0d0d0d', marker: 10, gapX: 16, gapY: 6, padTop: 12, itemPadX: 8, itemPadY: 4, itemGap: 6, maxRows: 2 },
62
+ };
 
 
 
 
 
 
 
 
63
 
64
+ // ── 页内渲染脚本(与 Node 侧共享同���份契约常量,经 JSON 注入) ──
65
+ function buildChatGPTChartHtml(spec, opts) {
66
+ // 兼容旧的位置参数签名(桌面端 Rust 未重编窗口期,2026-10-13 部署约束)
67
+ if (typeof spec === 'string' || (spec && spec.chartType === undefined && arguments.length > 1)) {
68
+ var a = arguments;
69
+ spec = {
70
+ chartType: a[0], series: a[1], data: a[2], xKey: a[3], nameKey: a[4],
71
+ valueKey: a[5], formattedData: a[6], axes: a[7],
72
+ meta: (a[8] && typeof a[8] === 'object') ? a[8] : { title: a[8] || '', description: a[9] || '' },
73
+ };
74
+ opts = {};
75
+ }
76
+ opts = opts || {};
77
+ // 官方 ChartWidget 只分发这 4 类,其余渲染为空 → 交回 null,由上层走 Markdown 表格兜底
78
+ if (['bar', 'line', 'pie', 'scatter'].indexOf(spec && spec.chartType) < 0) return null;
79
+ const engine = opts.engine === 'v2' ? 'v2' : 'v3';
80
+ const version = opts.version || (engine === 'v2' ? '2.12.7' : '3.10.1');
81
+ const width = opts.width || 719; // PDF 卡内容宽(官方卡宽 735 - body padding 8×2)
82
+ const height = opts.height || (spec && spec.chartType === 'pie' ? 348 : 340); // 官方实测卡内图高
83
+ const json = (v) => JSON.stringify(v).replace(/<\/script/gi, '<\\/script');
84
+ return `<!DOCTYPE html>
 
 
 
85
  <html><head><meta charset="UTF-8">
86
  <style>
87
+ body { margin:0; padding:8px; background:#fff; color:#0d0d0d;
88
+ font-family:-apple-system-body, ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, 'Apple Color Emoji', Arial, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; }
89
+ .xwx-chart-card { box-sizing:border-box; display:flex; flex-direction:column; }
90
+ .xwx-chart-body { flex:1 1 auto; min-height:0; }
91
+ /* 截图目标容器按官方卡宽定尺,避免 PNG 两侧留白 */
 
 
 
 
 
92
  #widget-container { width: 735px; }
93
+ /* 官方实测:刻度文字 12px/#5d5d5d/400(官方 CSS 把 recharts 默认 #666 覆盖为 rgb(93,93,93)) */
94
+ .recharts-wrapper text { font-size:12px; fill:#5d5d5d; font-weight:400;
95
+ font-family:-apple-system-body, ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; }
96
+ /* 官方 bar 刻度:12px / #5d5d5d / 居中,foreignObject 盒高 1.5em */
97
+ .xwx-xtick { font-size:12px; line-height:12px; color:#5d5d5d; text-align:center; font-weight:400; }
98
  </style>
99
  <script src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"><\/script>
100
  <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"><\/script>
101
  <script src="https://unpkg.com/react-is@18.2.0/umd/react-is.production.min.js"><\/script>
102
  <script src="https://unpkg.com/prop-types@15.8.1/prop-types.min.js"><\/script>
103
+ <script src="https://unpkg.com/recharts@${version}/umd/Recharts.js"><\/script>
104
  </head><body>
105
+ <div id="widget-container"></div>
106
  <script>
107
  window._widgetRendered = false;
108
+ window._widgetError = null;
109
+ (function () {
110
+ var O = ${json(OFFICIAL)};
111
+ var SPEC = ${json(spec)};
112
+ var BOX = ${json({ width, height, cardWidth: opts.cardWidth || 735 })};
113
  try {
114
+ var rc = Recharts, h = React.createElement;
115
+ var chartType = SPEC.chartType;
116
+ // 官方 M():t = {bar, line, pie, scatter},其余 chartType 官方渲染为空
117
+ if (['bar', 'line', 'pie', 'scatter'].indexOf(chartType) < 0) {
118
+ // 官方 ChartWidget 只分发这 4 类,其余渲染为空;此处交回 null 让上层走 Markdown 表格兜底
119
+ window._widgetUnsupported = true; window._widgetRendered = true; return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  }
121
+ var series = (SPEC.series || []).filter(function (s) { return s && typeof s === 'object'; });
122
+ var isPie = chartType === 'pie';
123
+ // 官方取色:pie 按扇区数、笛卡尔按系列数;spec 自带的 color 一律丢弃重灌
124
+ var colors = makePalette(isPie ? (SPEC.data || []).length : series.length);
125
 
126
+ function makePalette(n) {
127
+ return Array.from({ length: n }, function (_, t) {
128
+ return O.PALETTE.light[O.PALETTE_ORDER[t % O.PALETTE_ORDER.length]];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  });
130
+ }
131
+ function isNum(v) { return typeof v === 'number' && isFinite(v); }
132
+ function collapseWs(v) { return v == null ? '' : String(v).replace(/\\s+/g, ' ').trim(); }
133
+ function truncate20(t) { return t.length <= 20 ? t : t.slice(0, 19).replace(/\\s+$/, '') + '…'; }
134
 
135
+ function normalizeCartesianRows() {
136
+ var rows = (SPEC.data || []).length ? SPEC.data : (function () {
137
+ var r = {}; r[SPEC.xKey] = chartType === 'scatter' ? 0 : '';
138
+ series.forEach(function (s) { r[s.dataKey] = null; });
139
+ return [r];
140
+ })();
141
+ return rows.map(function (row) {
142
+ var out = {};
143
+ Object.keys(row || {}).forEach(function (k) {
144
+ var v = row[k];
145
+ out[k] = v == null ? null : isNum(v) ? v : (typeof v === 'string' || typeof v === 'boolean') ? v : String(v);
146
  });
147
+ return out;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  }
150
+ function normalizePieRows() {
151
+ return (SPEC.data || []).map(function (row, i) {
152
+ var out = {};
153
+ Object.keys(row || {}).forEach(function (k) {
154
+ var v = row[k];
155
+ out[k] = (isNum(v) || typeof v === 'string') ? v : v == null ? '' : String(v);
156
+ });
157
+ out.fill = colors[i % Math.max(1, colors.length)];
158
+ out.stroke = O.SURFACE_LIGHT;
159
+ return out;
160
+ });
161
  }
162
+ function fmtValue(v, s) {
163
+ if (!isNum(v)) return v == null ? null : String(v);
164
+ var t;
165
+ try {
166
+ if (s && s.valueFormat === 'integer') t = new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(v);
167
+ else if (s && s.valueFormat === 'raw') t = String(v);
168
+ else if (s && s.valueFormat === 'compact') t = new Intl.NumberFormat(undefined, { compactDisplay: 'short', maximumFractionDigits: 1, notation: 'compact' }).format(v);
169
+ else t = new Intl.NumberFormat(undefined).format(v);
170
+ } catch (e) { t = String(v); }
171
+ return ((s && s.valuePrefix) || '') + t + ((s && s.valueSuffix) || '');
172
  }
173
+ function tickFormatter(labels, s) {
174
+ return function (v) {
175
+ var k = String(v);
176
+ return labels && labels[k] !== undefined ? labels[k] : fmtValue(v, s);
177
+ };
 
178
  }
179
+ function buildXAxis(rows, gapPx) {
180
+ var isHBar = chartType === 'bar' && SPEC.layout === 'vertical';
181
+ var numericLine = chartType === 'line' && SPEC.xAxisScale === 'linear'
182
+ && (SPEC.data || []).length > 0 && SPEC.data.every(function (r) { return isNum(r[SPEC.xKey]); });
183
+ var labels = {};
184
+ rows.forEach(function (r) {
185
+ var t = r[SPEC.xKey];
186
+ if (t != null) labels[String(t)] = isHBar ? truncate20(collapseWs(t)) : collapseWs(t);
 
 
 
 
187
  });
188
+ var cfg = { axisLine: false, dataKey: SPEC.xKey, labels: labels, tickMargin: O.TICK_MARGIN };
189
+ if (isHBar) cfg.interval = 0;
190
+ else {
191
+ if (chartType === 'scatter' || numericLine) cfg.type = 'number';
192
+ if (numericLine) cfg.domain = ['dataMin', 'dataMax'];
193
+ if (chartType === 'bar') cfg.padding = { left: gapPx / 2, right: gapPx / 2 };
194
+ else if (chartType === 'line') cfg.padding = { left: 12, right: 12 };
 
 
 
 
 
 
 
 
 
 
 
 
195
  }
196
+ return cfg;
197
+ }
198
+ function buildYAxis() {
199
+ var cfg = { domain: ['auto', 'auto'], axisLine: false, tickLine: false, tickMargin: O.TICK_MARGIN };
200
+ var ys = (SPEC.axes || []).filter(function (a) { return a && a.dimension === 'y'; });
201
+ if (ys.length !== 1) return cfg;
202
+ var a = ys[0];
203
+ if (a.domain != null) cfg.domain = a.domain;
204
+ if (Array.isArray(a.ticks)) {
205
+ var finite = a.ticks.filter(function (t) { return t && isNum(t.value); });
206
+ if (finite.length) {
207
+ cfg.ticks = finite.map(function (t) { return t.value; });
208
+ var labels = {};
209
+ finite.forEach(function (t) { if (t.label != null) labels[t.value] = t.label; });
210
+ if (Object.keys(labels).length) cfg.labels = labels;
 
211
  }
 
212
  }
213
+ return cfg;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  }
215
+ // 官方 y 轴宽 = 实测最长刻度标签 + tickMargin(引擎的 width:'auto' 恒比官方宽 6px;
216
+ // 2026-10-14 用 10 张真实图逐值拟合:axisW = ceil(labelW) + 4,9/10 命中 ±1px)。
217
+ function makeTick(formatter, anchor) {
218
+ return function (p) {
219
+ var v = p.payload ? p.payload.value : p.value;
220
+ return h('text', { x: p.x, y: p.y, dy: '0.355em', 'text-anchor': anchor,
221
+ 'font-size': O.TICK.fontSize, fill: O.TICK.fill, 'font-weight': 400,
222
+ 'font-family': getComputedStyle(document.body).fontFamily }, String(formatter(v)));
223
+ };
224
+ }
225
+ function measureYAxisWidth(ya) {
226
+ var fmt = tickFormatter(ya.labels, series[0]);
227
+ var vals = ya.ticks && ya.ticks.length ? ya.ticks
228
+ : rows.map(function (r) { return r[series[0] && series[0].dataKey]; }).filter(function (v) { return isNum(v); });
229
+ if (!vals.length) return 60;
230
+ var probe = document.createElement('span');
231
+ probe.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap;left:-9999px;top:0;font-size:' + O.TICK.fontSize + 'px;font-family:' + getComputedStyle(document.body).fontFamily;
232
+ document.body.appendChild(probe);
233
+ var maxW = 0;
234
+ vals.forEach(function (v) { probe.textContent = String(fmt(v)); maxW = Math.max(maxW, probe.offsetWidth); });
235
+ document.body.removeChild(probe);
236
+ return Math.ceil(maxW) + O.TICK_MARGIN + O.Y_AXIS_PAD;
237
+ }
238
+ // 74115 官方 bar 刻度件:foreignObject 盒宽 = (图宽-左右padding)/行数 - 8,最小 12,居中于刻度点
239
+ function makeHtmlTick(nTicks, fmt) {
240
+ return function (p) {
241
+ var pad = p.padding || {};
242
+ var d = Math.max(12, (p.width - ((pad.left || 0) + (pad.right || 0))) / Math.max(1, nTicks) - 8);
243
+ return h('foreignObject', { x: p.x - d / 2, y: p.y, width: d, height: '1.5em' },
244
+ h('div', { className: 'xwx-xtick' }, String(fmt(p.payload ? p.payload.value : '', p.index))));
245
+ };
246
+ }
247
+ // 官方 legend 内容件(AXa b()):10px 圆点 + truncate 文本,flex-wrap,maxRows 限高
248
+ function legendContent(p) {
249
+ var payload = (p && p.payload) || [];
250
+ if (!payload.length) return null;
251
+ var L = O.LEGEND;
252
+ var maxRows = L.maxRows;
253
+ var items = payload.map(function (it) {
254
+ var val = it.value != null ? String(it.value) : '';
255
+ if (val === '') return null;
256
+ return h('div', {
257
+ key: val,
258
+ style: { display: 'flex', alignItems: 'center', gap: L.itemGap + 'px', maxWidth: '100%', minWidth: 0, padding: L.itemPadY + 'px ' + L.itemPadX + 'px' },
259
+ },
260
+ h('div', { style: { width: L.marker + 'px', height: L.marker + 'px', flex: '0 0 auto', borderRadius: '9999px', background: it.color } }),
261
+ h('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, val));
262
+ }).filter(Boolean);
263
+ return h('div', {
264
+ style: {
265
+ display: 'flex', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap',
266
+ columnGap: L.gapX + 'px', rowGap: L.gapY + 'px', paddingTop: L.padTop + 'px',
267
+ maxHeight: (28 * maxRows + 6 * (maxRows - 1) + 12) + 'px', overflow: 'hidden',
268
+ fontSize: L.fontSize + 'px', color: L.color,
269
+ },
270
+ }, items);
271
  }
272
 
273
+ var rows, children = [];
274
+ var showLegend, legendPayload = null;
275
+ // ── 官方几何档位(726342 IMu):只依赖 spec 与容器,两分支共用 ──
276
+ var dataLen = (SPEC.data || []).length;
277
+ var nSeries = (function () {
278
+ var stacks = {}, unstacked = 0;
279
+ series.forEach(function (s) { if (s.stack == null) unstacked += 1; else stacks[s.stack] = 1; });
280
+ return Math.max(1, Object.keys(stacks).length + unstacked);
281
+ })();
282
+ var isHBar = chartType === 'bar' && SPEC.layout === 'vertical';
283
+ // IMu d():ResizeObserver 量的是卡片容器宽(非 svg 宽),>=768 → 12 否则 8;再按 dataLength 收敛
284
+ var defaultGapPx = BOX.cardWidth >= 768 ? 12 : 8;
285
+ var gapPx = dataLen >= 24 ? Math.min(defaultGapPx, 3) : dataLen >= 16 ? Math.min(defaultGapPx, 6) : defaultGapPx;
286
+ // IMu u():barRadius 分档 = 估算条厚 (containerSize/dataLen/nSeries*0.65) 落档
287
+ var est = (isHBar ? BOX.height : BOX.width) / Math.max(1, dataLen) / nSeries * 0.65;
288
+ var barRadius = est >= 56 ? 8 : est >= 36 ? 6 : est >= 16 ? 4 : 2;
289
+ // IMu s():**除「2 行 �� 2 系列」外**恒给 maxBarSize(fiber 实测 120/48 逐字确认)
290
+ var maxBarSize = (dataLen === 2 && nSeries === 2) ? undefined : (isHBar ? 48 : 120);
291
 
292
+ if (isPie) {
293
+ rows = normalizePieRows();
294
+ if (!(SPEC.series || []).length) { document.getElementById('widget-container').innerHTML = ''; window._widgetRendered = true; return; }
295
+ var s0 = SPEC.series[0] || {};
296
+ var valueKey = SPEC.valueKey || s0.dataKey || 'value';
297
+ var nameKey = SPEC.nameKey; // 官方 A():xAxis = spec.nameKey;nameKey 缺失时官方显示 "Slice N"
298
+ var pieData = rows.map(function (r) {
299
+ var o2 = {}; Object.keys(r).forEach(function (k) { o2[k] = r[k]; });
300
+ o2.__sliceLabel = nameKey != null && r[nameKey] != null ? String(r[nameKey]) : '';
301
+ return o2;
302
+ });
303
+ var P = O.PIE;
304
+ children.push(h(rc.Legend, { key: 'lg', content: legendContent }));
305
+ children.push(h(rc.Pie, {
306
+ key: 'pie',
307
+ data: pieData,
308
+ dataKey: valueKey,
309
+ nameKey: '__sliceLabel',
310
+ cx: '50%', cy: '50%',
311
+ innerRadius: P.innerRadius, outerRadius: P.outerRadius,
312
+ startAngle: P.startAngle, endAngle: P.endAngle,
313
+ paddingAngle: P.paddingAngle,
314
+ isAnimationActive: false,
315
+ label: false, labelLine: false,
316
+ }, pieData.map(function (d, i) {
317
+ return h(rc.Cell, { key: i, fill: d.fill, stroke: d.stroke, strokeWidth: O.SLICE_STROKE_WIDTH });
318
+ })));
319
+ showLegend = true;
320
  } else {
321
+ rows = normalizeCartesianRows();
322
+ var xa = buildXAxis(rows, gapPx), ya = buildYAxis();
323
+ var ChartComp = chartType === 'line' ? rc.LineChart : chartType === 'scatter' ? rc.ScatterChart : rc.BarChart;
324
+ children.push(h(rc.CartesianGrid, {
325
+ key: 'grid', horizontal: true, vertical: false, stroke: O.GRID.stroke, strokeDasharray: O.GRID.dasharray,
326
+ }));
327
+ children.push(h(rc.XAxis, {
328
+ key: 'x', dataKey: xa.dataKey, type: xa.type || 'category', domain: xa.domain,
329
+ axisLine: false, tickLine: false, tickMargin: xa.tickMargin, padding: xa.padding,
330
+ interval: xa.interval, ticks: xa.ticks, minTickGap: 10,
331
+ tickFormatter: tickFormatter(xa.labels, series[0]),
332
+ // 74115 官方 primitive:仅 bar 用 foreignObject+div 刻度(可截断/换行),line/scatter 用引擎默认
333
+ // 官方 x 刻度:bar 用 foreignObject+div(可截断),line/scatter 用引擎默认 <text>
334
+ // (默认件带 dy=2/3em 基线,自定义直绘会整体抬高 ~4px)
335
+ tick: chartType === 'bar' ? makeHtmlTick(dataLen, tickFormatter(xa.labels, series[0])) : undefined,
336
+ }));
337
+ children.push(h(rc.YAxis, {
338
+ key: 'y', domain: ya.domain, ticks: ya.ticks, axisLine: false, tickLine: false,
339
+ tickMargin: ya.tickMargin, width: measureYAxisWidth(ya),
340
+ // 引擎默认 Text 的换行估算偏大(把 "260 千美元" 这类长标签全部折行,官方不折),
341
+ // 故 y 轴同样直绘 <text>;官方仅在 1/10 样本上折过 1 个标签(见备忘录 120 已知残差)。
342
+ tick: makeTick(tickFormatter(ya.labels, series[0]), 'end'),
343
+ tickFormatter: tickFormatter(ya.labels, series[0]),
344
+ }));
345
+ series.forEach(function (s, i) {
346
+ var color = colors[i % colors.length];
347
+ if (chartType === 'bar') {
348
+ children.push(h(rc.Bar, {
349
+ key: 'b' + i, dataKey: s.dataKey, name: s.label || s.dataKey,
350
+ fill: color, stroke: color, radius: barRadius,
351
+ stackId: s.stack != null ? s.stack : undefined,
352
+ maxBarSize: maxBarSize,
353
+ isAnimationActive: false,
354
+ }));
355
+ } else if (chartType === 'line') {
356
+ children.push(h(rc.Line, {
357
+ key: 'l' + i, dataKey: s.dataKey, name: s.label || s.dataKey, type: 'linear',
358
+ stroke: color, strokeWidth: 2, dot: (SPEC.data || []).length <= 40, activeDot: false,
359
+ connectNulls: true, isAnimationActive: false,
360
+ }));
361
+ } else {
362
+ children.push(h(rc.Scatter, {
363
+ key: 's' + i, dataKey: s.dataKey, name: s.label || s.dataKey, fill: color,
364
+ }));
365
+ }
366
+ });
367
+ showLegend = series.length > 1;
368
+ if (showLegend) children.push(h(rc.Legend, { key: 'lg', content: legendContent }));
369
  }
370
+
371
+ var Comp = isPie ? rc.PieChart : (chartType === 'line' ? rc.LineChart : chartType === 'scatter' ? rc.ScatterChart : rc.BarChart);
372
+ var chartProps = { data: rows, width: BOX.width, height: BOX.height, margin: O.MARGIN };
373
+ // 官方 fiber 实测:barCategoryGap / barGap 挂在**图表层**(不是 Bar 上)
374
+ if (chartType === 'bar') {
375
+ chartProps.barCategoryGap = isHBar ? '12%' : gapPx;
376
+ chartProps.barGap = O.BAR_GAP;
377
+ }
378
+ // 官方 j():只有笛卡尔系传 layout(spec.layout 原值,缺省交回引擎默认);pie 从不传
379
+ if (!isPie && SPEC.layout) chartProps.layout = SPEC.layout;
380
+ var meta = SPEC.meta || {};
381
+ var tree = h('div', { className: 'xwx-chart-card' },
382
+ (meta.title || meta.description) && h('div', {},
383
+ meta.title && h('div', { style: { fontSize: '16px', fontWeight: 600, color: '#0d0d0d', lineHeight: '24px', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' } }, meta.title),
384
+ meta.description && h('p', { style: { fontSize: '14px', fontWeight: 400, color: '#5d5d5d', lineHeight: '20px', margin: '4px 0 0', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' } }, meta.description)),
385
+ h('div', { className: 'xwx-chart-body' }, h(Comp, chartProps, children)),
386
+ meta.footer && h('div', { style: { fontSize: '12px', color: '#8f8f8f', lineHeight: '16px', marginTop: '10px' } }, meta.footer));
387
+
388
+ var mount = document.getElementById('widget-container');
389
+ if (ReactDOM.createRoot) ReactDOM.createRoot(mount).render(tree);
390
+ else ReactDOM.render(tree, mount);
391
  window._widgetRendered = true;
392
  } catch (err) {
393
+ window._widgetError = String((err && err.message) || err);
394
+ document.getElementById('widget-container').innerHTML = '<div style="padding:20px;color:#c00">Chart render error: ' + window._widgetError + '</div>';
395
  window._widgetRendered = true;
396
  }
397
  })();
398
+ <\/script></body></html>`;
 
399
  }
400
 
401
+ module.exports = { buildChatGPTChartHtml, OFFICIAL_CONTRACT: OFFICIAL };
server.js CHANGED
@@ -953,12 +953,10 @@ class WidgetRenderer {
953
  }
954
 
955
  // ─── ChatGPT charts_widget_v2 Rendering ─────────────────
956
- // Uses Puppeteer with Recharts v2.15.4 CDN (v3 SSR is broken).
957
- // html parameter is JSON string of chart data:
958
- // { chartType, meta: {title, description, footer}, xKey, yKey, series[], data[] }
959
- // meta 整体下传给构建器:标题/描述/脚注只来自 spec 的 meta 字段——
960
- // 调用方 title(part.title,是 meta.description 的回退)绝不能进画面,
961
- // 否则 description 会在 PNG 里渲染两遍(2026-10-13 用户报告的重复根因)。
962
 
963
  async renderChatGPTChart(dataJson, title) {
964
  const startTime = Date.now();
@@ -973,20 +971,16 @@ class WidgetRenderer {
973
  }
974
 
975
  const chartType = chartData.chartType || 'bar';
976
- const series = chartData.series || [];
977
- const data = chartData.data || [];
978
- const xKey = chartData.xKey || 'x';
979
- const nameKey = chartData.nameKey || '';
980
- const valueKey = chartData.valueKey || '';
981
- const formattedData = chartData.formattedData || [];
982
- const axes = chartData.axes || [];
983
  const meta = chartData.meta || {};
 
984
 
985
- console.log(`[WIDGET] renderChatGPTChart: type=${chartType}, series=${series.length}, rows=${data.length}, xKey=${xKey}, axes=${axes.length}`);
986
-
987
- const html = this.buildChatGPTChartHtml(chartType, series, data, xKey, nameKey, valueKey, formattedData, axes, meta);
 
 
 
988
 
989
- // title 仅进日志与 <img alt>,画面内容全部由构建器按 meta 渲染
990
  return this._renderFullHtml(html, (meta && meta.title) || title || 'chatgpt_chart', 8000, chartType);
991
  }
992
 
 
953
  }
954
 
955
  // ─── ChatGPT charts_widget_v2 Rendering ─────────────────
956
+ // 渲染引擎与官方对齐:Recharts v3 UMD(官方 = chunk 44829 qOl 驱动 Recharts v3)。
957
+ // spec **整体**交给构建器,不再按位置挑字段——官方 schema 是 .loose(),逐字段白名单
958
+ // 会让新键静默丢失(layout / xAxisScale 即因此被丢掉,证据见 temp/test/chatgpt/2026-10-14-chart-pie/)。
959
+ // 画面内容(标题/描述/脚注)只来自 spec.meta;调用方 title 仅进日志与 <img alt>。
 
 
960
 
961
  async renderChatGPTChart(dataJson, title) {
962
  const startTime = Date.now();
 
971
  }
972
 
973
  const chartType = chartData.chartType || 'bar';
 
 
 
 
 
 
 
974
  const meta = chartData.meta || {};
975
+ console.log(`[WIDGET] renderChatGPTChart: type=${chartType}, series=${(chartData.series || []).length}, rows=${(chartData.data || []).length}, xKey=${chartData.xKey}, axes=${(chartData.axes || []).length}, layout=${chartData.layout || '-'}`);
976
 
977
+ // 官方只分发 bar/line/pie/scatter;其余返回 null → 上层回退成 Markdown 表格
978
+ const html = this.buildChatGPTChartHtml(chartData);
979
+ if (!html) {
980
+ console.log(`[WIDGET] renderChatGPTChart SKIP: chartType=${chartType} 非官方支持类型`);
981
+ return null;
982
+ }
983
 
 
984
  return this._renderFullHtml(html, (meta && meta.title) || title || 'chatgpt_chart', 8000, chartType);
985
  }
986