XWX-AI commited on
Commit
515ca75
·
1 Parent(s): 265de41

feat(chart): Claude chart_display_v0 渲染器入库(备忘录125/126/127)——lib/claude-chart-html.js(125/126轮创建但漏未提交,与server.js的renderClaudeChart路由成对入库)+server.js claude_chart case(125)+CD视觉皮肤全套(8色调色板真机仲裁值/官方刻度算法cdYScale/cdTicks/横向判定/柱圆角/页内组装config防JSON.stringify丢函数(126根因))+127轮官方类目slot几何:xwx-cd-slot插件afterLayout按c20f35e63 D()/j()逐字数值化barThickness(pitch=轴长/类目数,slot=min(20n+2(n-1),pitch-inset),lane=(slot-2(n-1))/n),修复Q502类目间隔被categoryPercentage:1占满(用户实测图1);烟测9/9(柱宽20±0.5px/组间隙≥8px/line不受污染),容器端到端出图,真机PDF p6与网页同构。space/main未push(生产需人工;桌面pdf-render副本已同步md5 ae539ef5)

Browse files
Files changed (2) hide show
  1. lib/claude-chart-html.js +592 -0
  2. server.js +29 -0
lib/claude-chart-html.js ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * buildClaudeChartHtml — Claude chart_display_v0 spec → 完整渲染 HTML(Chart.js 4 + CD 视觉皮肤)
3
+ *
4
+ * 单一事实源:backend-service(本目录)与桌面 APP(…/pdf-render/)共用同一份实现;
5
+ * 插件侧整包下传 spec(src/content/api/claude-widgets.js 注册表),本模块按官方
6
+ * 同名路径读取,未知键忽略不删——官方 spec 语义 .loose()(备忘录 119 整包透传原则)。
7
+ *
8
+ * ── 契约取证(2026-10-25,官方前端 chunk 静态解析,证据 temp/test/claude/2026-10-25/round3/)──
9
+ * 官方渲染器 = Claude 自研 CD 图表库(tool_cell_chart chunk ccf210202 → ChartContainer
10
+ * cd138888b / Legend c50772270 / LineMark c8ae8e4af / BarMark c3cf96714 / Scatter c6fb33cf7),
11
+ * SVG 直绘,非 Chart.js/Recharts。本模块用 Chart.js 4.5.1(本地 lib/chart.umd.js,零 CDN)
12
+ * 对齐其视觉契约:
13
+ * · 调色板(c25d7186f token 表 chart.categorical,light):8 色
14
+ * #2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #008300 #6250d6 #e34948;
15
+ * 超 8 系列用 muted #c3c2b7(Legend K() 分配逻辑同构)
16
+ * · 网格:仅横向 rgba(11,11,11,0.1);scatter 双向;轴线 #c3c2b7
17
+ * · 线:borderWidth 2、直线段(interpolation 默认 linear)、末点 r=4 填充系列色 +
18
+ * surface 描边 3px(LineMark O()/pe 段:3+extra、strokeWidth 2*1.5)
19
+ * · bar:圆角 min(4, 柱长/4) 仅外侧两角(dataEnd 正值顶/负值底);系列间隙 2px
20
+ * · scatter:静态点 r=4 无描边;values→points 映射 {x: idx+1, y}
21
+ * · 图例:flex wrap,swatch line=10×2 横条 / bar=10×10 方 / scatter=8×8 圆,
22
+ * 文字 footnote 12px text-secondary #52514e
23
+ * · 标题区(tool_cell_chart M()):title 之外 description = "{yTitle} by {xTitle}"
24
+ * 或 "by {xTitle}"(有 x 无 y 时),全无则不显示
25
+ * · 数据变换(tool_cell_chart v()/y()):rows = {x:String(i), s0..sN};
26
+ * x 标签 = x_axis.data[i] 缺失时 String(i+1)(从 1 起);y_axis.min/max 进 domain
27
+ * (log 轴 ≤0 忽略;min>=max 整体忽略);style 缺省 "line"
28
+ * · 图例显示判定 b():series≥2 且任一有 name → 显示;单系列 name 非空且
29
+ * ≠ title 且 ≠ y_axis.title → 显示
30
+ * ── 刻度/柱宽算法移植(2026-10-26,备忘录 126,源 chunk c42085fb1/c50772270/
31
+ * c3cf96714/c20f35e63 逐字)──
32
+ * · y 刻度:官方 Be/Pe/Ie 纯函数复刻(cdYScale/cdTicks)——extent → 5% pad →
33
+ * nice domain([1,2,2.5,5]×10^k ≥ range/4,pin 侧不外扩,超 10% 回退)→
34
+ * includeZero "near"(lo ≤ hi×25% 归零)→ 候选步长筛选(minSpacing 44px,
35
+ * 图区高 200px)。真机对齐:折线 42..78 → 0/20/40/60/80;柱状 32..120 → 0/50/100。
36
+ * · 柱宽:官方 slot 上限 D(n)=20n+2(n-1)px → Chart.js maxBarThickness 20 +
37
+ * categoryPercentage/barPercentage 1.0(真机 Q8「柱子粗了很多」根因)。
38
+ * · 柱圆角:min(4, 柱长px/4)(官方 g() dSize/4)。
39
+ * · 横向条形图:单系列且 >1 个 x 标签含 ≥11 个非数字字符(官方 S())。
40
+ * 已知残差(有意):x 轴标签密集时的抽稀策略(官方 slide/drop vs Chart.js autoSkip)、
41
+ * log 刻度集(走 Chart.js logarithmic)、legend 处的 2px lane 间隙。
42
+ */
43
+
44
+ 'use strict';
45
+
46
+ // ⚠ 页内执行(桌面 WebView 注入)没有 require——fs/path 一律惰性获取,
47
+ // 顶层只允许纯 JS(chatgpt-chart-html.js 同纪律)。
48
+
49
+ // 本地 Chart.js(零 CDN 依赖)。后端 = lib/chart.umd.js(51 号留档 4.5.1);
50
+ // 桌面 APP 页内执行(Rust WebView vhost 注入,无 fs)走 CDN URL,由桌面
51
+ // vendor_map_json() 重写为本地 vendor/chart.umd-4.4.1.js(widget_renderer.rs
52
+ // 与 chatgpt_chart 同一机制)。本文件与桌面 pdf-render/ 逐字节同步(单一事实源)。
53
+ let _chartJsSource = null;
54
+ function chartJsInline() {
55
+ if (_chartJsSource === null) {
56
+ const fs = require('fs');
57
+ const path = require('path');
58
+ const candidates = [
59
+ path.join(__dirname, 'chart.umd.js'),
60
+ path.join(__dirname, 'vendor', 'chart.umd-4.4.1.js'),
61
+ path.join(__dirname, 'vendor', 'chart.umd.js'),
62
+ ];
63
+ for (const p of candidates) {
64
+ try {
65
+ _chartJsSource = fs.readFileSync(p, 'utf8');
66
+ break;
67
+ } catch { /* 尝试下一个 */ }
68
+ }
69
+ if (_chartJsSource === null) {
70
+ throw new Error('claude-chart-html: Chart.js UMD not found in ' + candidates.join(', '));
71
+ }
72
+ }
73
+ return _chartJsSource;
74
+ }
75
+
76
+ function isNodeEnv() {
77
+ return typeof process !== 'undefined' && process.versions && !!process.versions.node;
78
+ }
79
+
80
+ /** Chart.js 载入方式:Node 内联(零网络);浏览器/WebView 走 CDN URL(桌面 vendor_map 重写)。 */
81
+ function chartJsScriptTag(opts) {
82
+ if (opts && typeof opts.chartJsSource === 'string') {
83
+ return '<script>' + opts.chartJsSource + '<\/script>';
84
+ }
85
+ if (isNodeEnv() && require.resolve) {
86
+ try {
87
+ return '<script>' + chartJsInline() + '<\/script>';
88
+ } catch { /* 找不到本地 UMD → 回退 CDN */ }
89
+ }
90
+ return '<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js"><\/script>';
91
+ }
92
+
93
+ // ── CD token(light 模式;导出 PDF 恒 light,与 chatgpt_chart 同基准)──
94
+ // ⚠ 调色板以真机 getComputedStyle 为准(round3/palette-arbiter.json,2026-10-25):
95
+ // claude.ai 页面在运行时覆盖了 --cds-chart-categorical-*,与 c25d7186f chunk 里的
96
+ // CD 库默认值(#2a78d6/#eb6834/#1baf7a/#eda100/#e87ba4/#008300/#6250d6/#e34948)
97
+ // 不同——地面真值优先(备忘录 119 纪律)。axis 同理 #c2c2c2(token 表 #c3c2b7)。
98
+ const CD = {
99
+ CATEGORICAL: ['#257de0', '#f47230', '#00b894', '#f2a600', '#ee7fac', '#008a17', '#6a4ce2', '#ec4647'],
100
+ MUTED: '#c3c2b7',
101
+ GRID: 'rgba(11, 11, 11, 0.1)',
102
+ AXIS: '#c2c2c2',
103
+ TEXT_PRIMARY: '#1a1a18',
104
+ TEXT_SECONDARY: '#52514e',
105
+ SURFACE: '#ffffff',
106
+ FONT_FAMILY: "'Styrene B', 'StyreneB', -apple-system, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif",
107
+ PLOT_HEIGHT: 240,
108
+ };
109
+
110
+ /** 系列配色(Legend K() 同构:显式色值保留,其余按 categorical 顺序,超出 muted) */
111
+ function assignPaints(series) {
112
+ const used = new Set(series.map((s) => s && s.color).filter((c) => typeof c === 'string' && /^categorical-\d$/.test(c)));
113
+ const free = [];
114
+ for (let i = 0; i < CD.CATEGORICAL.length; i++) {
115
+ if (!used.has(`categorical-${i + 1}`)) free.push(CD.CATEGORICAL[i]);
116
+ }
117
+ let fi = 0;
118
+ return series.map((s) => {
119
+ const c = s && s.color;
120
+ if (typeof c === 'string' && c.startsWith('#')) return c; // 显式色值(整包透传的未来参数)
121
+ if (typeof c === 'string' && /^categorical-\d$/.test(c)) {
122
+ return CD.CATEGORICAL[parseInt(c.slice(12), 10) - 1] || CD.MUTED;
123
+ }
124
+ return free[fi++] || CD.MUTED;
125
+ });
126
+ }
127
+
128
+ /** 数字格式(CD ge(formatYTicks compact):逐刻度 |v|≥1000 → compact 3 位有效数字) */
129
+ function formatNumber(v, compact) {
130
+ if (typeof v !== 'number' || !Number.isFinite(v)) return String(v ?? '');
131
+ if (compact && Math.abs(v) >= 1000) {
132
+ return new Intl.NumberFormat('en-US', { notation: 'compact', maximumSignificantDigits: 3 }).format(v);
133
+ }
134
+ return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(v);
135
+ }
136
+
137
+ // ── CD 刻度算法移植(2026-10-26,备忘录 126)──
138
+ // 官方源:c42085fb1 `Ie`(刻度候选筛选)/`Pe`(nice domain)/`Be`(线性 y 尺度) +
139
+ // c50772270 常数。全为纯函数(不传 format 时无需 DOM 文本测量),可离线复刻。
140
+ // 手算已对齐两个真机案例:折线 42..78 → 0/20/40/60/80;柱状 120..32 → 0/50/100。
141
+ const TICK_STEPS = [1, 2, 2.5, 5];
142
+ const ALMOST_EQ = (a, b) => Math.abs(b - a) <= Math.max(Math.abs(a), Math.abs(b)) * 1e-12;
143
+ /** 官方 Me:k*step(step<1 时用除法回避浮点误差) */
144
+ function mulTick(k, step) {
145
+ if (k === 0) return 0;
146
+ return step < 1 ? k / Math.round(1 / step) : k * step;
147
+ }
148
+ /** 官方 Ne:[lo,hi] 内按 step 生成的刻度值序列 */
149
+ function genTicks(lo, hi, step) {
150
+ const first = Math.ceil(lo / step - 1e-9);
151
+ const count = Math.floor(hi / step + 1e-9) - first + 1;
152
+ return Array.from({ length: Math.max(0, count) }, (_, i) => mulTick(first + i, step));
153
+ }
154
+ /** 官方 Pe:domain 边界 nice 化(步进 = [1,2,2.5,5]×10^k ≥ range/4,目标约 4 档;
155
+ * pin 侧不外扩;外扩超过 range 10% 时回退到数据端) */
156
+ function niceDomain(lo, hi, padLo, padHi) {
157
+ const r = (hi - lo) / 4;
158
+ if (!(r > 0) || !Number.isFinite(r)) return [lo, hi];
159
+ const mag = 10 ** Math.floor(Math.log10(r));
160
+ const step = (TICK_STEPS.find((c) => c * mag >= r) ?? 10) * mag;
161
+ const d = [padLo ? mulTick(Math.floor(lo / step + 1e-9), step) : lo, padHi ? mulTick(Math.ceil(hi / step - 1e-9), step) : hi];
162
+ for (let n = 0; n < 2; n++) {
163
+ const pad = [lo - d[0], d[1] - hi];
164
+ if (Math.max(...pad) <= (d[1] - d[0]) * 0.1) break;
165
+ if (pad[0] >= pad[1]) d[0] = lo; else d[1] = hi;
166
+ }
167
+ return d;
168
+ }
169
+ /** 官方 Ie:候选步长筛选(minSpacing 44px vertical / 64px horizontal);
170
+ * format 未传 → Fe 恒真,无需文本测量。 */
171
+ function cdTicks(lo, hi, length, opts = {}) {
172
+ const minSpacing = opts.minSpacing ?? 44;
173
+ if (ALMOST_EQ(lo, hi) || !(length > 0) || !Number.isFinite(hi - lo)) {
174
+ return Number.isFinite(lo) ? [lo] : [];
175
+ }
176
+ const integer = opts.integer === true && Math.floor(hi) - Math.ceil(lo) >= 1;
177
+ const spacing = Math.min(Math.max(minSpacing, length / 6), Math.max(length / 3.5, 24));
178
+ const half = Math.max(spacing / 2, 24);
179
+ let full, part, single, lastResort;
180
+ const start = Math.floor(Math.log10((hi - lo) * half / length));
181
+ for (let p = start; p < start + 8; p++) {
182
+ for (const cand of TICK_STEPS) {
183
+ const step = cand * 10 ** p;
184
+ const pxPerTick = step / (hi - lo) * length;
185
+ if (pxPerTick < half || (integer && !Number.isInteger(step))) continue;
186
+ const ticks = genTicks(lo, hi, step);
187
+ if (ticks.length < (full?.length ?? 0) || (step > hi - lo && single !== undefined)) {
188
+ return full ?? part ?? single ?? lastResort ?? [];
189
+ }
190
+ if (ticks.length === 1) single ??= ticks;
191
+ else if (full !== undefined || pxPerTick >= spacing - 1e-6) full = ticks;
192
+ else part = ticks;
193
+ }
194
+ }
195
+ return full ?? part ?? single ?? lastResort ?? [];
196
+ }
197
+ /** 官方 Be 线性 y 尺度(includeZero 默认 "near":padded lo ≤ hi×25% 时归零;
198
+ * 显式 min/max 为 pin,min≥max 整体忽略;全 0 数据 → 刻度 [0]) */
199
+ function cdYScale(values, opts = {}) {
200
+ let lo = Infinity, hi = -Infinity, allInt = true, allZero = true;
201
+ for (const v of values) {
202
+ if (!Number.isFinite(v)) continue;
203
+ if (v < lo) lo = v;
204
+ if (v > hi) hi = v;
205
+ if (!Number.isInteger(v)) allInt = false;
206
+ if (v !== 0) allZero = false;
207
+ }
208
+ if (!Number.isFinite(lo)) return null;
209
+ const pinMin = (typeof opts.min === 'number' && Number.isFinite(opts.min)) ? opts.min : undefined;
210
+ const pinMax = (typeof opts.max === 'number' && Number.isFinite(opts.max)) ? opts.max : undefined;
211
+ if (pinMin !== undefined && pinMax !== undefined && pinMin >= pinMax) return null;
212
+ if (allZero && pinMin === undefined && pinMax === undefined) {
213
+ return { domain: [-1, 1], ticks: [0] };
214
+ }
215
+ let plo = lo, phi = hi;
216
+ if (ALMOST_EQ(plo, phi)) {
217
+ const e = Math.abs(plo) * 0.1 || 1;
218
+ phi += e;
219
+ if (plo !== 0) plo -= e;
220
+ } else {
221
+ const pad = (phi - plo) * 0.05;
222
+ plo = (plo >= 0 && plo - pad < 0) ? 0 : plo - pad;
223
+ phi = (phi <= 0 && phi + pad > 0) ? 0 : phi + pad;
224
+ }
225
+ let dLo = pinMin ?? plo, dHi = pinMax ?? phi;
226
+ if (dHi <= dLo) {
227
+ const t = Math.abs(dLo) * 0.1 || 1;
228
+ if (pinMax !== undefined && pinMin === undefined) dLo = dHi - t;
229
+ else dHi = dLo + t;
230
+ }
231
+ let domain = niceDomain(dLo, dHi, pinMin === undefined, pinMax === undefined);
232
+ // includeZero "near"(官方 je=0.25)
233
+ if (pinMin === undefined && plo > 0 && plo <= phi * 0.25) domain[0] = 0;
234
+ if (pinMax === undefined && phi < 0 && phi >= plo * 0.25 && plo < 0) domain[1] = 0;
235
+ const ticks = cdTicks(domain[0], domain[1], opts.plotHeight ?? 200, { integer: allInt });
236
+ return { domain, ticks };
237
+ }
238
+ /** 官方 S() barOrientation:单系列且 >1 个 x 标签含 ≥11 个非数字字符 → 横向 */
239
+ function barOrientation(seriesCount, labels) {
240
+ if (seriesCount !== 1) return 'vertical';
241
+ const longRe = /^\P{Nd}{11,}$/u;
242
+ const longCount = labels.filter((l) => longRe.test(String(l))).length;
243
+ return longCount > 1 ? 'horizontal' : 'vertical';
244
+ }
245
+
246
+
247
+ /** 官方 M():description = "{yTitle} by {xTitle}" / "by {xTitle}" / 无。
248
+ * i18n(官方 Eke8/Rd12Y key,真机中文实测"按月份划分的访问量(千次)"):
249
+ * 标题/轴标题含 CJK 即用中文语序(自包含检测,不依赖调用方传 locale),
250
+ * 其余英文语序(全语种 i18n 记为残差)。 */
251
+ function chartDescription(spec) {
252
+ const x = spec && spec.x_axis && spec.x_axis.title;
253
+ const y = spec && spec.y_axis && spec.y_axis.title;
254
+ if (!x) return '';
255
+ const zh = /[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/.test(String(spec.title || '') + String(x) + String(y || ''));
256
+ if (y) return zh ? `按${x}划分的${y}` : `${y} by ${x}`;
257
+ return zh ? `按${x}划分` : `by ${x}`;
258
+ }
259
+
260
+ /** 图例显示判定(tool_cell_chart b() 同构) */
261
+ function hasLegend(spec) {
262
+ const series = spec.series || [];
263
+ if (series.length >= 2) return series.some((s) => !!s.name);
264
+ const name = (series[0] && series[0].name || '').trim().toLowerCase();
265
+ if (!name) return false;
266
+ const title = (spec.title || '').trim().toLowerCase();
267
+ const yTitle = (spec.y_axis && spec.y_axis.title || '').trim().toLowerCase();
268
+ return name !== title && name !== yTitle;
269
+ }
270
+
271
+ /** x 标签(官方 formatX:x_axis.data[i] 缺失时 String(i+1)) */
272
+ function xLabels(spec, n) {
273
+ const data = Array.isArray(spec.x_axis && spec.x_axis.data) ? spec.x_axis.data : [];
274
+ const labels = [];
275
+ for (let i = 0; i < n; i++) labels.push(data[i] !== undefined ? String(data[i]) : String(i + 1));
276
+ return labels;
277
+ }
278
+
279
+ /**
280
+ * 构建 claude_chart 渲染 HTML。
281
+ * @param {object} spec chart_display_v0 input 整包(style/title/series/x_axis/y_axis + 未知键)
282
+ * @param {object} [opts] { chartJsSource?: string } 桌面页内可显式传入 Chart.js 源码
283
+ * @returns {string|null} 完整 HTML;spec 不可渲染(无有效数据)返回 null
284
+ */
285
+ function buildClaudeChartHtml(spec, opts) {
286
+ if (!spec || typeof spec !== 'object') return null;
287
+ const style = ['line', 'bar', 'scatter'].includes(spec.style) ? spec.style : 'line';
288
+ const series = Array.isArray(spec.series) ? spec.series : [];
289
+ if (series.length === 0) return null;
290
+ // 官方 validator(c59c32499 Rr):values 无有效值且 points 空 → 系列丢弃;全空 → 图不可渲染
291
+ const liveSeries = series.filter((s) => s && typeof s === 'object' &&
292
+ (Array.isArray(s.values) && s.values.some((v) => v !== null && v !== undefined && Number.isFinite(Number(v))) ||
293
+ Array.isArray(s.points) && s.points.length > 0));
294
+ if (liveSeries.length === 0) return null;
295
+
296
+ const paints = assignPaints(liveSeries);
297
+ const nRows = Math.max(...liveSeries.map((s) => (s.values || s.points || []).length));
298
+ const labels = xLabels(spec, nRows);
299
+ const legend = hasLegend(spec);
300
+ const desc = chartDescription(spec);
301
+ const flatValues = liveSeries.flatMap((s) => (s.values || (s.points || []).map((p) => p.y)) ?? [])
302
+ .map((v) => (v === null || v === undefined) ? NaN : Number(v)).filter(Number.isFinite);
303
+
304
+ // 值轴 pin(官方 D():log 轴 ≤0 忽略;min>=max 整体忽略)
305
+ const ya = spec.y_axis || {};
306
+ const clampLog = (v) => (ya.scale === 'log' && typeof v === 'number' && v <= 0) ? undefined : v;
307
+ const mn = clampLog(typeof ya.min === 'number' ? ya.min : (ya.min !== undefined ? Number(ya.min) : undefined));
308
+ const mx = clampLog(typeof ya.max === 'number' ? ya.max : (ya.max !== undefined ? Number(ya.max) : undefined));
309
+
310
+ // 值域/刻度:官方 CD 算法离线复刻(cdYScale/cdTicks),替代 Chart.js nice
311
+ let valueScale = null;
312
+ if (ya.scale !== 'log') {
313
+ valueScale = cdYScale(flatValues, { min: mn, max: mx, plotHeight: 200 });
314
+ }
315
+
316
+ // 官方 S():单系列长标签 → 横向条形图(值轴水平、类目轴垂直)
317
+ const horizontal = style === 'bar' && barOrientation(liveSeries.length, labels) === 'horizontal';
318
+ const isScatter = style === 'scatter';
319
+ // Chart.js 键位:值轴(刻度算法所在)/类目轴
320
+ const valueKey = horizontal ? 'x' : 'y';
321
+ const catKey = horizontal ? 'y' : 'x';
322
+ const pxPerUnit = valueScale
323
+ ? (horizontal ? 680 : 200) / Math.max(1e-9, valueScale.domain[1] - valueScale.domain[0])
324
+ : 0;
325
+
326
+ const datasets = liveSeries.map((s, i) => {
327
+ const paint = paints[i];
328
+ if (isScatter) {
329
+ // 官方 y():points 直接用;values → {x: idx+1, y}(C() 同构)
330
+ const pts = (s.points && s.points.length)
331
+ ? s.points.map((p) => ({ x: Number(p.x), y: Number(p.y) }))
332
+ : (s.values || []).flatMap((v, idx) => (v === null || !Number.isFinite(Number(v))) ? [] : [{ x: idx + 1, y: Number(v) }]);
333
+ return {
334
+ label: s.name || `Series ${i + 1}`,
335
+ data: pts,
336
+ backgroundColor: paint,
337
+ pointRadius: 4,
338
+ pointHoverRadius: 4,
339
+ borderWidth: 0,
340
+ };
341
+ }
342
+ const values = (s.values || (s.points || []).map((p) => p.y)).map((v) => (v === null || v === undefined) ? null : Number(v));
343
+ return {
344
+ label: s.name || `Series ${i + 1}`,
345
+ data: values,
346
+ borderColor: paint,
347
+ backgroundColor: paint,
348
+ borderWidth: 2,
349
+ borderJoinStyle: 'round',
350
+ borderCapStyle: 'round',
351
+ tension: 0,
352
+ pointRadius: (ctx) => (ctx.dataIndex === values.length - 1 ? 4 : 0),
353
+ pointHoverRadius: 0,
354
+ pointBackgroundColor: paint,
355
+ pointBorderColor: CD.SURFACE,
356
+ pointBorderWidth: 3,
357
+ fill: false,
358
+ // 官方 g():圆角 min(4, 柱长px/4),仅值端外侧两角
359
+ borderRadius: style === 'bar'
360
+ ? (ctx) => {
361
+ const v = ctx.dataset?.data?.[ctx.dataIndex];
362
+ if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
363
+ return Math.min(4, Math.abs(v) * pxPerUnit / 4);
364
+ }
365
+ : 0,
366
+ borderSkipped: style === 'bar' ? 'start' : false,
367
+ // 官方 BarMark 几何(备忘录 127):类目 slot 上限 D(lanes)=20n+2(n-1)px、
368
+ // 类目间 inset=min(12, pitch×0.25)、lane 内柱间 2px——由页内 afterLayout
369
+ // 插件按真实绘图区宽度数值化 barThickness(barPercentage/categoryPercentage
370
+ // 组合表达不出「slot 上限 + 组间 inset」,Q502 实测组间隙被占满)。
371
+ ...(style === 'bar' ? { barPercentage: 1, categoryPercentage: 1 } : {}),
372
+ };
373
+ });
374
+
375
+ const pointStyle = isScatter ? 'circle' : (style === 'bar' ? 'rect' : 'line');
376
+ // 官方 Legend swatch:line=10×2 横条 / bar=10×10 方 / scatter=8×8 圆
377
+ const legendSwatch = isScatter ? { boxWidth: 8, boxHeight: 8 } : (style === 'bar' ? { boxWidth: 10, boxHeight: 10 } : { boxWidth: 10, boxHeight: 2 });
378
+
379
+ const valueTicks = valueScale ? valueScale.ticks : null;
380
+
381
+ // ⚠ 模板契约:config 必须在**页内**组装(2026-10-26 备忘录 126 根因)——
382
+ // 旧实现 JSON.stringify(整份 config) 会把全部函数型选项(ticks.callback /
383
+ // pointRadius / borderRadius)静默丢弃,图表退化成 Chart.js 全默认行为
384
+ // (每点圆点、错误刻度密度、平顶柱)。JSON 只承载纯数据 payload。
385
+ const payload = {
386
+ type: isScatter ? 'scatter' : (style === 'bar' ? 'bar' : 'line'),
387
+ labels,
388
+ isScatter,
389
+ horizontal,
390
+ catKey,
391
+ valueKey,
392
+ legendSwatch,
393
+ pointStyle,
394
+ legend,
395
+ domain: valueScale ? valueScale.domain : null,
396
+ valueTicks,
397
+ pinnedMin: !valueScale ? mn : null,
398
+ pinnedMax: !valueScale ? mx : null,
399
+ isLog: ya.scale === 'log',
400
+ pxPerUnit,
401
+ scatterXMin: isScatter && spec.x_axis && spec.x_axis.min !== undefined ? Number(spec.x_axis.min) : null,
402
+ scatterXMax: isScatter && spec.x_axis && spec.x_axis.max !== undefined ? Number(spec.x_axis.max) : null,
403
+ datasets: datasets.map((d) => ({
404
+ ...d,
405
+ data: d.data,
406
+ // 函数型字段只传标记,页内按 style 重建
407
+ _lastIndex: (style !== 'bar') ? (Array.isArray(d.data) ? d.data.length - 1 : -1) : -1,
408
+ })),
409
+ };
410
+
411
+ const titleHtml = spec.title ? `<div class="cw-title">${escapeHtml(String(spec.title))}</div>` : '';
412
+ const descHtml = desc ? `<div class="cw-desc">${escapeHtml(desc)}</div>` : '';
413
+ const axisNote = [];
414
+ if (ya.scale === 'log') axisNote.push('log scale');
415
+
416
+ const json = JSON.stringify(payload).replace(/</g, '\\u003c');
417
+ return `<!doctype html>
418
+ <html><head><meta charset="utf-8">
419
+ <style>
420
+ html, body { margin: 0; padding: 0; background: ${CD.SURFACE}; }
421
+ #widget-container { width: 720px; box-sizing: border-box; padding: 0; background: ${CD.SURFACE};
422
+ font-family: ${CD.FONT_FAMILY}; color: ${CD.TEXT_PRIMARY}; }
423
+ .cw-head { padding: 2px 2px 6px; }
424
+ .cw-title { font-size: 15px; font-weight: 500; line-height: 22px; color: ${CD.TEXT_PRIMARY}; }
425
+ .cw-desc { font-size: 12px; line-height: 17px; color: ${CD.TEXT_SECONDARY}; margin-top: 2px; }
426
+ .cw-note { font-size: 11px; color: ${CD.TEXT_SECONDARY}; padding: 0 2px; }
427
+ .cw-chart { width: 720px; height: ${CD.PLOT_HEIGHT + 60}px; }
428
+ </style></head>
429
+ <body>
430
+ <div id="widget-container">
431
+ <div class="cw-head">${titleHtml}${descHtml}</div>
432
+ <div class="cw-chart"><canvas id="cd-chart"></canvas></div>
433
+ ${axisNote.length ? `<div class="cw-note">${escapeHtml(axisNote.join(' · '))}</div>` : ''}
434
+ </div>
435
+ ${chartJsScriptTag(opts)}
436
+ <script>
437
+ (function () {
438
+ try {
439
+ var P = ${json};
440
+ var CD = ${JSON.stringify({ TEXT_SECONDARY: CD.TEXT_SECONDARY, GRID: CD.GRID, AXIS: CD.AXIS, SURFACE: CD.SURFACE, FONT_FAMILY: CD.FONT_FAMILY })};
441
+
442
+ // 官方 ge(formatYTicks compact):逐刻度 |v|≥1000 → compact 3 位有效数字
443
+ function fmtNum(v) {
444
+ if (typeof v !== 'number' || !Number.isFinite(v)) return String(v == null ? '' : v);
445
+ if (Math.abs(v) >= 1000) {
446
+ return new Intl.NumberFormat('en-US', { notation: 'compact', maximumSignificantDigits: 3 }).format(v);
447
+ }
448
+ return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(v);
449
+ }
450
+
451
+ // 官方 CD 刻度集整体替换 Chart.js 自动 nice(v4 的 afterBuildTicks 走插件通知)
452
+ var cdTicksPlugin = {
453
+ id: 'xwx-cd-ticks',
454
+ afterBuildTicks: function (chart, args, opts) {
455
+ if (!opts || !opts.values || !opts.values.length) return;
456
+ if (args.scale && args.scale.id === opts.axisId) {
457
+ args.scale.ticks = opts.values.map(function (v) { return { value: v }; });
458
+ }
459
+ },
460
+ };
461
+
462
+ // 官方类目 slot 几何(备忘录 127,源 c20f35e63 D()/j()/c3cf96714):
463
+ // pitch = 绘图区长/类目数(point-kind)
464
+ // inset = min(12, pitch×0.25) —— 类目之间的间隔(图1 根因)
465
+ // slot = min(D(lanes), pitch - inset),D(n) = 20n + 2(n-1)
466
+ // lane = (slot - 2(lanes-1)) / lanes —— 单柱宽(上限 20px)
467
+ // afterLayout 时 scale 已量好真实宽度、dataset 元素还未计算几何 →
468
+ // 数值化 barThickness(Chart.js v4 以 stack 居中排布,组内 2px lane 间隙
469
+ // 为已知残差,组间 inset 契约精确成立)。
470
+ var cdSlotPlugin = {
471
+ id: 'xwx-cd-slot',
472
+ afterLayout: function (chart) {
473
+ if (P.type !== 'bar' || P.isScatter) return;
474
+ var cat = chart.scales[P.catKey];
475
+ var data = chart.data;
476
+ var n = data.labels ? data.labels.length : (data.datasets[0] ? data.datasets[0].data.length : 0);
477
+ var lanes = (data.datasets && data.datasets.length) || 1;
478
+ if (!cat || !n || cat.width <= 0) return;
479
+ var pitch = cat.width / n;
480
+ var inset = Math.min(12, pitch * 0.25);
481
+ var slot = Math.min(20 * lanes + 2 * (lanes - 1), Math.max(1, pitch - inset));
482
+ var lane = Math.max(1, (slot - 2 * (lanes - 1)) / lanes);
483
+ data.datasets.forEach(function (ds) { ds.barThickness = lane; });
484
+ },
485
+ };
486
+
487
+ var datasets = P.datasets.map(function (d) {
488
+ if (P.type === 'scatter') return d;
489
+ return Object.assign({}, d, {
490
+ // 官方 LineMark:仅末点 r=4 填充系列色 + surface 描边 3px
491
+ pointRadius: function (ctx) { return ctx.dataIndex === d._lastIndex ? 4 : 0; },
492
+ // 官方 g():圆角 min(4, 柱长px/4),仅值端外侧两角
493
+ borderRadius: P.type === 'bar'
494
+ ? function (ctx) {
495
+ var v = ctx.dataset && ctx.dataset.data ? ctx.dataset.data[ctx.dataIndex] : null;
496
+ if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
497
+ return Math.min(4, Math.abs(v) * P.pxPerUnit / 4);
498
+ }
499
+ : 0,
500
+ });
501
+ });
502
+
503
+ var config = {
504
+ type: P.type,
505
+ data: P.isScatter ? { datasets: datasets } : { labels: P.labels, datasets: datasets },
506
+ plugins: [cdTicksPlugin, cdSlotPlugin],
507
+ options: {
508
+ animation: false,
509
+ responsive: false,
510
+ devicePixelRatio: 2,
511
+ ...(P.horizontal ? { indexAxis: 'y' } : {}),
512
+ layout: { padding: { top: 4, right: 8, bottom: 2, left: 2 } },
513
+ scales: (function () {
514
+ var cat = {
515
+ grid: { display: P.isScatter, color: CD.GRID, drawTicks: false },
516
+ border: { color: CD.AXIS, width: 1 },
517
+ ticks: {
518
+ color: CD.TEXT_SECONDARY, font: { size: 11, family: CD.FONT_FAMILY },
519
+ maxRotation: 45, autoSkip: true, maxTicksLimit: 12, padding: 6,
520
+ },
521
+ };
522
+ if (P.isScatter && P.catKey === 'x') {
523
+ cat.type = 'linear';
524
+ if (P.scatterXMin != null) cat.min = P.scatterXMin;
525
+ if (P.scatterXMax != null) cat.max = P.scatterXMax;
526
+ }
527
+ var val = {
528
+ grid: { color: CD.GRID, drawTicks: false },
529
+ border: { color: CD.AXIS, width: 1 },
530
+ ticks: {
531
+ color: CD.TEXT_SECONDARY, font: { size: 11, family: CD.FONT_FAMILY },
532
+ callback: function (v) { return fmtNum(v); }, padding: 6,
533
+ },
534
+ };
535
+ if (P.valueTicks) {
536
+ val.min = P.domain[0];
537
+ val.max = P.domain[1];
538
+ } else {
539
+ val.ticks.maxTicksLimit = 5;
540
+ if (P.pinnedMin != null) val.min = P.pinnedMin;
541
+ if (P.pinnedMax != null) val.max = P.pinnedMax;
542
+ }
543
+ if (P.isLog) val.type = 'logarithmic';
544
+ var scales = {};
545
+ scales[P.catKey] = cat;
546
+ scales[P.valueKey] = val;
547
+ return scales;
548
+ })(),
549
+ plugins: {
550
+ legend: {
551
+ display: P.legend,
552
+ position: 'bottom',
553
+ align: 'start',
554
+ labels: {
555
+ usePointStyle: true,
556
+ pointStyle: P.pointStyle,
557
+ color: CD.TEXT_SECONDARY,
558
+ font: { size: 12, family: CD.FONT_FAMILY },
559
+ boxWidth: P.legendSwatch.boxWidth,
560
+ boxHeight: P.legendSwatch.boxHeight,
561
+ padding: 16,
562
+ },
563
+ },
564
+ tooltip: { enabled: false },
565
+ 'xwx-cd-ticks': { axisId: P.valueKey, values: P.valueTicks || [] },
566
+ },
567
+ },
568
+ };
569
+ delete config.options.scales[P.valueKey].ticks.__cdAxisId;
570
+ delete config.options.scales[P.valueKey].ticks.__cdValues;
571
+
572
+ var canvas = document.getElementById('cd-chart');
573
+ canvas.width = 716; canvas.height = ${CD.PLOT_HEIGHT};
574
+ canvas.style.width = '716px'; canvas.style.height = '${CD.PLOT_HEIGHT}px';
575
+ config.options.maintainAspectRatio = false;
576
+ window._widgetReady = true;
577
+ new Chart(canvas.getContext('2d'), config);
578
+ } catch (e) {
579
+ window._widgetError = String(e && e.message || e);
580
+ document.getElementById('widget-container').innerHTML =
581
+ '<div style="padding:20px;color:#c00">Chart render error: ' + window._widgetError + '</div>';
582
+ }
583
+ })();
584
+ </script>
585
+ </body></html>`;
586
+ }
587
+
588
+ function escapeHtml(s) {
589
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
590
+ }
591
+
592
+ module.exports = { buildClaudeChartHtml, CD_TOKENS: CD, cdYScale, cdTicks, barOrientation, niceDomain, genTicks };
server.js CHANGED
@@ -35,6 +35,8 @@ const { BrowserPool } = require('./browser-pool');
35
  const { buildChatGPTChartHtml } = require('./lib/chatgpt-chart-html');
36
  // GPT-6 DIL 图标占位符 → 内联 SVG(客户端不带图标集,见 lib/dil-icons.js 顶部说明)
37
  const { resolveDilIcons, dilIconStats } = require('./lib/dil-icons');
 
 
38
 
39
  let ChartJSNodeCanvas = null;
40
  try {
@@ -985,6 +987,31 @@ class WidgetRenderer {
985
  return this._renderFullHtml(html, (meta && meta.title) || title || 'chatgpt_chart', 8000, chartType);
986
  }
987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  /**
989
  * Render a complete HTML document via Puppeteer (for chatgpt_chart).
990
  * The HTML already contains full <html>/<head>/<body> with script tags.
@@ -1321,6 +1348,8 @@ class WidgetRenderer {
1321
  return await this.renderMermaid(html, title);
1322
  case 'chatgpt_chart':
1323
  return await this.renderChatGPTChart(html, title);
 
 
1324
  case 'interactive':
1325
  return await this.renderWidgetPuppeteer(html, 'interactive', title, 3000);
1326
  default:
 
35
  const { buildChatGPTChartHtml } = require('./lib/chatgpt-chart-html');
36
  // GPT-6 DIL 图标占位符 → 内联 SVG(客户端不带图标集,见 lib/dil-icons.js 顶部说明)
37
  const { resolveDilIcons, dilIconStats } = require('./lib/dil-icons');
38
+ // Claude widgets chart(chart_display_v0)→ Chart.js 4 渲染 HTML(CD 视觉皮肤,备忘录 125)
39
+ const { buildClaudeChartHtml } = require('./lib/claude-chart-html');
40
 
41
  let ChartJSNodeCanvas = null;
42
  try {
 
987
  return this._renderFullHtml(html, (meta && meta.title) || title || 'chatgpt_chart', 8000, chartType);
988
  }
989
 
990
+
991
+ /**
992
+ * Claude widgets chart(chart_display_v0,备忘录 125):Chart.js 4 + CD 视觉皮肤。
993
+ * spec 整包下传(buildClaudeChartHtml 内部按官方同名路径读取);非官方支持的
994
+ * style / 无有效数据返回 null → 插件上层回退 Markdown 表格(与 chatgpt_chart 同协议)。
995
+ */
996
+ async renderClaudeChart(dataJson, title) {
997
+ console.log(`[WIDGET] renderClaudeChart START: title=${title}, dataLen=${dataJson.length}`);
998
+ let spec;
999
+ try {
1000
+ spec = typeof dataJson === 'string' ? JSON.parse(dataJson) : dataJson;
1001
+ } catch (e) {
1002
+ console.log(`[WIDGET] renderClaudeChart FAIL: JSON parse error: ${e.message}`);
1003
+ return null;
1004
+ }
1005
+ const style = (spec && spec.style) || 'line';
1006
+ console.log(`[WIDGET] renderClaudeChart: style=${style}, series=${(spec.series || []).length}`);
1007
+ const html = buildClaudeChartHtml(spec);
1008
+ if (!html) {
1009
+ console.log(`[WIDGET] renderClaudeChart SKIP: style=${style} 不可渲染(未知 style 或无有效数据)`);
1010
+ return null;
1011
+ }
1012
+ return this._renderFullHtml(html, (spec && spec.title) || title || 'claude_chart', 8000, 'claude_' + style);
1013
+ }
1014
+
1015
  /**
1016
  * Render a complete HTML document via Puppeteer (for chatgpt_chart).
1017
  * The HTML already contains full <html>/<head>/<body> with script tags.
 
1348
  return await this.renderMermaid(html, title);
1349
  case 'chatgpt_chart':
1350
  return await this.renderChatGPTChart(html, title);
1351
+ case 'claude_chart':
1352
+ return await this.renderClaudeChart(html, title);
1353
  case 'interactive':
1354
  return await this.renderWidgetPuppeteer(html, 'interactive', title, 3000);
1355
  default: