File size: 29,189 Bytes
515ca75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e02419
 
 
 
 
 
 
515ca75
 
 
 
2e02419
 
515ca75
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/**
 * buildClaudeChartHtml — Claude chart_display_v0 spec → 完整渲染 HTML(Chart.js 4 + CD 视觉皮肤)
 *
 * 单一事实源:backend-service(本目录)与桌面 APP(…/pdf-render/)共用同一份实现;
 * 插件侧整包下传 spec(src/content/api/claude-widgets.js 注册表),本模块按官方
 * 同名路径读取,未知键忽略不删——官方 spec 语义 .loose()(备忘录 119 整包透传原则)。
 *
 * ── 契约取证(2026-10-25,官方前端 chunk 静态解析,证据 temp/test/claude/2026-10-25/round3/)──
 * 官方渲染器 = Claude 自研 CD 图表库(tool_cell_chart chunk ccf210202 → ChartContainer
 * cd138888b / Legend c50772270 / LineMark c8ae8e4af / BarMark c3cf96714 / Scatter c6fb33cf7),
 * SVG 直绘,非 Chart.js/Recharts。本模块用 Chart.js 4.5.1(本地 lib/chart.umd.js,零 CDN)
 * 对齐其视觉契约:
 *   · 调色板(c25d7186f token 表 chart.categorical,light):8 色
 *     #2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #008300 #6250d6 #e34948;
 *     超 8 系列用 muted #c3c2b7(Legend K() 分配逻辑同构)
 *   · 网格:仅横向 rgba(11,11,11,0.1);scatter 双向;轴线 #c3c2b7
 *   · 线:borderWidth 2、直线段(interpolation 默认 linear)、末点 r=4 填充系列色 +
 *     surface 描边 3px(LineMark O()/pe 段:3+extra、strokeWidth 2*1.5)
 *   · bar:圆角 min(4, 柱长/4) 仅外侧两角(dataEnd 正值顶/负值底);系列间隙 2px
 *   · scatter:静态点 r=4 无描边;values→points 映射 {x: idx+1, y}
 *   · 图例:flex wrap,swatch line=10×2 横条 / bar=10×10 方 / scatter=8×8 圆,
 *     文字 footnote 12px text-secondary #52514e
 *   · 标题区(tool_cell_chart M()):title 之外 description = "{yTitle} by {xTitle}"
 *     或 "by {xTitle}"(有 x 无 y 时),全无则不显示
 *   · 数据变换(tool_cell_chart v()/y()):rows = {x:String(i), s0..sN};
 *     x 标签 = x_axis.data[i] 缺失时 String(i+1)(从 1 起);y_axis.min/max 进 domain
 *     (log 轴 ≤0 忽略;min>=max 整体忽略);style 缺省 "line"
 *   · 图例显示判定 b():series≥2 且任一有 name → 显示;单系列 name 非空且
 *     ≠ title 且 ≠ y_axis.title → 显示
 * ── 刻度/柱宽算法移植(2026-10-26,备忘录 126,源 chunk c42085fb1/c50772270/
 *    c3cf96714/c20f35e63 逐字)──
 *   · y 刻度:官方 Be/Pe/Ie 纯函数复刻(cdYScale/cdTicks)——extent → 5% pad →
 *     nice domain([1,2,2.5,5]×10^k ≥ range/4,pin 侧不外扩,超 10% 回退)→
 *     includeZero "near"(lo ≤ hi×25% 归零)→ 候选步长筛选(minSpacing 44px,
 *     图区高 200px)。真机对齐:折线 42..78 → 0/20/40/60/80;柱状 32..120 → 0/50/100。
 *   · 柱宽:官方 slot 上限 D(n)=20n+2(n-1)px → Chart.js maxBarThickness 20 +
 *     categoryPercentage/barPercentage 1.0(真机 Q8「柱子粗了很多」根因)。
 *   · 柱圆角:min(4, 柱长px/4)(官方 g() dSize/4)。
 *   · 横向条形图:单系列且 >1 个 x 标签含 ≥11 个非数字字符(官方 S())。
 * 已知残差(有意):x 轴标签密集时的抽稀策略(官方 slide/drop vs Chart.js autoSkip)、
 * log 刻度集(走 Chart.js logarithmic)、legend 处的 2px lane 间隙。
 */

