XWX-AI commited on
Commit
b689996
·
1 Parent(s): 7ffc5c1

fix(chart): GPT-6 charts_widget_v2 PDF渲染重写对齐官方网页契约(备忘录119)——①lib/chatgpt-chart-html.js按官方v2契约重写: 渐变圆角柱(stopOpacity1→0.9+radius8+barCategoryGap自适应3/6/8+maxBarSize120)/仅横向#ccc"3 3"网格/12px rgb(93,93,93)刻度轴无边线/图例=series>1才显示/header固定块min-height68px+line-clamp2/footer固定; ②server.js meta整包下传(title/description单一来源修双写重复)+legacy字符串签名归一; ③Recharts v2.12.7两引擎坑实测修复: YAxis width:'auto'整图不渲染→隐藏span逐标签offsetWidth量宽+TICK_MARGIN4+Y_AXIS_PAD6(官方81=71+4+6), 默认tick Text按16px估宽致长标签tspan折行丢空格→双轴自定义<text>组件; ④验证: verify-r1 34项DOM契约全过+pdf-test容器(17861)E2E渲染比对官方常量一致(2026-10-13)。生产space/main未推送(用户指示:会影响生产环境)

Browse files
Files changed (2) hide show
  1. lib/chatgpt-chart-html.js +192 -85
  2. server.js +7 -5
lib/chatgpt-chart-html.js CHANGED
@@ -1,50 +1,102 @@
1
  /**
2
  * buildChatGPTChartHtml — ChatGPT charts_widget_v2 数据 → 完整渲染 HTML
3
  *
4
- * 单一事实源:backend-service(本目录)与桌面 APP(xwx-backup/app/src-tauri/pdf-render/)
5
- * 共用同一份实现。桌面端通过 make/build-pdf-render-assets.mjs 同步并做指纹校验。
6
- * 提取自 server.js WidgetRenderer.buildChatGPTChatHtml 原实现(函数体逐字节一致,
7
- * 仅类方法→独立函数)。修改时保持两端同步流程:先改这里,再跑 make 脚本同步。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  */
9
- function buildChatGPTChartHtml(chartType, series, data, xKey, nameKey, valueKey, formattedData, axes, title, description) {
10
- // ChatGPT official chart color palette (extracted from live ChatGPT web)
11
- // ChatGPT official chart color palette (first 4) + D3 schemeCategory10 extended (10 total)
12
- // D3 schemeCategory10: industry-standard categorical palette, colorblind-friendly
13
- const COLORS = ['#339CFF', '#40C977', '#FF8549', '#FFD240', '#6366f1', '#ec4899', '#14b8a6', '#f97316', '#8b5cf6', '#06b6d4'];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  // Serialize data safely for inline script
16
- const dataJson = JSON.stringify(data || [])
17
- .replace(/<\/script/gi, '<\\/script');
18
- const seriesJson = JSON.stringify(series || [])
19
- .replace(/<\/script/gi, '<\\/script');
20
- const chartTypeJson = JSON.stringify(chartType || 'bar')
21
- .replace(/<\/script/gi, '<\\/script');
22
- const titleJson = JSON.stringify(title || '')
23
- .replace(/<\/script/gi, '<\\/script');
24
- const descJson = JSON.stringify(description || '')
25
- .replace(/<\/script/gi, '<\\/script');
26
- const xKeyJson = JSON.stringify(xKey || 'x')
27
- .replace(/<\/script/gi, '<\\/script');
28
- const nameKeyJson = JSON.stringify(nameKey || '')
29
- .replace(/<\/script/gi, '<\\/script');
30
- const valueKeyJson = JSON.stringify(valueKey || '')
31
- .replace(/<\/script/gi, '<\\/script');
32
- const formattedDataJson = JSON.stringify(formattedData || [])
33
- .replace(/<\/script/gi, '<\\/script');
34
- const axesJson = JSON.stringify(axes || [])
35
- .replace(/<\/script/gi, '<\\/script');
 
36
 
37
  return `<!DOCTYPE html>
38
  <html><head><meta charset="UTF-8">
39
  <style>
40
- body { margin: 0; padding: 12px; background: #ffffff; font-family: system-ui, -apple-system, sans-serif; }
41
- .chart-title { font-size: 16px; font-weight: 600; margin-bottom: 4px; color: #111827; }
42
- .chart-subtitle { font-size: 12px; color: #6b7280; margin-bottom: 12px; }
43
- #widget-container { width: 720px; min-height: 300px; }
44
- /* Widen container to prevent last data point dot from overflowing SVG boundary.
45
- Recharts plots the last point at the plotting area edge; the dot (r=4-6) extends
46
- beyond. 720px gives ~70px extra right padding after the Y-axis. */
47
- .recharts-wrapper { margin: 0 auto; }
 
 
 
48
  </style>
49
  <script src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"><\/script>
50
  <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"><\/script>
@@ -52,7 +104,7 @@ function buildChatGPTChartHtml(chartType, series, data, xKey, nameKey, valueKey,
52
  <script src="https://unpkg.com/prop-types@15.8.1/prop-types.min.js"><\/script>
53
  <script src="https://unpkg.com/recharts@2.12.7/umd/Recharts.js"><\/script>
54
  </head><body>
55
- <div id="widget-container"></div>
56
  <script>
57
  window._widgetRendered = false;
58
  (function() {
@@ -61,18 +113,28 @@ window._widgetRendered = false;
61
  var chartSeries = ${seriesJson};
62
  var chartTitle = ${titleJson};
63
  var chartDesc = ${descJson};
 
64
  var xKey = ${xKeyJson};
65
  var chartType = ${chartTypeJson};
66
  var nameKey = ${nameKeyJson};
67
  var valueKey = ${valueKeyJson};
68
  var formattedData = ${formattedDataJson};
69
  var chartAxes = ${axesJson};
70
-
71
- var COLORS = ${JSON.stringify(COLORS)};
 
 
 
 
 
 
72
 
73
  var rc = Recharts;
74
  var h = React.createElement;
75
 
 
 
 
76
  // ── Scatter chart: detect x-axis key ──
77
  var scatterXKey = xKey;
78
  if (chartType === 'scatter' && chartData.length > 0) {
@@ -159,53 +221,52 @@ window._widgetRendered = false;
159
  }
160
 
161
  // Build series elements
 
 
162
  var seriesEls = [];
163
- // Each series may carry additional Recharts props (stackId, radius, type, etc.)
164
- // that AI could generate. We pass them through to the component props.
165
  if (chartType === 'bar') {
166
  chartSeries.forEach(function(s, i) {
 
167
  var props = {
168
  dataKey: s.dataKey,
169
  name: s.label || s.dataKey,
170
- fill: s.color || COLORS[i % COLORS.length]
 
 
 
171
  };
172
  if (s.stackId !== undefined) props.stackId = s.stackId;
173
- if (s.radius !== undefined) props.radius = s.radius;
174
  if (s.barSize !== undefined) props.barSize = s.barSize;
175
- if (s.maxBarSize !== undefined) props.maxBarSize = s.maxBarSize;
176
- if (s.stroke !== undefined) props.stroke = s.stroke;
177
- if (s.strokeWidth !== undefined) props.strokeWidth = s.strokeWidth;
178
  if (s.unit !== undefined) props.unit = s.unit;
179
- if (s.label !== undefined) props.label = s.label;
180
  seriesEls.push(h(rc.Bar, props));
181
  });
182
  } else if (chartType === 'line') {
183
  chartSeries.forEach(function(s, i) {
 
184
  var props = {
185
- type: s.type || 'monotone',
186
  dataKey: s.dataKey,
187
  name: s.label || s.dataKey,
188
- stroke: s.color || COLORS[i % COLORS.length],
189
  strokeWidth: 2,
190
- dot: s.dot !== undefined ? s.dot : { r: 4 },
191
  connectNulls: s.connectNulls !== undefined ? s.connectNulls : true,
192
  isAnimationActive: false
193
  };
194
  if (s.strokeDasharray !== undefined) props.strokeDasharray = s.strokeDasharray;
195
- if (s.activeDot !== undefined) props.activeDot = s.activeDot;
196
- if (s.label !== undefined) props.label = s.label;
197
  if (s.unit !== undefined) props.unit = s.unit;
198
- if (s.fillOpacity !== undefined) props.fillOpacity = s.fillOpacity;
199
  seriesEls.push(h(rc.Line, props));
200
  });
201
  } else if (chartType === 'area') {
202
  chartSeries.forEach(function(s, i) {
 
203
  var props = {
204
- type: s.type || 'monotone',
205
  dataKey: s.dataKey,
206
  name: s.label || s.dataKey,
207
- fill: s.color || COLORS[i % COLORS.length],
208
- stroke: s.color || COLORS[i % COLORS.length],
209
  strokeWidth: 2,
210
  connectNulls: s.connectNulls !== undefined ? s.connectNulls : true,
211
  isAnimationActive: false
@@ -214,8 +275,6 @@ window._widgetRendered = false;
214
  if (s.baseValue !== undefined) props.baseValue = s.baseValue;
215
  if (s.strokeDasharray !== undefined) props.strokeDasharray = s.strokeDasharray;
216
  if (s.dot !== undefined) props.dot = s.dot;
217
- if (s.activeDot !== undefined) props.activeDot = s.activeDot;
218
- if (s.label !== undefined) props.label = s.label;
219
  if (s.unit !== undefined) props.unit = s.unit;
220
  if (s.stackId !== undefined) props.stackId = s.stackId;
221
  seriesEls.push(h(rc.Area, props));
@@ -225,12 +284,8 @@ window._widgetRendered = false;
225
  var props = {
226
  name: s.label || s.dataKey,
227
  dataKey: s.dataKey,
228
- fill: s.color || COLORS[i % COLORS.length]
229
  };
230
- if (s.shape !== undefined) props.shape = s.shape;
231
- if (s.activeDot !== undefined) props.activeDot = s.activeDot;
232
- if (s.line !== undefined) props.line = s.line;
233
- if (s.lineJointType !== undefined) props.lineJointType = s.lineJointType;
234
  if (s.unit !== undefined) props.unit = s.unit;
235
  seriesEls.push(h(rc.Scatter, props));
236
  });
@@ -243,7 +298,7 @@ window._widgetRendered = false;
243
  var pieColoredData = chartData.map(function(row, ri) {
244
  var copy = {};
245
  for (var _k in row) { copy[_k] = row[_k]; }
246
- copy.fill = COLORS[ri % COLORS.length];
247
  return copy;
248
  });
249
 
@@ -279,7 +334,7 @@ window._widgetRendered = false;
279
  name: s.label || s.dataKey,
280
  cx: '50%', cy: '50%',
281
  outerRadius: 100,
282
- innerRadius: 60,
283
  isAnimationActive: false,
284
  label: labelFormatter
285
  };
@@ -292,16 +347,14 @@ window._widgetRendered = false;
292
  });
293
  } else if (chartType === 'radar') {
294
  chartSeries.forEach(function(s, i) {
 
295
  var props = {
296
  dataKey: s.dataKey,
297
  name: s.label || s.dataKey,
298
- stroke: s.color || COLORS[i % COLORS.length],
299
- fill: s.color || COLORS[i % COLORS.length],
300
  fillOpacity: 0.3
301
  };
302
- if (s.dot !== undefined) props.dot = s.dot;
303
- if (s.activeDot !== undefined) props.activeDot = s.activeDot;
304
- if (s.strokeWidth !== undefined) props.strokeWidth = s.strokeWidth;
305
  if (s.unit !== undefined) props.unit = s.unit;
306
  seriesEls.push(h(rc.Radar, props));
307
  });
@@ -324,7 +377,12 @@ window._widgetRendered = false;
324
  default: ChartComponent = rc.BarChart;
325
  }
326
 
327
- var chartProps = { data: chartData, width: 720, height: 300 };
 
 
 
 
 
328
  if (chartType === 'radar') {
329
  chartProps.cx = '50%';
330
  chartProps.cy = '50%';
@@ -334,10 +392,38 @@ window._widgetRendered = false;
334
  }
335
 
336
  var gridEls = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  if (chartType !== 'pie' && chartType !== 'donut' && chartType !== 'radar') {
338
- gridEls.push(h(rc.CartesianGrid, { strokeDasharray: '3 3', key: 'grid' }));
 
339
  var axisKey = chartType === 'scatter' ? scatterXKey : xKey;
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  // ── XAxis: use axes[].dimension from API JSON ──
342
  // Find X axis config from axes array by dimension="x"
343
  var xAxisConfig = null;
@@ -347,7 +433,7 @@ window._widgetRendered = false;
347
  break;
348
  }
349
  }
350
- var xAxisProps = { dataKey: axisKey, key: 'x' };
351
  if (xAxisConfig && xAxisConfig.domain) { xAxisProps.domain = xAxisConfig.domain; }
352
  if (xAxisConfig && xAxisConfig.ticks) {
353
  var _xTickMap = {};
@@ -357,22 +443,39 @@ window._widgetRendered = false;
357
  xAxisProps.tickFormatter = function(v) { var k = String(v); return _xTickMap[k] !== undefined ? _xTickMap[k] : String(v); };
358
  }
359
  if (xAxisConfig && xAxisConfig.label) { xAxisProps.label = xAxisConfig.label; }
 
360
  gridEls.push(h(rc.XAxis, xAxisProps));
361
 
362
  // ── YAxis: use axes[].dimension from API JSON, linked by series[].axisId ──
363
  var yAxisId = chartSeries[0] ? (chartSeries[0].axisId || null) : null;
364
  var yAxisConfig = yAxisId ? buildAxisConfig(yAxisId) : buildAxisConfig(null);
365
- var yAxisProps = { key: 'y', tickFormatter: yAxisConfig.tickFormatter };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  if (yAxisConfig.domain) { yAxisProps.domain = yAxisConfig.domain; }
367
  if (yAxisConfig.ticks) { yAxisProps.ticks = yAxisConfig.ticks; }
368
  // Use axes[].label from API JSON for axis title (e.g., "用户数")
369
  if (yAxisConfig.label) { yAxisProps.label = yAxisConfig.label; }
 
370
  gridEls.push(h(rc.YAxis, yAxisProps));
371
  }
372
- gridEls.push(h(rc.Tooltip, { key: 'tooltip' }));
373
 
374
- // Legend: for pie/donut charts, use custom payload to show category names
375
- // instead of the series name ("占比")
376
  if (chartType === 'pie' || chartType === 'donut') {
377
  var pieActualNameKey = nameKey || 'name';
378
  var legendPayload = chartData.map(function(row, i) {
@@ -381,11 +484,11 @@ window._widgetRendered = false;
381
  id: i,
382
  value: fmt ? (fmt[pieActualNameKey] || row[pieActualNameKey]) : (row[pieActualNameKey] || 'Item'),
383
  type: 'rect',
384
- color: COLORS[i % COLORS.length]
385
  };
386
  });
387
  gridEls.push(h(rc.Legend, { key: 'legend', payload: legendPayload }));
388
- } else {
389
  gridEls.push(h(rc.Legend, { key: 'legend' }));
390
  }
391
 
@@ -395,15 +498,19 @@ window._widgetRendered = false;
395
 
396
  // Use ReactDOM.render for Recharts v2.12.7 compatibility
397
  // Render chart directly without ResponsiveContainer to avoid coordinate scaling issues
 
398
  var el = h('div', {},
399
- chartTitle && h('div', { className: 'chart-title' }, chartTitle),
400
- chartDesc && h('div', { className: 'chart-subtitle' }, chartDesc),
401
- chart
 
 
 
402
  );
403
  if (ReactDOM.render) {
404
- ReactDOM.render(el, document.getElementById('widget-container'));
405
  } else {
406
- ReactDOM.createRoot(document.getElementById('widget-container')).render(el);
407
  }
408
  window._widgetRendered = true;
409
  } catch (err) {
 
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>
 
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() {
 
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) {
 
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
 
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));
 
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
  });
 
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
 
 
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
  };
 
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
  });
 
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%';
 
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;
 
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 = {};
 
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) {
 
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
 
 
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) {
server.js CHANGED
@@ -955,7 +955,10 @@ class WidgetRenderer {
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}, xKey, yKey, series[], data[] }
 
 
 
959
 
960
  async renderChatGPTChart(dataJson, title) {
961
  const startTime = Date.now();
@@ -978,14 +981,13 @@ class WidgetRenderer {
978
  const formattedData = chartData.formattedData || [];
979
  const axes = chartData.axes || [];
980
  const meta = chartData.meta || {};
981
- const chartTitle = meta.title || title || 'Chart';
982
- const chartDesc = meta.description || '';
983
 
984
  console.log(`[WIDGET] renderChatGPTChart: type=${chartType}, series=${series.length}, rows=${data.length}, xKey=${xKey}, axes=${axes.length}`);
985
 
986
- const html = this.buildChatGPTChartHtml(chartType, series, data, xKey, nameKey, valueKey, formattedData, axes, chartTitle, chartDesc);
987
 
988
- return this._renderFullHtml(html, chartTitle, 8000, chartType);
 
989
  }
990
 
991
  /**
 
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();
 
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
 
993
  /**