'use strict';

// ⚠ 页内执行(桌面 WebView 注入)没有 require——fs/path 一律惰性获取,
// 顶层只允许纯 JS(chatgpt-chart-html.js 同纪律)。

// 本地 Chart.js(零 CDN 依赖)。后端 = lib/chart.umd.js(51 号留档 4.5.1);
// 桌面 APP 页内执行(Rust WebView vhost 注入,无 fs)走 CDN URL,由桌面
// vendor_map_json() 重写为本地 vendor/chart.umd-4.4.1.js(widget_renderer.rs
// 与 chatgpt_chart 同一机制)。本文件与桌面 pdf-render/ 逐字节同步(单一事实源)。
let _chartJsSource = null;
function chartJsInline() {
  if (_chartJsSource === null) {
    const fs = require('fs');
    const path = require('path');
    const candidates = [
      path.join(__dirname, 'chart.umd.js'),
      path.join(__dirname, 'vendor', 'chart.umd-4.4.1.js'),
      path.join(__dirname, 'vendor', 'chart.umd.js'),
    ];
    for (const p of candidates) {
      try {
        _chartJsSource = fs.readFileSync(p, 'utf8');
        break;
      } catch { /* 尝试下一个 */ }
    }
    if (_chartJsSource === null) {
      throw new Error('claude-chart-html: Chart.js UMD not found in ' + candidates.join(', '));
    }
  }
  return _chartJsSource;
}

function isNodeEnv() {
  return typeof process !== 'undefined' && process.versions && !!process.versions.node;
}

/** Chart.js 载入方式:Node 内联(零网络);浏览器/WebView 走 CDN URL(桌面 vendor_map 重写)。 */
function chartJsScriptTag(opts) {
  if (opts && typeof opts.chartJsSource === 'string') {
    return '<script>' + opts.chartJsSource + '<\/script>';
  }
  if (isNodeEnv() && require.resolve) {
    try {
      return '<script>' + chartJsInline() + '<\/script>';
    } catch { /* 找不到本地 UMD → 回退 CDN */ }
  }
  return '<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js"><\/script>';
}

// ── CD token(light 模式;导出 PDF 恒 light,与 chatgpt_chart 同基准)──
// ⚠ 调色板以真机 getComputedStyle 为准(round3/palette-arbiter.json,2026-10-25):
// claude.ai 页面在运行时覆盖了 --cds-chart-categorical-*,与 c25d7186f chunk 里的
// CD 库默认值(#2a78d6/#eb6834/#1baf7a/#eda100/#e87ba4/#008300/#6250d6/#e34948)
// 不同——地面真值优先(备忘录 119 纪律)。axis 同理 #c2c2c2(token 表 #c3c2b7)。
const CD = {
  CATEGORICAL: ['#257de0', '#f47230', '#00b894', '#f2a600', '#ee7fac', '#008a17', '#6a4ce2', '#ec4647'],
  MUTED: '#c3c2b7',
  GRID: 'rgba(11, 11, 11, 0.1)',
  AXIS: '#c2c2c2',
  TEXT_PRIMARY: '#1a1a18',
  TEXT_SECONDARY: '#52514e',
  SURFACE: '#ffffff',
  FONT_FAMILY: "'Styrene B', 'StyreneB', -apple-system, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif",
  PLOT_HEIGHT: 240,
};

/** 系列配色(Legend K() 同构:显式色值保留,其余按 categorical 顺序,超出 muted) */
function assignPaints(series) {
  const used = new Set(series.map((s) => s && s.color).filter((c) => typeof c === 'string' && /^categorical-\d$/.test(c)));
  const free = [];
  for (let i = 0; i < CD.CATEGORICAL.length; i++) {
    if (!used.has(`categorical-${i + 1}`)) free.push(CD.CATEGORICAL[i]);
  }
  let fi = 0;
  return series.map((s) => {
    const c = s && s.color;
    if (typeof c === 'string' && c.startsWith('#')) return c; // 显式色值(整包透传的未来参数)
    if (typeof c === 'string' && /^categorical-\d$/.test(c)) {
      return CD.CATEGORICAL[parseInt(c.slice(12), 10) - 1] || CD.MUTED;
    }
    return free[fi++] || CD.MUTED;
  });
}

/** 数字格式(CD ge(formatYTicks compact):逐刻度 |v|≥1000 → compact 3 位有效数字) */
function formatNumber(v, compact) {
  if (typeof v !== 'number' || !Number.isFinite(v)) return String(v ?? '');
  if (compact && Math.abs(v) >= 1000) {
    return new Intl.NumberFormat('en-US', { notation: 'compact', maximumSignificantDigits: 3 }).format(v);
  }
  return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(v);
}

// ── CD 刻度算法移植(2026-10-26,备忘录 126)──
// 官方源:c42085fb1 `Ie`(刻度候选筛选)/`Pe`(nice domain)/`Be`(线性 y 尺度) +
// c50772270 常数。全为纯函数(不传 format 时无需 DOM 文本测量),可离线复刻。
// 手算已对齐两个真机案例:折线 42..78 → 0/20/40/60/80;柱状 120..32 → 0/50/100。
const TICK_STEPS = [1, 2, 2.5, 5];
const ALMOST_EQ = (a, b) => Math.abs(b - a) <= Math.max(Math.abs(a), Math.abs(b)) * 1e-12;
/** 官方 Me:k*step(step<1 时用除法回避浮点误差) */
function mulTick(k, step) {
  if (k === 0) return 0;
  return step < 1 ? k / Math.round(1 / step) : k * step;
}
/** 官方 Ne:[lo,hi] 内按 step 生成的刻度值序列 */
function genTicks(lo, hi, step) {
  const first = Math.ceil(lo / step - 1e-9);
  const count = Math.floor(hi / step + 1e-9) - first + 1;
  return Array.from({ length: Math.max(0, count) }, (_, i) => mulTick(first + i, step));
}
/** 官方 Pe:domain 边界 nice 化(步进 = [1,2,2.5,5]×10^k ≥ range/4,目标约 4 档;
 * pin 侧不外扩;外扩超过 range 10% 时回退到数据端) */
function niceDomain(lo, hi, padLo, padHi) {
  const r = (hi - lo) / 4;
  if (!(r > 0) || !Number.isFinite(r)) return [lo, hi];
  const mag = 10 ** Math.floor(Math.log10(r));
  const step = (TICK_STEPS.find((c) => c * mag >= r) ?? 10) * mag;
  const d = [padLo ? mulTick(Math.floor(lo / step + 1e-9), step) : lo, padHi ? mulTick(Math.ceil(hi / step - 1e-9), step) : hi];
  for (let n = 0; n < 2; n++) {
    const pad = [lo - d[0], d[1] - hi];
    if (Math.max(...pad) <= (d[1] - d[0]) * 0.1) break;
    if (pad[0] >= pad[1]) d[0] = lo; else d[1] = hi;
  }
  return d;
}
/** 官方 Ie:候选步长筛选(minSpacing 44px vertical / 64px horizontal);
 * format 未传 → Fe 恒真,无需文本测量。 */
function cdTicks(lo, hi, length, opts = {}) {
  const minSpacing = opts.minSpacing ?? 44;
  if (ALMOST_EQ(lo, hi) || !(length > 0) || !Number.isFinite(hi - lo)) {
    return Number.isFinite(lo) ? [lo] : [];
  }
  const integer = opts.integer === true && Math.floor(hi) - Math.ceil(lo) >= 1;
  const spacing = Math.min(Math.max(minSpacing, length / 6), Math.max(length / 3.5, 24));
  const half = Math.max(spacing / 2, 24);
  let full, part, single, lastResort;
  const start = Math.floor(Math.log10((hi - lo) * half / length));
  for (let p = start; p < start + 8; p++) {
    for (const cand of TICK_STEPS) {
      const step = cand * 10 ** p;
      const pxPerTick = step / (hi - lo) * length;
      if (pxPerTick < half || (integer && !Number.isInteger(step))) continue;
      const ticks = genTicks(lo, hi, step);
      if (ticks.length < (full?.length ?? 0) || (step > hi - lo && single !== undefined)) {
        return full ?? part ?? single ?? lastResort ?? [];
      }
      if (ticks.length === 1) single ??= ticks;
      else if (full !== undefined || pxPerTick >= spacing - 1e-6) full = ticks;
      else part = ticks;
    }
  }
  return full ?? part ?? single ?? lastResort ?? [];
}
/** 官方 Be 线性 y 尺度(includeZero 默认 "near":padded lo ≤ hi×25% 时归零;
 * 显式 min/max 为 pin,min≥max 整体忽略;全 0 数据 → 刻度 [0]) */
function cdYScale(values, opts = {}) {
  let lo = Infinity, hi = -Infinity, allInt = true, allZero = true;
  for (const v of values) {
    if (!Number.isFinite(v)) continue;
    if (v < lo) lo = v;
    if (v > hi) hi = v;
    if (!Number.isInteger(v)) allInt = false;
    if (v !== 0) allZero = false;
  }
  if (!Number.isFinite(lo)) return null;
  const pinMin = (typeof opts.min === 'number' && Number.isFinite(opts.min)) ? opts.min : undefined;
  const pinMax = (typeof opts.max === 'number' && Number.isFinite(opts.max)) ? opts.max : undefined;
  if (pinMin !== undefined && pinMax !== undefined && pinMin >= pinMax) return null;
  if (allZero && pinMin === undefined && pinMax === undefined) {
    return { domain: [-1, 1], ticks: [0] };
  }
  let plo = lo, phi = hi;
  if (ALMOST_EQ(plo, phi)) {
    const e = Math.abs(plo) * 0.1 || 1;
    phi += e;
    if (plo !== 0) plo -= e;
  } else {
    const pad = (phi - plo) * 0.05;
    plo = (plo >= 0 && plo - pad < 0) ? 0 : plo - pad;
    phi = (phi <= 0 && phi + pad > 0) ? 0 : phi + pad;
  }
  let dLo = pinMin ?? plo, dHi = pinMax ?? phi;
  if (dHi <= dLo) {
    const t = Math.abs(dLo) * 0.1 || 1;
    if (pinMax !== undefined && pinMin === undefined) dLo = dHi - t;
    else dHi = dLo + t;
  }
  let domain = niceDomain(dLo, dHi, pinMin === undefined, pinMax === undefined);
  // includeZero "near"(官方 je=0.25)
  if (pinMin === undefined && plo > 0 && plo <= phi * 0.25) domain[0] = 0;
  if (pinMax === undefined && phi < 0 && phi >= plo * 0.25 && plo < 0) domain[1] = 0;
  const ticks = cdTicks(domain[0], domain[1], opts.plotHeight ?? 200, { integer: allInt });
  return { domain, ticks };
}
/** 官方 S() barOrientation:单系列且 >1 个 x 标签含 ≥11 个非数字字符 → 横向 */
function barOrientation(seriesCount, labels) {
  if (seriesCount !== 1) return 'vertical';
  const longRe = /^\P{Nd}{11,}$/u;
  const longCount = labels.filter((l) => longRe.test(String(l))).length;
  return longCount > 1 ? 'horizontal' : 'vertical';
}


/** 官方 M():description = "{yTitle} by {xTitle}" / "by {xTitle}" / 无。
 * i18n(官方 Eke8/Rd12Y key,真机中文实测"按月份划分的访问量(千次)"):
 * 标题/轴标题含 CJK 即用中文语序(自包含检测,不依赖调用方传 locale),
 * 其余英文语序(全语种 i18n 记为残差)。 */
function chartDescription(spec) {
  const x = spec && spec.x_axis && spec.x_axis.title;
  const y = spec && spec.y_axis && spec.y_axis.title;
  if (!x) return '';
  const zh = /[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/.test(String(spec.title || '') + String(x) + String(y || ''));
  if (y) return zh ? `按${x}划分的${y}` : `${y} by ${x}`;
  return zh ? `按${x}划分` : `by ${x}`;
}

/** 图例显示判定(tool_cell_chart b() 同构) */
function hasLegend(spec) {
  const series = spec.series || [];
  if (series.length >= 2) return series.some((s) => !!s.name);
  const name = (series[0] && series[0].name || '').trim().toLowerCase();
  if (!name) return false;
  const title = (spec.title || '').trim().toLowerCase();
  const yTitle = (spec.y_axis && spec.y_axis.title || '').trim().toLowerCase();
  return name !== title && name !== yTitle;
}

/** x 标签(官方 formatX:x_axis.data[i] 缺失时 String(i+1)) */
function xLabels(spec, n) {
  const data = Array.isArray(spec.x_axis && spec.x_axis.data) ? spec.x_axis.data : [];
  const labels = [];
  for (let i = 0; i < n; i++) labels.push(data[i] !== undefined ? String(data[i]) : String(i + 1));
  return labels;
}

/**
 * 构建 claude_chart 渲染 HTML。
 * @param {object} spec chart_display_v0 input 整包(style/title/series/x_axis/y_axis + 未知键)
 * @param {object} [opts] { chartJsSource?: string } 桌面页内可显式传入 Chart.js 源码
 * @returns {string|null} 完整 HTML;spec 不可渲染(无有效数据)返回 null
 */
function buildClaudeChartHtml(spec, opts) {
  if (!spec || typeof spec !== 'object') return null;
  const style = ['line', 'bar', 'scatter'].includes(spec.style) ? spec.style : 'line';
  const series = Array.isArray(spec.series) ? spec.series : [];
  if (series.length === 0) return null;
  // 官方 validator(c59c32499 Rr):values 无有效值且 points 空 → 系列丢弃;全空 → 图不可渲染
  const liveSeries = series.filter((s) => s && typeof s === 'object' &&
    (Array.isArray(s.values) && s.values.some((v) => v !== null && v !== undefined && Number.isFinite(Number(v))) ||
     Array.isArray(s.points) && s.points.length > 0));
  if (liveSeries.length === 0) return null;

  const paints = assignPaints(liveSeries);
  const nRows = Math.max(...liveSeries.map((s) => (s.values || s.points || []).length));
  const labels = xLabels(spec, nRows);
  const legend = hasLegend(spec);
  const desc = chartDescription(spec);
  const flatValues = liveSeries.flatMap((s) => (s.values || (s.points || []).map((p) => p.y)) ?? [])
    .map((v) => (v === null || v === undefined) ? NaN : Number(v)).filter(Number.isFinite);

  // 值轴 pin(官方 D():log 轴 ≤0 忽略;min>=max 整体忽略)
  const ya = spec.y_axis || {};
  const clampLog = (v) => (ya.scale === 'log' && typeof v === 'number' && v <= 0) ? undefined : v;
  const mn = clampLog(typeof ya.min === 'number' ? ya.min : (ya.min !== undefined ? Number(ya.min) : undefined));
  const mx = clampLog(typeof ya.max === 'number' ? ya.max : (ya.max !== undefined ? Number(ya.max) : undefined));

  // 值域/刻度:官方 CD 算法离线复刻(cdYScale/cdTicks),替代 Chart.js nice
  let valueScale = null;
  if (ya.scale !== 'log') {
    valueScale = cdYScale(flatValues, { min: mn, max: mx, plotHeight: 200 });
  }

  // 官方 S():单系列长标签 → 横向条形图(值轴水平、类目轴垂直)
  const horizontal = style === 'bar' && barOrientation(liveSeries.length, labels) === 'horizontal';
  const isScatter = style === 'scatter';
  // Chart.js 键位:值轴(刻度算法所在)/类目轴
  const valueKey = horizontal ? 'x' : 'y';
  const catKey = horizontal ? 'y' : 'x';
  const pxPerUnit = valueScale
    ? (horizontal ? 680 : 200) / Math.max(1e-9, valueScale.domain[1] - valueScale.domain[0])
    : 0;

  const datasets = liveSeries.map((s, i) => {
    const paint = paints[i];
    if (isScatter) {
      // 官方 y():points 直接用;values → {x: idx+1, y}(C() 同构)
      const pts = (s.points && s.points.length)
        ? s.points.map((p) => ({ x: Number(p.x), y: Number(p.y) }))
        : (s.values || []).flatMap((v, idx) => (v === null || !Number.isFinite(Number(v))) ? [] : [{ x: idx + 1, y: Number(v) }]);
      return {
        label: s.name || `Series ${i + 1}`,
        data: pts,
        backgroundColor: paint,
        pointRadius: 4,
        pointHoverRadius: 4,
        borderWidth: 0,
      };
    }
    const values = (s.values || (s.points || []).map((p) => p.y)).map((v) => (v === null || v === undefined) ? null : Number(v));
    return {
      label: s.name || `Series ${i + 1}`,
      data: values,
      borderColor: paint,
      backgroundColor: paint,
      borderWidth: 2,
      borderJoinStyle: 'round',
      borderCapStyle: 'round',
      tension: 0,
      pointRadius: (ctx) => (ctx.dataIndex === values.length - 1 ? 4 : 0),
      pointHoverRadius: 0,
      pointBackgroundColor: paint,
      pointBorderColor: CD.SURFACE,
      pointBorderWidth: 3,
      fill: false,
      // 官方 g():圆角 min(4, 柱长px/4),仅值端外侧两角
      borderRadius: style === 'bar'
        ? (ctx) => {
            const v = ctx.dataset?.data?.[ctx.dataIndex];
            if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
            return Math.min(4, Math.abs(v) * pxPerUnit / 4);
          }
        : 0,
      borderSkipped: style === 'bar' ? 'start' : false,
      // 官方 BarMark 几何(备忘录 127):类目 slot 上限 D(lanes)=20n+2(n-1)px、
      // 类目间 inset=min(12, pitch×0.25)、lane 内柱间 2px——由页内 afterLayout
      // 插件按真实绘图区宽度数值化 barThickness(barPercentage/categoryPercentage
      // 组合表达不出「slot 上限 + 组间 inset」,Q502 实测组间隙被占满)。
      ...(style === 'bar' ? { barPercentage: 1, categoryPercentage: 1 } : {}),
    };
  });

  const pointStyle = isScatter ? 'circle' : (style === 'bar' ? 'rect' : 'line');
  // 官方 Legend swatch:line=10×2 横条 / bar=10×10 方 / scatter=8×8 圆
  const legendSwatch = isScatter ? { boxWidth: 8, boxHeight: 8 } : (style === 'bar' ? { boxWidth: 10, boxHeight: 10 } : { boxWidth: 10, boxHeight: 2 });

  const valueTicks = valueScale ? valueScale.ticks : null;

  // ⚠ 模板契约:config 必须在**页内**组装(2026-10-26 备忘录 126 根因)——
  // 旧实现 JSON.stringify(整份 config) 会把全部函数型选项(ticks.callback /
  // pointRadius / borderRadius)静默丢弃,图表退化成 Chart.js 全默认行为
  // (每点圆点、错误刻度密度、平顶柱)。JSON 只承载纯数据 payload。
  const payload = {
    type: isScatter ? 'scatter' : (style === 'bar' ? 'bar' : 'line'),
    labels,
    isScatter,
    horizontal,
    catKey,
    valueKey,
    legendSwatch,
    pointStyle,
    legend,
    domain: valueScale ? valueScale.domain : null,
    valueTicks,
    pinnedMin: !valueScale ? mn : null,
    pinnedMax: !valueScale ? mx : null,
    isLog: ya.scale === 'log',
    pxPerUnit,
    scatterXMin: isScatter && spec.x_axis && spec.x_axis.min !== undefined ? Number(spec.x_axis.min) : null,
    scatterXMax: isScatter && spec.x_axis && spec.x_axis.max !== undefined ? Number(spec.x_axis.max) : null,
    datasets: datasets.map((d) => ({
      ...d,
      data: d.data,
      // 函数型字段只传标记,页内按 style 重建
      _lastIndex: (style !== 'bar') ? (Array.isArray(d.data) ? d.data.length - 1 : -1) : -1,
    })),
  };

  const titleHtml = spec.title ? `<div class="cw-title">${escapeHtml(String(spec.title))}</div>` : '';
  const descHtml = desc ? `<div class="cw-desc">${escapeHtml(desc)}</div>` : '';
  const axisNote = [];
  if (ya.scale === 'log') axisNote.push('log scale');

  const json = JSON.stringify(payload).replace(/</g, '\\u003c');
  return `<!doctype html>
<html><head><meta charset="utf-8">
<style>
  html, body { margin: 0; padding: 0; background: ${CD.SURFACE}; }
  #widget-container { width: 720px; box-sizing: border-box; padding: 0; background: ${CD.SURFACE};
    font-family: ${CD.FONT_FAMILY}; color: ${CD.TEXT_PRIMARY}; }
  .cw-head { padding: 2px 2px 6px; }
  .cw-title { font-size: 15px; font-weight: 500; line-height: 22px; color: ${CD.TEXT_PRIMARY}; }
  .cw-desc { font-size: 12px; line-height: 17px; color: ${CD.TEXT_SECONDARY}; margin-top: 2px; }
  .cw-note { font-size: 11px; color: ${CD.TEXT_SECONDARY}; padding: 0 2px; }
  .cw-chart { width: 720px; height: ${CD.PLOT_HEIGHT + 60}px; }
</style></head>
<body>
<div id="widget-container">
  <div class="cw-head">${titleHtml}${descHtml}</div>
  <div class="cw-chart"><canvas id="cd-chart"></canvas></div>
  ${axisNote.length ? `<div class="cw-note">${escapeHtml(axisNote.join(' · '))}</div>` : ''}
</div>
${chartJsScriptTag(opts)}
<script>
(function () {
  try {
    var P = ${json};
    var CD = ${JSON.stringify({ TEXT_SECONDARY: CD.TEXT_SECONDARY, GRID: CD.GRID, AXIS: CD.AXIS, SURFACE: CD.SURFACE, FONT_FAMILY: CD.FONT_FAMILY })};

    // 官方 ge(formatYTicks compact):逐刻度 |v|≥1000 → compact 3 位有效数字
    function fmtNum(v) {
      if (typeof v !== 'number' || !Number.isFinite(v)) return String(v == null ? '' : v);
      if (Math.abs(v) >= 1000) {
        return new Intl.NumberFormat('en-US', { notation: 'compact', maximumSignificantDigits: 3 }).format(v);
      }
      return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(v);
    }

    // 官方 CD 刻度集整体替换 Chart.js 自动 nice(v4 的 afterBuildTicks 走插件通知)
    var cdTicksPlugin = {
      id: 'xwx-cd-ticks',
      afterBuildTicks: function (chart, args, opts) {
        if (!opts || !opts.values || !opts.values.length) return;
        if (args.scale && args.scale.id === opts.axisId) {
          args.scale.ticks = opts.values.map(function (v) { return { value: v }; });
        }
      },
    };

    // 官方类目 slot 几何(备忘录 127,源 c20f35e63 D()/j()/c3cf96714):
    //   pitch = 绘图区长/类目数(point-kind)
    //   inset = min(12, pitch×0.25)          —— 类目之间的间隔(图1 根因)
    //   slot  = min(D(lanes), pitch - inset),D(n) = 20n + 2(n-1)
    //   lane  = (slot - 2(lanes-1)) / lanes   —— 单柱宽(上限 20px)
    // afterLayout 时 scale 已量好真实宽度、dataset 元素还未计算几何 →
    // 数值化 barThickness(Chart.js v4 以 stack 居中排布,组内 2px lane 间隙
    // 为已知残差,组间 inset 契约精确成立)。
    var cdSlotPlugin = {
      id: 'xwx-cd-slot',
      afterLayout: function (chart) {
        if (P.type !== 'bar' || P.isScatter) return;
        var cat = chart.scales[P.catKey];
        var data = chart.data;
        var n = data.labels ? data.labels.length : (data.datasets[0] ? data.datasets[0].data.length : 0);
        var lanes = (data.datasets && data.datasets.length) || 1;
        if (!cat || !n || cat.width <= 0) return;
        var pitch = cat.width / n;
        var inset = Math.min(12, pitch * 0.25);
        var slot = Math.min(20 * lanes + 2 * (lanes - 1), Math.max(1, pitch - inset));
        var lane = Math.max(1, (slot - 2 * (lanes - 1)) / lanes);
        data.datasets.forEach(function (ds) { ds.barThickness = lane; });
      },
    };

    var datasets = P.datasets.map(function (d) {
      if (P.type === 'scatter') return d;
      return Object.assign({}, d, {
        // 官方 LineMark:仅末点 r=4 填充系列色 + surface 描边 3px
        pointRadius: function (ctx) { return ctx.dataIndex === d._lastIndex ? 4 : 0; },
        // 官方 g():圆角 min(4, 柱长px/4),仅值端外侧两角
        borderRadius: P.type === 'bar'
          ? function (ctx) {
              var v = ctx.dataset && ctx.dataset.data ? ctx.dataset.data[ctx.dataIndex] : null;
              if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
              return Math.min(4, Math.abs(v) * P.pxPerUnit / 4);
            }
          : 0,
      });
    });

    var config = {
      type: P.type,
      data: P.isScatter ? { datasets: datasets } : { labels: P.labels, datasets: datasets },
      plugins: [cdTicksPlugin, cdSlotPlugin],
      options: {
        animation: false,
        responsive: false,
        devicePixelRatio: 2,
        ...(P.horizontal ? { indexAxis: 'y' } : {}),
        layout: { padding: { top: 4, right: 8, bottom: 2, left: 2 } },
        scales: (function () {
          var cat = {
            grid: { display: P.isScatter, color: CD.GRID, drawTicks: false },
            border: { color: CD.AXIS, width: 1 },
            ticks: {
              color: CD.TEXT_SECONDARY, font: { size: 11, family: CD.FONT_FAMILY },
              maxRotation: 45, autoSkip: true, maxTicksLimit: 12, padding: 6,
            },
          };
          if (P.isScatter && P.catKey === 'x') {
            cat.type = 'linear';
            if (P.scatterXMin != null) cat.min = P.scatterXMin;
            if (P.scatterXMax != null) cat.max = P.scatterXMax;
          }
          var val = {
            grid: { color: CD.GRID, drawTicks: false },
            border: { color: CD.AXIS, width: 1 },
            ticks: {
              color: CD.TEXT_SECONDARY, font: { size: 11, family: CD.FONT_FAMILY },
              callback: function (v) { return fmtNum(v); }, padding: 6,
            },
          };
          if (P.valueTicks) {
            val.min = P.domain[0];
            val.max = P.domain[1];
          } else {
            val.ticks.maxTicksLimit = 5;
            if (P.pinnedMin != null) val.min = P.pinnedMin;
            if (P.pinnedMax != null) val.max = P.pinnedMax;
          }
          if (P.isLog) val.type = 'logarithmic';
          var scales = {};
          scales[P.catKey] = cat;
          scales[P.valueKey] = val;
          return scales;
        })(),
        plugins: {
          legend: {
            display: P.legend,
            position: 'bottom',
            align: 'start',
            labels: {
              usePointStyle: true,
              pointStyle: P.pointStyle,
              color: CD.TEXT_SECONDARY,
              font: { size: 12, family: CD.FONT_FAMILY },
              boxWidth: P.legendSwatch.boxWidth,
              boxHeight: P.legendSwatch.boxHeight,
              padding: 16,
            },
          },
          tooltip: { enabled: false },
          'xwx-cd-ticks': { axisId: P.valueKey, values: P.valueTicks || [] },
        },
      },
    };
    delete config.options.scales[P.valueKey].ticks.__cdAxisId;
    delete config.options.scales[P.valueKey].ticks.__cdValues;

    var canvas = document.getElementById('cd-chart');
    canvas.width = 716; canvas.height = ${CD.PLOT_HEIGHT};
    canvas.style.width = '716px'; canvas.style.height = '${CD.PLOT_HEIGHT}px';
    config.options.maintainAspectRatio = false;
    window._widgetReady = true;
    new Chart(canvas.getContext('2d'), config);
    // 渲染完成信号(chatgpt-chart-html.js 同一契约):渲染端(server.js
    // _renderFullHtmlImpl / 桌面 widget_renderer.rs)等的是 _widgetRendered,
    // 不是 _widgetReady。animation:false → new Chart() 构造返回即同步画完。
    // 此标志缺失时两端都等满超时(后端 8s、桌面 10s)才强制截图——每个
    // claude_chart 白等一轮,PDF/DOCX 双格式 × 图表数放大(2026-10-27
    // 导出耗时翻倍回归的根因,实测 9.5s/张 → 1.4s/张,PNG 逐字节同观感)。
    window._widgetRendered = true;
  } catch (e) {
    window._widgetError = String(e && e.message || e);
    document.getElementById('widget-container').innerHTML =
      '<div style="padding:20px;color:#c00">Chart render error: ' + window._widgetError + '</div>';
    // 失败同样放行:渲染端立即截错误占位,不等超时(chatgpt_chart 同语义)
    window._widgetRendered = true;
  }
})();
</script>
</body></html>`;
}

function escapeHtml(s) {
  return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

module.exports = { buildClaudeChartHtml, CD_TOKENS: CD, cdYScale, cdTicks, barOrientation, niceDomain, genTicks };