@x-cmd/draw 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # draw
2
2
 
3
- > English | [中文](README.cn.md)
3
+ > **English** | [简体中文](readme/cn.md) | [Deutsch](readme/de.md) | [Español](readme/es.md) | [Français](readme/fr.md) | [Italiano](readme/it.md) | [Português](readme/pt.md) | [Русский](readme/ru.md) | [Українська](readme/uk.md) | [日本語](readme/ja.md) | [한국어](readme/ko.md) | [Čeština](readme/cs.md) | [Polski](readme/pl.md) | [Română](readme/ro.md) | [Türkçe](readme/tr.md) | [Tiếng Việt](readme/vi.md) | [ไทย](readme/th.md) | [Bahasa Indonesia](readme/id.md)
4
4
 
5
5
  [![JSR score](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.jsr.io%2Fscopes%2Fx-cmd%2Fpackages%2Fdraw&query=%24.score&label=JSR%20score&color=yellowgreen)](https://jsr.io/@x-cmd/draw/score)
6
6
  [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/x-cmd/draw/badge)](https://securityscorecards.dev/viewer/?uri=github.com/x-cmd/draw)
package/dist/lib.d.ts CHANGED
@@ -17,6 +17,9 @@ export { renderCombo } from './render/combo.js';
17
17
  export { renderQR } from './render/qr.js';
18
18
  export { renderSankey } from './render/sankey.js';
19
19
  export { renderStored } from './render/dispatch.js';
20
+ export { esc, fmtFull, fmtNum, textW } from './render/svg.js';
21
+ export { parseColor, requireQRText, QR_DEFAULTS } from './render/qr.js';
22
+ export { assertDims } from './render/radar.js';
20
23
  export type { RenderOpts } from './render/svg.js';
21
24
  import { type DrawResult } from './render/query.js';
22
25
  export { renderFromUrl, renderStoredFromUrl } from './render/query.js';
package/dist/lib.js CHANGED
@@ -22,6 +22,10 @@ export { renderCombo } from './render/combo.js';
22
22
  export { renderQR } from './render/qr.js';
23
23
  export { renderSankey } from './render/sankey.js';
24
24
  export { renderStored } from './render/dispatch.js';
25
+ // Small helpers that page builders (and the x-cmd-hosted worker) reuse:
26
+ export { esc, fmtFull, fmtNum, textW } from './render/svg.js';
27
+ export { parseColor, requireQRText, QR_DEFAULTS } from './render/qr.js';
28
+ export { assertDims } from './render/radar.js';
25
29
  import { renderFromUrl } from './render/query.js';
26
30
  export { renderFromUrl, renderStoredFromUrl } from './render/query.js';
27
31
  export { CHART_TEMPLATES, fingerprint, canonicalJson, } from './store.js';
@@ -18,14 +18,26 @@ export function renderBarGrid(spec, o) {
18
18
  });
19
19
  // 几何(规范 960×520 实测):起点 78/214,格 14×12,横距 18 纵距 6
20
20
  const sx = Math.round(width * 0.0604);
21
- const startX = Math.round(width * 0.0813);
22
- const startY = Math.round(height * 0.4115);
23
- const pitch = Math.min(32, (width - startX * 2) / Math.max(n, 1));
21
+ const baseX = Math.round(width * 0.0813);
22
+ const baseY = Math.round(height * 0.4115);
23
+ const pitch = Math.min(32, (width - baseX * 2) / Math.max(n, 1));
24
24
  const cellW = pitch * (14 / 32);
25
25
  const vs = height / 520;
26
26
  const cellH = 12 * vs;
27
27
  const gapY = 6 * vs;
28
28
  const headR = Math.round(width * 0.9396);
29
+ // Sparse data (fewer columns/rows than the designer spec's dense series):
30
+ // center the cell block instead of leaving a small cluster in one corner.
31
+ // Dense layouts (n>=12 and rows>=10) keep the exact spec geometry.
32
+ const blockW = n * pitch - (pitch - cellW);
33
+ const blockH = rows * (cellH + gapY) - gapY;
34
+ const sparse = n < 12 || rows < 10;
35
+ const plotTop = Math.round(154 * vs) + Math.round(24 * vs);
36
+ const plotBottom = Math.round(height * 0.86);
37
+ const startX = sparse ? baseX + Math.max(0, (width - baseX * 2 - blockW) / 2) : baseX;
38
+ const startY = sparse
39
+ ? baseY + Math.max(0, plotTop + (plotBottom - plotTop - blockH) / 2 - baseY)
40
+ : baseY;
29
41
  const parts = [card(width, height, plain)];
30
42
  // 表头(等宽):[Σ] Total | [◆] Peak | 右侧注释行
31
43
  const mono = (x, y, fs, text, cls = 'muted', anchor = 'start') => `<text x="${r2(x)}" y="${r2(y)}" text-anchor="${anchor}" font-family="${MONO}" font-size="${r2(fs)}" fill="var(--d-${cls === 'muted' ? 'muted' : 'text'})"${cls === 'value' ? ' style="font-variant-numeric:tabular-nums"' : ''}>${esc(text)}</text>`;
@@ -39,9 +51,11 @@ export function renderBarGrid(spec, o) {
39
51
  parts.push(`<line x1="${r2(sx)}" y1="${r2(Math.round(154 * vs))}" x2="${r2(headR)}" y2="${r2(Math.round(154 * vs))}" stroke="var(--d-grid)" stroke-dasharray="4 5"/>`);
40
52
  // 单元格:行 0 在顶,active = 自底向上 levels[col] 格
41
53
  for (let col = 0; col < n; col++) {
54
+ const d = spec.data[col];
55
+ const tip = o.interactive ? ` data-tip="${esc(`${d.label} · ${fmtFull(d.value)}${spec.unit ? ' ' + spec.unit : ''}`)}"` : '';
42
56
  for (let row = 0; row < rows; row++) {
43
57
  const active = row >= rows - levels[col];
44
- parts.push(`<rect x="${r2(startX + col * pitch)}" y="${r2(startY + row * (cellH + gapY))}" width="${r2(cellW)}" height="${r2(cellH)}" rx="1" fill="${active ? sVar(0) : 'var(--d-faint)'}"/>`);
58
+ parts.push(`<rect x="${r2(startX + col * pitch)}" y="${r2(startY + row * (cellH + gapY))}" width="${r2(cellW)}" height="${r2(cellH)}" rx="1" fill="${active ? sVar(0) : 'var(--d-faint)'}"${tip}/>`);
45
59
  }
46
60
  }
47
61
  // 时间刻度:约每 n/12 列一个(规范 24 列 → 每隔 1 列)
@@ -1,5 +1,5 @@
1
1
  import { card } from '../theme.js';
2
- import { esc, fmtNum, niceTicks, r2, textW, topLegend, trunc, svgDoc, titleBlock, yAxisGrid, findPeak, onVar, sVar, pushBarLabelsAllOrNothing, labelStride, LabelPlacer, reserveBands } from './svg.js';
2
+ import { esc, fmtFull, fmtNum, niceTicks, r2, textW, topLegend, trunc, svgDoc, titleBlock, yAxisGrid, findPeak, onVar, sVar, pushBarLabelsAllOrNothing, labelStride, LabelPlacer, reserveBands } from './svg.js';
3
3
  import { yTickInset } from './measure.js';
4
4
  // 规范 bar-1 实测几何(960×520):left 76、右留 50、顶 94(0.181h)、底 448(0.862h)、X 标签 480
5
5
  // 留白 = max(规范比例, 实测刻度列):长刻度/窄画布时左缘撑大,刻度不裁字
@@ -79,10 +79,10 @@ export function renderBarMulti(spec, o) {
79
79
  `<stop offset="0" stop-color="var(--d-ramp-a)"/><stop offset="1" stop-color="var(--d-ramp-b)"/></linearGradient></defs>`,
80
80
  ];
81
81
  if (rules.legend === 'top-left') {
82
- parts.push(topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), left, legendY, 'left', rules.legendShape));
82
+ parts.push(topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i], ...(o.interactive ? { index: i } : {}) })), left, legendY, 'left', rules.legendShape));
83
83
  }
84
84
  else {
85
- parts.push(topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), plain ? right : width - pad, legendY, 'right', rules.legendShape));
85
+ parts.push(topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i], ...(o.interactive ? { index: i } : {}) })), plain ? right : width - pad, legendY, 'right', rules.legendShape));
86
86
  }
87
87
  yAxisGrid(parts, ticks, y, left, right, bottom, rules.grid, rules.gridDash, false, rules.baseline, [], rules.tickFont, geo ? 18 : 8);
88
88
  const step = (right - left) / n;
@@ -102,14 +102,15 @@ export function renderBarMulti(spec, o) {
102
102
  const groupX = left + step * pi + (step - (barW * k + (k - 1) * gap)) / 2;
103
103
  const x = groupX + si * (barW + gap);
104
104
  const yt = y(v);
105
+ const tip = o.interactive ? ` data-tip="${esc(`${spec.labels[pi]} · ${s.name}: ${fmtFull(v)}${spec.unit ? ' ' + spec.unit : ''}`)}" data-series="${si}"` : '';
105
106
  if (rules.barCorner > 0) {
106
- parts.push(`<rect x="${r2(x)}" y="${r2(yt)}" width="${r2(barW)}" height="${r2(bottom - yt)}" rx="${rules.barCorner}" fill="${colors[si]}"/>`);
107
+ parts.push(`<rect x="${r2(x)}" y="${r2(yt)}" width="${r2(barW)}" height="${r2(bottom - yt)}" rx="${rules.barCorner}" fill="${colors[si]}"${tip}/>`);
107
108
  }
108
109
  else {
109
110
  const m = Math.min(3, barW / 2, bottom - yt);
110
111
  const path = `M${r2(x)} ${r2(bottom)}V${r2(yt + m)}Q${r2(x)} ${r2(yt)} ${r2(x + m)} ${r2(yt)}` +
111
112
  `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z`;
112
- parts.push(`<path d="${path}" fill="${colors[si]}"/>`);
113
+ parts.push(`<path d="${path}" fill="${colors[si]}"${tip}/>`);
113
114
  }
114
115
  const isPeak = si === peakS && pi === peakP;
115
116
  // 零值/占位不标:零高柱上飘"0"是噪音(标注克制原则)
@@ -1,5 +1,5 @@
1
1
  import { TAB, card } from '../theme.js';
2
- import { esc, fmtNum, niceTicks, r2, textW, topLegend, trunc, svgDoc, titleBlock, yAxisGrid, findPeak, onVar, sVar, pushBarLabelsAllOrNothing, labelStride, LabelPlacer, reserveBands } from './svg.js';
2
+ import { esc, fmtFull, fmtNum, niceTicks, r2, textW, topLegend, trunc, svgDoc, titleBlock, yAxisGrid, findPeak, onVar, sVar, pushBarLabelsAllOrNothing, labelStride, LabelPlacer, reserveBands } from './svg.js';
3
3
  import { yTickInset, tickColW } from './measure.js';
4
4
  /**
5
5
  * Stacked multi-series bars (auto-switches to 100% stacking on extreme magnitudes).
@@ -79,7 +79,7 @@ export function renderBarStacked(spec, o) {
79
79
  });
80
80
  const parts = [
81
81
  card(width, height),
82
- topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), width - pad, pad + 16),
82
+ topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i], ...(o.interactive ? { index: i } : {}) })), width - pad, pad + 16),
83
83
  ];
84
84
  if (pctMode) {
85
85
  for (const t of tickVals) {
@@ -117,7 +117,8 @@ export function renderBarStacked(spec, o) {
117
117
  `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yTop)} ${r2(x + barW)} ${r2(yTop + m)}V${r2(cursor)}Z`;
118
118
  // 分隔白描边按段高自适应:段太矮时描边会盖掉颜色
119
119
  const sw = segH >= 6 ? 2 : 0;
120
- parts.push(`<path d="${path}" fill="${colors[si]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}/>`);
120
+ const tip = o.interactive ? ` data-tip="${esc(`${label} · ${s.name}: ${fmtFull(v)}${spec.unit ? ' ' + spec.unit : ''}`)}" data-series="${si}"` : '';
121
+ parts.push(`<path d="${path}" fill="${colors[si]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}${tip}/>`);
121
122
  const isPeakSeg = si === peakS && pi === peakP;
122
123
  if (num === 'all' || (num === 'peak' && isPeakSeg)) {
123
124
  // 数值一律入柱(像 900/1k 那样),字号自适应缩小;
@@ -1,5 +1,5 @@
1
1
  import { card } from '../theme.js';
2
- import { esc, fmtNum, niceTicks, r2, trunc, svgDoc, titleBlock, yAxisGrid, pushBarLabelsAllOrNothing, labelStride, textW, LabelPlacer, reserveBands } from './svg.js';
2
+ import { esc, fmtFull, fmtNum, niceTicks, r2, trunc, svgDoc, titleBlock, yAxisGrid, pushBarLabelsAllOrNothing, labelStride, textW, LabelPlacer, reserveBands } from './svg.js';
3
3
  import { yTickInset } from './measure.js';
4
4
  /**
5
5
  * Single-series bar chart.
@@ -59,7 +59,8 @@ export function renderBar(spec, o) {
59
59
  const m = Math.min(4, barW / 2, bottom - yt);
60
60
  const path = `M${r2(x)} ${r2(bottom)}V${r2(yt + m)}Q${r2(x)} ${r2(yt)} ${r2(x + m)} ${r2(yt)}` +
61
61
  `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z`;
62
- parts.push(`<path d="${path}" fill="url(#dg-bar)"/>`);
62
+ const tip = o.interactive ? ` data-tip="${esc(`${d.label} · ${fmtFull(d.value)}${spec.unit ? ' ' + spec.unit : ''}`)}"` : '';
63
+ parts.push(`<path d="${path}" fill="url(#dg-bar)"${tip}/>`);
63
64
  const isPeak = i === peakIdx;
64
65
  // 零值不标:没有柱子的"0"是噪音(标注克制原则)
65
66
  if (d.value > 0 && (num === 'all' || (num === 'peak' && isPeak))) {
@@ -1,5 +1,5 @@
1
1
  import { TAB, card } from '../theme.js';
2
- import { esc, fmtNum, niceTicks, r2, topLegend, trunc, textW, LabelPlacer, pushLineLabel, pushBarLabelsAllOrNothing, smoothPath, svgDoc, titleBlock, findPeak, onVar, sVar, labelStride, reserveBands, reserveEdges, toSegments } from './svg.js';
2
+ import { esc, fmtFull, fmtNum, niceTicks, r2, topLegend, trunc, textW, LabelPlacer, pushLineLabel, pushBarLabelsAllOrNothing, smoothPath, svgDoc, titleBlock, findPeak, onVar, sVar, labelStride, reserveBands, reserveEdges, toSegments } from './svg.js';
3
3
  import { yTickInset, tickColW } from './measure.js';
4
4
  /**
5
5
  * Bars + line(s) in one chart; dual y-axes on >5× magnitude spread.
@@ -44,7 +44,7 @@ export function renderCombo(spec, o) {
44
44
  const yLine = (v) => bottom - (v / lineYMax) * (bottom - contentTop);
45
45
  const parts = [
46
46
  card(width, height),
47
- topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i] })), width - pad, pad + 16),
47
+ topLegend(spec.series.map((s, i) => ({ name: s.name, color: colors[i], ...(o.interactive ? { index: i } : {}) })), width - pad, pad + 16),
48
48
  ];
49
49
  for (const t of ticks) {
50
50
  const gy = r2(y(t));
@@ -71,9 +71,10 @@ export function renderCombo(spec, o) {
71
71
  const gIdx = spec.series.indexOf(s);
72
72
  const pts = s.values.map((v, pi) => [cx(pi), (dual ? yLine : y)(v)]);
73
73
  lineSegs.push(...toSegments(pts));
74
- lineSvg.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${colors[gIdx]}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>`);
74
+ lineSvg.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${colors[gIdx]}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"${o.interactive ? ` data-series="${gIdx}"` : ''}/>`);
75
75
  pts.forEach(([lx, ly], pi) => {
76
- lineSvg.push(`<circle cx="${r2(lx)}" cy="${r2(ly)}" r="2.5" fill="${colors[gIdx]}" stroke="#ffffff" stroke-width="1.5"/>`);
76
+ const tip = o.interactive ? ` data-tip="${esc(`${spec.labels[pi]} · ${s.name}: ${fmtFull(s.values[pi])}${spec.unit ? ' ' + spec.unit : ''}`)}" data-series="${gIdx}"` : '';
77
+ lineSvg.push(`<circle cx="${r2(lx)}" cy="${r2(ly)}" r="2.5" fill="${colors[gIdx]}" stroke="#ffffff" stroke-width="1.5"${tip}/>`);
77
78
  const isPeak = gIdx === peakS && pi === peakP;
78
79
  if (num === 'all' || (num === 'peak' && isPeak)) {
79
80
  lineLabels.push({ px: lx, py: ly, text: fmtNum(s.values[pi]), isPeak });
@@ -97,6 +98,7 @@ export function renderCombo(spec, o) {
97
98
  if (stacked && v <= 0)
98
99
  return;
99
100
  const isPeak = gIdx === peakS && pi === peakP;
101
+ const tip = o.interactive ? ` data-tip="${esc(`${spec.labels[pi]} · ${s.name}: ${fmtFull(v)}${spec.unit ? ' ' + spec.unit : ''}`)}" data-series="${gIdx}"` : '';
100
102
  if (stacked) {
101
103
  const x = left + step * pi + (step - barW) / 2;
102
104
  const segH = (v / yMax) * (bottom - contentTop);
@@ -108,7 +110,7 @@ export function renderCombo(spec, o) {
108
110
  // 细段描边会吃掉颜色,够高才画
109
111
  const sw = segH >= 12 ? 2 : 0;
110
112
  parts.push(`<path d="M${r2(x)} ${r2(yTop + drawH)}V${r2(yTop + m)}Q${r2(x)} ${r2(yTop)} ${r2(x + m)} ${r2(yTop)}` +
111
- `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yTop)} ${r2(x + barW)} ${r2(yTop + m)}V${r2(yTop + drawH)}Z" fill="${colors[gIdx]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}/>`);
113
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yTop)} ${r2(x + barW)} ${r2(yTop + m)}V${r2(yTop + drawH)}Z" fill="${colors[gIdx]}"${sw ? ` stroke="var(--d-card)" stroke-width="${sw}"` : ''}${tip}/>`);
112
114
  // 堆叠段一律入柱,微小段不标
113
115
  if (num === 'all' || (num === 'peak' && isPeak)) {
114
116
  const text = fmtNum(v);
@@ -123,7 +125,7 @@ export function renderCombo(spec, o) {
123
125
  const yt = y(v);
124
126
  const m = Math.min(3, barW / 2, bottom - yt);
125
127
  parts.push(`<path d="M${r2(x)} ${r2(bottom)}V${r2(yt + m)}Q${r2(x)} ${r2(yt)} ${r2(x + m)} ${r2(yt)}` +
126
- `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z" fill="${colors[gIdx]}"/>`);
128
+ `H${r2(x + barW - m)}Q${r2(x + barW)} ${r2(yt)} ${r2(x + barW)} ${r2(yt + m)}V${r2(bottom)}Z" fill="${colors[gIdx]}"${tip}/>`);
127
129
  // 零值不标(标注克制原则:零高柱上飘"0"是噪音)
128
130
  if (v > 0 && (num === 'all' || (num === 'peak' && isPeak))) {
129
131
  barLabels.push({ x, yt, v, color: colors[gIdx], isPeak, barW, row: bi, fx: left + step * pi + step / 2, fyt: groupTop[pi] });
@@ -220,19 +222,22 @@ function renderComboEvil(spec, o) {
220
222
  }
221
223
  // 柱:圆角 rx5,槽内缩 12
222
224
  const barW = Math.max(4, slot - Math.min(24, width * 0.025));
225
+ const evilTip = (i, name, v, idx) => o.interactive ? ` data-tip="${esc(`${spec.labels[i]} · ${name}: ${fmtFull(v)}${spec.unit ? ' ' + spec.unit : ''}`)}" data-series="${idx}"` : '';
223
226
  bars.forEach((s) => {
227
+ const gIdx = spec.series.indexOf(s);
224
228
  s.values.forEach((v, i) => {
225
229
  if (v <= 0)
226
230
  return;
227
- parts.push(`<rect x="${r2(x0 + i * slot + (slot - barW) / 2)}" y="${r2(yBar(v))}" width="${r2(barW)}" height="${r2(y0 - yBar(v))}" rx="5" fill="${barColor}"/>`);
231
+ parts.push(`<rect x="${r2(x0 + i * slot + (slot - barW) / 2)}" y="${r2(yBar(v))}" width="${r2(barW)}" height="${r2(y0 - yBar(v))}" rx="5" fill="${barColor}"${evilTip(i, s.name, v, gIdx)}/>`);
228
232
  });
229
233
  });
230
234
  // 线:独立量程,平滑折线 + r4 实心点
231
235
  lines.forEach((s) => {
236
+ const gIdx = spec.series.indexOf(s);
232
237
  const pts = s.values.map((v, i) => [x0 + i * slot + slot / 2, yLine(v)]);
233
- parts.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${lineColor}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`);
234
- pts.forEach(([px, py]) => {
235
- parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="4" fill="${lineColor}"/>`);
238
+ parts.push(`<path d="${smoothPath(pts)}" fill="none" stroke="${lineColor}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"${o.interactive ? ` data-series="${gIdx}"` : ''}/>`);
239
+ pts.forEach(([px, py], i) => {
240
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="4" fill="${lineColor}"${evilTip(i, s.name, s.values[i], gIdx)}/>`);
236
241
  });
237
242
  });
238
243
  const xStride = labelStride(spec.labels, slot);
@@ -240,19 +245,22 @@ function renderComboEvil(spec, o) {
240
245
  if (i % xStride === 0)
241
246
  parts.push(`<text x="${r2(x0 + i * slot + slot / 2)}" y="${r2(height * 0.936)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(trunc(l, 12))}</text>`);
242
247
  });
243
- // 右上图例(方块 11×11 rx3,13px)
248
+ // 右上图例(方块 11×11 rx3,13px);interactive 模式带 data-legend + 透明命中区
244
249
  const items = [
245
- ...(bars.length ? [{ name: bars[0].name, color: barColor }] : []),
246
- ...(lines.length ? [{ name: lines[0].name, color: lineColor }] : []),
250
+ ...(bars.length ? [{ name: bars[0].name, color: barColor, idx: spec.series.indexOf(bars[0]) }] : []),
251
+ ...(lines.length ? [{ name: lines[0].name, color: lineColor, idx: spec.series.indexOf(lines[0]) }] : []),
247
252
  ];
248
253
  let lx = x0 + w;
249
254
  const legendY = Math.round(height * 0.116);
250
255
  for (let i = items.length - 1; i >= 0; i--) {
251
256
  const it = items[i];
252
257
  const tw = textW(it.name, 13);
253
- parts.push(`<text x="${r2(lx)}" y="${r2(legendY)}" text-anchor="end" font-size="13" fill="var(--d-muted)">${esc(it.name)}</text>`);
258
+ const lg = o.interactive ? ` data-legend="${it.idx}"` : '';
259
+ parts.push(`<text x="${r2(lx)}" y="${r2(legendY)}" text-anchor="end" font-size="13" fill="var(--d-muted)"${lg}>${esc(it.name)}</text>`);
254
260
  lx -= tw + 16;
255
- parts.push(`<rect x="${r2(lx)}" y="${r2(legendY - 9)}" width="11" height="11" rx="3" fill="${it.color}"/>`);
261
+ parts.push(`<rect x="${r2(lx)}" y="${r2(legendY - 9)}" width="11" height="11" rx="3" fill="${it.color}"${lg}/>`);
262
+ if (o.interactive)
263
+ parts.push(`<rect x="${r2(lx - 4)}" y="${r2(legendY - 16)}" width="${r2(tw + 24)}" height="20" fill="none" pointer-events="all" role="button" tabindex="0"${lg}/>`);
256
264
  lx -= 27;
257
265
  }
258
266
  return svgDoc(width, height, 'combo', version, spec.title ?? 'combo chart', spec, skin, parts.join(''));
@@ -144,6 +144,10 @@ export function renderPie(spec, o) {
144
144
  parts.push(`<defs>${defs}</defs>`);
145
145
  }
146
146
  const sliceFill = (i) => (rules.pieGradient ? `url(#dgs-${i})` : rowColor(rows[i].colorIdx));
147
+ // Interactive embedders: preformatted tooltip text (value + share) on each slice
148
+ const tipAttr = (row) => o.interactive
149
+ ? ` data-tip="${esc(`${row.label} · ${fmtFull(row.value)}${spec.unit ? ' ' + spec.unit : ''} (${((row.value / total) * 100).toFixed(1)}%)`)}"`
150
+ : '';
147
151
  // 扇区方向/起始角:规范 Evil 系 = 逆时针(ECharts 度),OpenData = 顺时针自 12 点钟
148
152
  const startRad = (rules.pieStart * Math.PI) / 180;
149
153
  const dirSign = rules.pieDir === 'ccw' ? 1 : -1;
@@ -153,10 +157,10 @@ export function renderPie(spec, o) {
153
157
  if (rows.length === 1) {
154
158
  const stroke = gap > 0 ? ` stroke="var(--d-halo)" stroke-width="${gap}"` : '';
155
159
  if (r > 0) {
156
- parts.push(`<circle cx="${r2(cx)}" cy="${r2(cy)}" r="${r2((R + r) / 2)}" fill="none" stroke="${sliceFill(0)}" stroke-width="${r2(R - r - Math.max(gap, 0))}"/>`);
160
+ parts.push(`<circle cx="${r2(cx)}" cy="${r2(cy)}" r="${r2((R + r) / 2)}" fill="none" stroke="${sliceFill(0)}" stroke-width="${r2(R - r - Math.max(gap, 0))}"${tipAttr(rows[0])}/>`);
157
161
  }
158
162
  else {
159
- parts.push(`<circle cx="${r2(cx)}" cy="${r2(cy)}" r="${r2(R)}" fill="${sliceFill(0)}"${stroke}/>`);
163
+ parts.push(`<circle cx="${r2(cx)}" cy="${r2(cy)}" r="${r2(R)}" fill="${sliceFill(0)}"${stroke}${tipAttr(rows[0])}/>`);
160
164
  }
161
165
  }
162
166
  else {
@@ -174,7 +178,7 @@ export function renderPie(spec, o) {
174
178
  if (d) {
175
179
  const fill = rules.pieGradient ? `url(#dgs-${rows.indexOf(row)})` : rowColor(row.colorIdx);
176
180
  const stroke = gap > 0 ? ` stroke="var(--d-halo)" stroke-width="${gap}" stroke-linejoin="round" stroke-linecap="round"` : '';
177
- parts.push(`<path d="${d}" fill="${fill}"${stroke}/>`);
181
+ parts.push(`<path d="${d}" fill="${fill}"${stroke}${tipAttr(row)}/>`);
178
182
  }
179
183
  });
180
184
  }
@@ -1,6 +1,6 @@
1
1
  import { ApiError } from '../specs/index.js';
2
2
  import { card, TAB } from '../theme.js';
3
- import { esc, fmtNum, r2, textW, trunc, sVar, svgDoc, titleBlock } from './svg.js';
3
+ import { esc, fmtFull, fmtNum, r2, textW, trunc, sVar, svgDoc, titleBlock } from './svg.js';
4
4
  import { radialFit } from './measure.js';
5
5
  const HAND_FONT = "Handlee,'Comic Sans MS','Chalkboard SE','Comic Neue','Segoe Print',cursive";
6
6
  /**
@@ -60,10 +60,15 @@ export function renderRadar(spec, o) {
60
60
  .map((d, i) => pt(i, (d.value / max) * R).map(r2).join(' '))
61
61
  .join('L');
62
62
  parts.push(`<path d="M${dataPoly}Z" fill="var(--d-s1)" fill-opacity="0.18" stroke="var(--d-s1)" stroke-width="2" stroke-linejoin="round"/>`);
63
- // 顶点圆点
63
+ // 顶点圆点(interactive:外加透明命中圈,小点也可 hover)
64
+ const unit = spec.unit ? ` ${spec.unit}` : '';
64
65
  spec.data.forEach((d, i) => {
65
66
  const [px, py] = pt(i, (d.value / max) * R);
66
67
  parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="3" fill="var(--d-s1)" stroke="var(--d-card)" stroke-width="2"/>`);
68
+ if (o.interactive) {
69
+ const tip = ` data-tip="${esc(`${d.label} · ${fmtFull(d.value)}${unit}`)}"`;
70
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="11" fill="none" pointer-events="all"${tip}/>`);
71
+ }
67
72
  });
68
73
  // 维度标签
69
74
  spec.data.forEach((d, i) => {
@@ -133,8 +138,12 @@ function renderRadarEvil(spec, o) {
133
138
  parts.push(`<path d="M${pts.map((p) => p.map(r2).join(' ')).join('L')}Z" fill="${colors[si]}" fill-opacity="${r2(0.12 + si * 0.02)}" stroke="${colors[si]}" stroke-width="2" stroke-linejoin="round"/>`);
134
139
  });
135
140
  allPts.forEach((pts, si) => {
136
- pts.forEach(([px, py]) => {
141
+ pts.forEach(([px, py], i) => {
137
142
  parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="5" fill="var(--d-card)" stroke="${colors[si]}" stroke-width="2"/>`);
143
+ if (o.interactive) {
144
+ const tip = ` data-tip="${esc(`${spec.labels[i]} · ${spec.series[si].name}: ${fmtFull(spec.series[si].values[i])}${spec.unit ? ` ${spec.unit}` : ''}`)}" data-series="${si}"`;
145
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="11" fill="none" pointer-events="all"${tip}/>`);
146
+ }
138
147
  });
139
148
  });
140
149
  // 轴端标签:维度名 + 各系列数值内嵌(系列色,13px 粗体)
@@ -208,8 +217,13 @@ function renderRadarXcmd(spec, o) {
208
217
  // 数据多边形 + 方形顶点标记(6×6 rx1)
209
218
  const pts = spec.data.map((d, i) => pt(i, (d.value / scaleMax) * R));
210
219
  parts.push(`<path d="M${pts.map((p) => p.map(r2).join(' ')).join('L')}Z" fill="var(--d-s1)" fill-opacity="0.16" stroke="var(--d-s1)" stroke-width="2.25" stroke-linejoin="round"/>`);
211
- pts.forEach(([px, py]) => {
220
+ pts.forEach(([px, py], i) => {
212
221
  parts.push(`<rect x="${r2(px - 3)}" y="${r2(py - 3)}" width="6" height="6" rx="1" fill="var(--d-s1)"/>`);
222
+ if (o.interactive) {
223
+ const d = spec.data[i];
224
+ const tip = ` data-tip="${esc(`${d.label} · ${fmtFull(d.value)}${spec.unit ? ` ${spec.unit}` : ''}`)}"`;
225
+ parts.push(`<circle cx="${r2(px)}" cy="${r2(py)}" r="11" fill="none" pointer-events="all"${tip}/>`);
226
+ }
213
227
  });
214
228
  // 手写维度标签(Handlee,18px)
215
229
  spec.data.forEach((d, i) => {
@@ -152,12 +152,14 @@ function renderSankeyBasic(spec, o) {
152
152
  const nodeW = width * 0.0194; // 14/720
153
153
  const { nodes, links, cols } = layoutSankey(spec, width * 0.1667, width * 0.8806, height * 0.119, height * 0.871, nodeW);
154
154
  const styles = labelStyles(nodes, cols);
155
+ const unit = spec.unit ? ` ${spec.unit}` : '';
156
+ const tip = (text) => (o.interactive ? ` data-tip="${esc(text)}"` : '');
155
157
  const parts = [card(width, height, true)];
156
158
  for (const l of links) {
157
- parts.push(`<path d="${l.d}" fill="${sVar(l.from.colorIdx % skin.series.length)}" fill-opacity="0.46"/>`);
159
+ parts.push(`<path d="${l.d}" fill="${sVar(l.from.colorIdx % skin.series.length)}" fill-opacity="0.46"${tip(`${l.from.name} → ${l.to.name} · ${fmtFull(l.link.value)}${unit}`)}/>`);
158
160
  }
159
161
  for (const n of nodes) {
160
- parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${sVar(n.colorIdx % skin.series.length)}"/>`);
162
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${sVar(n.colorIdx % skin.series.length)}"${tip(`${n.name} · ${fmtFull(n.value)}${unit}`)}/>`);
161
163
  const last = n.col === cols - 1;
162
164
  const st = styles.get(n) ?? 'two';
163
165
  if (n.col === 0)
@@ -188,12 +190,14 @@ function renderSankeyFund(spec, o) {
188
190
  parts.push(`<text x="${r2(width * 0.033)}" y="${r2(height * 0.067)}" font-size="18" font-weight="600" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(trunc(spec.title, 40))}</text>`);
189
191
  if (spec.unit)
190
192
  parts.push(`<text x="${r2(width * 0.967)}" y="${r2(height * 0.067)}" text-anchor="end" font-size="12" fill="var(--d-muted)">${esc(trunc(spec.unit, 24))}</text>`);
193
+ const unit = spec.unit ? ` ${spec.unit}` : '';
194
+ const tip = (text) => (o.interactive ? ` data-tip="${esc(text)}"` : '');
191
195
  for (const l of links) {
192
- parts.push(`<path d="${l.d}" fill="url(#sk-${links.indexOf(l)})" fill-opacity="0.38"/>`);
196
+ parts.push(`<path d="${l.d}" fill="url(#sk-${links.indexOf(l)})" fill-opacity="0.38"${tip(`${l.from.name} → ${l.to.name} · ${fmtFull(l.link.value)}${unit}`)}/>`);
193
197
  }
194
198
  for (const n of nodes) {
195
199
  const c = sVar(n.colorIdx % k);
196
- parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(n.w)}" height="${r2(n.h)}" rx="${r2(height * 0.0174)}" fill="${c}" fill-opacity="0.42" stroke="${c}" stroke-width="1.5"/>`);
200
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(n.w)}" height="${r2(n.h)}" rx="${r2(height * 0.0174)}" fill="${c}" fill-opacity="0.42" stroke="${c}" stroke-width="1.5"${tip(`${n.name} · ${fmtFull(n.value)}${unit}`)}/>`);
197
201
  if (n.h >= 34) {
198
202
  parts.push(`<text x="${r2(n.x + n.w / 2)}" y="${r2(n.y + n.h / 2 - 3)}" text-anchor="middle" font-size="12" font-weight="700" fill="var(--d-ink)">${esc(trunc(n.name, 12))}</text>`);
199
203
  parts.push(`<text x="${r2(n.x + n.w / 2)}" y="${r2(n.y + n.h / 2 + 14)}" text-anchor="middle" font-size="11" fill="var(--d-muted)" style="${TAB}">${fmtFull(n.value)}</text>`);
@@ -252,18 +256,21 @@ function renderSankeyPipeline(spec, o) {
252
256
  // 中缝 = 中央面板各内缩 0.0395w(规范 760 宽下为 350/410)
253
257
  const xa = midX - width * 0.0395;
254
258
  const xb = midX + width * 0.0395;
255
- const half = (x1, x2, y1, y2, lh, fill) => {
259
+ const half = (x1, x2, y1, y2, lh, fill, tip = '') => {
256
260
  const c1 = x1 + (x2 - x1) * 0.52;
257
261
  const c2 = x2 - (x2 - x1) * 0.52;
258
262
  return `<path d="M${r2(x1)} ${r2(y1)}C${r2(c1)} ${r2(y1)} ${r2(c2)} ${r2(y2)} ${r2(x2)} ${r2(y2)}` +
259
- `L${r2(x2)} ${r2(y2 + lh)}C${r2(c2)} ${r2(y2 + lh)} ${r2(c1)} ${r2(y1 + lh)} ${r2(x1)} ${r2(y1 + lh)}Z" fill="${fill}" fill-opacity="0.34"/>`;
263
+ `L${r2(x2)} ${r2(y2 + lh)}C${r2(c2)} ${r2(y2 + lh)} ${r2(c1)} ${r2(y1 + lh)} ${r2(x1)} ${r2(y1 + lh)}Z" fill="${fill}" fill-opacity="0.34"${tip}/>`;
260
264
  };
265
+ const unit = spec.unit ? ` ${spec.unit}` : '';
266
+ const tip = (text) => (o.interactive ? ` data-tip="${esc(text)}"` : '');
261
267
  for (const l of links) {
262
- parts.push(half(l.from.x + nodeW, xa, l.sy, l.ty, l.lh, 'url(#sk-in)'));
263
- parts.push(half(xb, l.to.x, l.sy, l.ty, l.lh, 'url(#sk-out)'));
268
+ const t = tip(`${l.from.name} → ${l.to.name} · ${fmtFull(l.link.value)}${unit}`);
269
+ parts.push(half(l.from.x + nodeW, xa, l.sy, l.ty, l.lh, 'url(#sk-in)', t));
270
+ parts.push(half(xb, l.to.x, l.sy, l.ty, l.lh, 'url(#sk-out)', t));
264
271
  }
265
272
  for (const n of nodes) {
266
- parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${nodeColor(n)}"/>`);
273
+ parts.push(`<rect x="${r2(n.x)}" y="${r2(n.y)}" width="${r2(nodeW)}" height="${r2(n.h)}" rx="${r2(nodeW * 0.286)}" fill="${nodeColor(n)}"${tip(`${n.name} · ${fmtFull(n.value)}${unit}`)}/>`);
267
274
  if (n.x < midX)
268
275
  nodeLabel(parts, n.name, n.value, n.x - 12, n.y + n.h / 2, 'end', false, 'two');
269
276
  else
@@ -11,6 +11,7 @@ export declare function rangeTicks(min: number, max: number, count?: number): nu
11
11
  export declare function topLegend(items: readonly {
12
12
  name: string;
13
13
  color: string;
14
+ index?: number;
14
15
  }[], x: number, y: number, anchor?: 'left' | 'right', shape?: 'circle' | 'square'): string;
15
16
  export declare const sVar: (i: number) => string;
16
17
  export declare const onVar: (i: number) => string;
@@ -45,6 +46,8 @@ export interface RenderOpts {
45
46
  refLine?: number;
46
47
  /** 参考线文案(?reflabel=WCAG AA) */
47
48
  refLabel?: string;
49
+ /** Interactive embedders (/explore): emit data-tip on data shapes for client tooltips */
50
+ interactive?: boolean;
48
51
  }
49
52
  export declare function textW(s: string, fs: number): number;
50
53
  export declare function smoothPath(pts: [number, number][]): string;
@@ -79,18 +79,25 @@ function metaTag(template, version, spec) {
79
79
  return `<metadata>${esc(json)}</metadata>`;
80
80
  }
81
81
  // 顶部图例:anchor='left' 从左往右(shadcn 圆点) | 'right' 从右往左(Evil 方块)
82
+ // item.index is only passed by interactive embedders: the legend item gets a
83
+ // data-legend attribute plus an invisible hit rect (for click-to-toggle series).
82
84
  export function topLegend(items, x, y, anchor = 'right', shape = 'circle') {
83
85
  const parts = [];
84
- const swatch = (sx, color) => shape === 'square'
85
- ? `<rect x="${r2(sx - 5)}" y="${r2(y - 9)}" width="11" height="11" rx="3" fill="${color}"/>`
86
- : `<circle cx="${r2(sx)}" cy="${r2(y - 4)}" r="5" fill="${color}"/>`;
86
+ const lg = (index) => (index === undefined ? '' : ` data-legend="${index}"`);
87
+ const swatch = (sx, color, index) => shape === 'square'
88
+ ? `<rect x="${r2(sx - 5)}" y="${r2(y - 9)}" width="11" height="11" rx="3" fill="${color}"${lg(index)}/>`
89
+ : `<circle cx="${r2(sx)}" cy="${r2(y - 4)}" r="5" fill="${color}"${lg(index)}/>`;
90
+ const hit = (bx, bw, index) => index === undefined
91
+ ? ''
92
+ : `<rect x="${r2(bx)}" y="${r2(y - 16)}" width="${r2(bw)}" height="20" fill="none" pointer-events="all" role="button" tabindex="0"${lg(index)}/>`;
87
93
  const gap = shape === 'square' ? 18 : 13;
88
94
  if (anchor === 'left') {
89
95
  let cx = x;
90
96
  for (const it of items) {
91
97
  const w = textW(it.name, 12);
92
- parts.push(swatch(cx, it.color));
93
- parts.push(`<text x="${r2(cx + gap)}" y="${r2(y)}" font-size="12" font-weight="500" fill="var(--d-text)">${esc(it.name)}</text>`);
98
+ parts.push(swatch(cx, it.color, it.index));
99
+ parts.push(`<text x="${r2(cx + gap)}" y="${r2(y)}" font-size="12" font-weight="500" fill="var(--d-text)"${lg(it.index)}>${esc(it.name)}</text>`);
100
+ parts.push(hit(cx - 10, gap + w + 16, it.index));
94
101
  cx += gap + w + 26;
95
102
  }
96
103
  }
@@ -99,8 +106,10 @@ export function topLegend(items, x, y, anchor = 'right', shape = 'circle') {
99
106
  for (let i = items.length - 1; i >= 0; i--) {
100
107
  const it = items[i];
101
108
  const w = textW(it.name, 12);
102
- parts.push(`<text x="${r2(cx)}" y="${r2(y)}" text-anchor="end" font-size="12" font-weight="500" fill="var(--d-text)">${esc(it.name)}</text>`);
103
- parts.push(swatch(cx - w - (shape === 'square' ? 18 : 10), it.color));
109
+ const swatchX = cx - w - (shape === 'square' ? 18 : 10);
110
+ parts.push(`<text x="${r2(cx)}" y="${r2(y)}" text-anchor="end" font-size="12" font-weight="500" fill="var(--d-text)"${lg(it.index)}>${esc(it.name)}</text>`);
111
+ parts.push(swatch(swatchX, it.color, it.index));
112
+ parts.push(hit(swatchX - 8, w + (shape === 'square' ? 18 : 10) + 14, it.index));
104
113
  cx -= w + 28 + (shape === 'square' ? 8 : 0);
105
114
  }
106
115
  }
@@ -45,13 +45,28 @@ const OVERFLOW_SERIES = [
45
45
  duo('#E11D48', '#FB7185'), // rose
46
46
  duo('#06B6D4', '#22D3EE'), // cyan
47
47
  ];
48
+ // Overflow for monochrome (grayscale) palettes: bright series colors would
49
+ // break the monochrome look (e.g. market-mono), so pad with grays instead.
50
+ const MONO_OVERFLOW = [
51
+ duo('#8E8E8E', '#B4B4B4'),
52
+ duo('#A6A6A6', '#8E8E8E'),
53
+ duo('#C2C2C2', '#A6A6A6'),
54
+ ];
55
+ const isGray = (hex) => {
56
+ const m = /^#([0-9a-f]{6})$/i.exec(hex);
57
+ if (!m)
58
+ return false;
59
+ const n = parseInt(m[1], 16);
60
+ return (n >> 16) === ((n >> 8) & 0xff) && ((n >> 8) & 0xff) === (n & 0xff);
61
+ };
48
62
  function padSeries(series) {
49
63
  const MIN = 10; // 饼图按扇区着色:9 类 + Other = 10 色,末扇与首扇相邻不得同色
50
64
  if (series.length >= MIN)
51
65
  return series;
52
66
  const have = new Set(series.map((d) => d.light));
67
+ const mono = series.every((d) => isGray(d.light) && isGray(d.dark));
53
68
  const out = [...series];
54
- for (const d of OVERFLOW_SERIES) {
69
+ for (const d of mono ? MONO_OVERFLOW : OVERFLOW_SERIES) {
55
70
  if (out.length >= MIN)
56
71
  break;
57
72
  if (!have.has(d.light)) {
package/dist/theme.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare const FONT = "'DrawInter',Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif";
1
+ export declare const FONT = "'DrawInter',Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei','Hiragino Sans','Yu Gothic','Meiryo','Noto Sans JP','Apple SD Gothic Neo','Malgun Gothic','Noto Sans KR',sans-serif";
2
2
  export declare const TAB = "font-variant-numeric:tabular-nums";
3
3
  export declare function card(w: number, h: number, plain?: boolean): string;
package/dist/theme.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // 公共字体与画布。字体栈与设计规范一致(Inter 系统栈;CJK 回退)。
2
2
  // DrawInter = 每张 SVG 内嵌的 Inter 图表子集(same 源于 styles/inter.ts),
3
3
  // 拉丁/数字/符号用它(跨平台像素一致),子集外字符(中文等)沿栈回退系统字体。
4
- export const FONT = "'DrawInter',Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif";
4
+ // CJK 顺序注意: 汉字统一码下静态栈只能给一族字形(此处简中优先,与既有行为一致);
5
+ // 日文假名/谚文由后续 JP/KR 族接住。按文字运行选栈(检测假名/谚文切日/韩栈)见 issue #2。
6
+ export const FONT = "'DrawInter',Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei','Hiragino Sans','Yu Gothic','Meiryo','Noto Sans JP','Apple SD Gothic Neo','Malgun Gothic','Noto Sans KR',sans-serif";
5
7
  export const TAB = 'font-variant-numeric:tabular-nums';
6
8
  // 卡片:canvas='card' 时白底 1px 边框 12px 圆角;plain(规范约定)透明由页面承接
7
9
  export function card(w, h, plain = false) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-cmd/draw",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "SVG chart rendering as a service, a library, and a CLI — pie/bar/hbar/line/area/radar/gauge/scatter/combo/sankey/qr, same params everywhere",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/README.cn.md DELETED
@@ -1,247 +0,0 @@
1
- # draw
2
-
3
- > [English](README.md) | 中文
4
-
5
- [![JSR score](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.jsr.io%2Fscopes%2Fx-cmd%2Fpackages%2Fdraw&query=%24.score&label=JSR%20score&color=yellowgreen)](https://jsr.io/@x-cmd/draw/score)
6
- [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/x-cmd/draw/badge)](https://securityscorecards.dev/viewer/?uri=github.com/x-cmd/draw)
7
-
8
- AI 时代的 SVG 图表生成服务(狗粮原型)。单端点 `/draw?type=...`,数据在 URL 里、输出带机器可读 `<metadata>`、Cloudflare Workers + TypeScript 直生成 SVG。风格体系对齐设计师规范(13 张 SVG),每图种多风格变体。
9
-
10
- ## 先睹为快
11
-
12
- 数据全在 URL 里 — 浏览器打开、`<img>` 嵌入、贴进仓库 README,SVG 直接渲染:
13
-
14
- ### 桑基图 — PR 生命周期:类型 → 结果 → 时段 (`type=sankey&t=pipeline`)
15
-
16
- ```text
17
- https://x-cmd.com/draw?type=sankey&t=pipeline&labels=feat,fix,docs,chore,merged,closed,rejected,0-1y,1-2y,2y+&links=feat>merged:38;feat>closed:12;feat>rejected:8;fix>merged:33;fix>closed:6;fix>rejected:2;docs>merged:16;docs>closed:4;chore>merged:5;chore>closed:6;chore>rejected:6;merged>0-1y:52;merged>1-2y:28;merged>2y+:12;closed>0-1y:14;closed>1-2y:9;closed>2y+:5;rejected>0-1y:9;rejected>1-2y:5;rejected>2y+:2&title=Pull%20requests%20lifecycle&unit=prs
18
- ```
19
-
20
- ![桑基图:PR 生命周期](https://x-cmd.com/draw?type=sankey&t=pipeline&labels=feat,fix,docs,chore,merged,closed,rejected,0-1y,1-2y,2y+&links=feat>merged:38;feat>closed:12;feat>rejected:8;fix>merged:33;fix>closed:6;fix>rejected:2;docs>merged:16;docs>closed:4;chore>merged:5;chore>closed:6;chore>rejected:6;merged>0-1y:52;merged>1-2y:28;merged>2y+:12;closed>0-1y:14;closed>1-2y:9;closed>2y+:5;rejected>0-1y:9;rejected>1-2y:5;rejected>2y+:2&title=Pull%20requests%20lifecycle&unit=prs)
21
-
22
- ### 水平柱 — 运行时吞吐,真实实测 (`type=hbar`; deno 7238 · node 6553 · bun 4972 ops/s, Apple Silicon)
23
-
24
- ```text
25
- https://x-cmd.com/draw?type=hbar&labels=deno,node,bun&values=7238,6553,4972&title=Runtime%20throughput&unit=ops%2Fs
26
- ```
27
-
28
- ![水平柱:运行时吞吐](https://x-cmd.com/draw?type=hbar&labels=deno,node,bun&values=7238,6553,4972&title=Runtime%20throughput&unit=ops%2Fs)
29
-
30
- ### 雷达图 — 三软件对比 (`type=radar&t=evil`, 多系列)
31
-
32
- ```text
33
- https://x-cmd.com/draw?type=radar&t=evil&labels=startup,ecosystem,extensibility,memory,ease&series=vscode:60,95,90,55,80&series=neovim:95,65,85,95,35&series=zed:92,50,55,90,60&title=Editor%20comparison
34
- ```
35
-
36
- ![雷达图:编辑器对比](https://x-cmd.com/draw?type=radar&t=evil&labels=startup,ecosystem,extensibility,memory,ease&series=vscode:60,95,90,55,80&series=neovim:95,65,85,95,35&series=zed:92,50,55,90,60&title=Editor%20comparison)
37
-
38
- ### 混合图 — 周下载 vs 星标增速 (`type=combo`, 量级差自动双 y 轴)
39
-
40
- ```text
41
- https://x-cmd.com/draw?type=combo&labels=Mon,Tue,Wed,Thu,Fri,Sat,Sun&series=Downloads:120,180,150,210,240,200,260&line=Star%20growth:3.1,3.4,3.2,3.8,4.1,3.9,4.5&title=Weekly%20npm%20downloads&unit=dl
42
- ```
43
-
44
- ![混合图:周下载与星标增速](https://x-cmd.com/draw?type=combo&labels=Mon,Tue,Wed,Thu,Fri,Sat,Sun&series=Downloads:120,180,150,210,240,200,260&line=Star%20growth:3.1,3.4,3.2,3.8,4.1,3.9,4.5&title=Weekly%20npm%20downloads&unit=dl)
45
-
46
- ### 水平柱 — 分区 issue 开/闭蝴蝶图 (`type=hbar&t=xcmd-issue`)
47
-
48
- ```text
49
- https://x-cmd.com/draw?type=hbar&t=xcmd-issue&labels=cli,core,docs,ci,ui&series=open:12,8,15,4,9&series=closed:38,52,20,11,26&title=Issues%20by%20area
50
- ```
51
-
52
- ![水平柱:分区 issue 开闭](https://x-cmd.com/draw?type=hbar&t=xcmd-issue&labels=cli,core,docs,ci,ui&series=open:12,8,15,4,9&series=closed:38,52,20,11,26&title=Issues%20by%20area)
53
-
54
- ### 环形图 — 语言构成 (`type=pie&t=market-mono`)
55
-
56
- ```text
57
- https://x-cmd.com/draw?type=pie&t=market-mono&title=Languages&unit=%25&labels=TypeScript,Shell,JavaScript,Rust,Other&values=68,14,9,6,3
58
- ```
59
-
60
- ![环形图:语言构成](https://x-cmd.com/draw?type=pie&t=market-mono&title=Languages&unit=%25&labels=TypeScript,Shell,JavaScript,Rust,Other&values=68,14,9,6,3)
61
-
62
- ## 三种使用方式(同一份渲染核心)
63
-
64
- **托管服务**(零安装):直接拼 URL — `https://x-cmd.com/draw?type=pie&labels=A,B&values=3,2`
65
-
66
- **npm 库**(离线/嵌入,同步无网络,参数与 URL 完全一致):
67
-
68
- ```sh
69
- npm install @x-cmd/draw
70
- ```
71
- ```ts
72
- import { draw } from '@x-cmd/draw';
73
- const { svg } = draw({ type: 'pie', labels: 'A,B', values: '3,2', t: 'evil', scheme: 'dark' });
74
- // 也接受查询串: draw('?type=bar&labels=Mon,Tue&values=3,5')
75
- // 数组值 = 重复参数(labels 含逗号时): draw({ type: 'bar', labels: ['Q1, 2024', 'Q2'], values: [1, 2] })
76
- ```
77
-
78
- **CLI**(`npm i -g @x-cmd/draw` 后可用,或 `npx`):
79
-
80
- ```sh
81
- draw --type pie --labels "TypeScript,Python,Go" --values "4821,2312,980" --out pie.svg
82
- draw --type hbar --labels a,b,c --values 3,2,1 --theme xcmd # 长参数(--theme/--width/--height)
83
- draw "?type=hbar&labels=a,b,c&values=3,2,1&t=xcmd" # 裸查询串,与 URL 同参
84
- ```
85
-
86
- **自托管**:三种入口任选 —
87
-
88
- ```sh
89
- git clone https://github.com/x-cmd/draw && cd draw && npm install
90
- npm run serve # Node 本地服务(默认 http://localhost:8787/draw,含演示页)
91
- npm run dev # Cloudflare wrangler 本地开发
92
- bash scripts/setup.sh # 一键部署到你自己的 Cloudflare 账号
93
- ```
94
-
95
- 环境变量(Node 服务):`PORT`(默认 8787)· `BASE_PATH` · `DATA_REPO`/`DATA_BRANCH`/`GITHUB_TOKEN`(配置后 POST 短链同样可用,未配置时与线上自部署一样优雅降级)。
96
-
97
- **Deno**(原生 TS;渲染核心是纯函数 — 不碰网络/文件,零权限沙盒即安全边界):
98
-
99
- ```ts
100
- import { draw } from "jsr:@x-cmd/draw"; // JSR(Deno 原生注册表)
101
- // 或 npm:import { draw } from "npm:@x-cmd/draw";
102
- const { svg } = draw({ type: "pie", labels: "A,B", values: "3,2" });
103
- ```
104
-
105
- ```sh
106
- deno add jsr:@x-cmd/draw
107
- # 仓库内直跑源码(免构建):
108
- deno task cli --type pie --labels A,B --values 3,2 --out pie.svg # 仅需 --allow-write
109
- deno task serve # 本地服务(同 npm run serve)
110
- # 渲染零权限可证:deno eval 默认无任何授权,直接 import 即渲染成功
111
- ```
112
-
113
- ## 端点
114
-
115
- **`GET /draw?type=<pie|bar|hbar|line|area|radar|gauge|scatter|combo|sankey|qr>`** — 渲染图表
116
-
117
- | type | 图表 | 示例 |
118
- |---|---|---|
119
- | `pie` | 环形图;`donut=0` 变实心饼<br><br>**<u>≤100 类(>9 自动合并 Other)</u>** | <a href="https://x-cmd.com/draw?type=pie&labels=TS,Py,Go,Rust&values=4821,2312,980,645&title=Stars%20by%20language"><img src="https://x-cmd.com/draw?type=pie&labels=TS,Py,Go,Rust&values=4821,2312,980,645&title=Stars%20by%20language" width="360" alt="pie example"></a> |
120
- | `bar` | 柱状图/分组并排;多系列加 `stack=1` 变堆叠柱<br><br>**<u>≤30 组</u>** | <a href="https://x-cmd.com/draw?type=bar&labels=Mon,Tue,Wed&series=dev:12,18,9&series=ci:8,11,6"><img src="https://x-cmd.com/draw?type=bar&labels=Mon,Tue,Wed&series=dev:12,18,9&series=ci:8,11,6" width="360" alt="bar example"></a> |
121
- | `hbar` | 水平柱状图(排行场景,标签左值右)<br><br>**<u>≤30 条,单系列(部分风格双系列)</u>** | <a href="https://x-cmd.com/draw?type=hbar&labels=cli,core,docs,ui&values=42,31,18,9&title=Commits%20by%20area"><img src="https://x-cmd.com/draw?type=hbar&labels=cli,core,docs,ui&values=42,31,18,9&title=Commits%20by%20area" width="360" alt="hbar example"></a> |
122
- | `line` | 折线图(平滑+渐变面积)/多折线<br><br>**<u>≤60 点</u>** | <a href="https://x-cmd.com/draw?type=line&labels=Jan,Feb,Mar,Apr,May,Jun&values=12,19,15,25,22,30&title=Stars"><img src="https://x-cmd.com/draw?type=line&labels=Jan,Feb,Mar,Apr,May,Jun&values=12,19,15,25,22,30&title=Stars" width="360" alt="line example"></a> |
123
- | `area` | 面积图/多系列面积(渐变填充)<br><br>**<u>≤60 点</u>** | <a href="https://x-cmd.com/draw?type=area&labels=Q1,Q2,Q3,Q4&values=8,14,23,37&title=Downloads"><img src="https://x-cmd.com/draw?type=area&labels=Q1,Q2,Q3,Q4&values=8,14,23,37&title=Downloads" width="360" alt="area example"></a> |
124
- | `radar` | 雷达图<br><br>**<u>3-12 维</u>** | <a href="https://x-cmd.com/draw?type=radar&t=evil&labels=perf,docs,tests,dx&series=v1:7,5,8,6&series=v2:8,8,9,8"><img src="https://x-cmd.com/draw?type=radar&t=evil&labels=perf,docs,tests,dx&series=v1:7,5,8,6&series=v2:8,8,9,8" width="360" alt="radar example"></a> |
125
- | `gauge` | 仪表盘(240° 弧+中心数值)<br><br>**<u>`value`+`max`(默认100),value≤max;多环 ≤8</u>** | <a href="https://x-cmd.com/draw?type=gauge&title=CI%20pass%20rate&value=87&max=100"><img src="https://x-cmd.com/draw?type=gauge&title=CI%20pass%20rate&value=87&max=100" width="360" alt="gauge example"></a> |
126
- | `scatter` | 散点图(双数值轴,支持负值;默认不标数值)<br><br>**<u>`x=&y=`,≤200 点</u>** | <a href="https://x-cmd.com/draw?type=scatter&x=1,2,3,4,5&y=4,5,3,6,5&title=Latency"><img src="https://x-cmd.com/draw?type=scatter&x=1,2,3,4,5&y=4,5,3,6,5&title=Latency" width="360" alt="scatter example"></a> |
127
- | `combo` | 混合图:柱(`series=`)+线(`line=`)同图,`stack=1` 变堆叠柱<br><br>**<u>≤30 组,共 ≤6 系列</u>** | <a href="https://x-cmd.com/draw?type=combo&labels=Mon,Tue,Wed,Thu,Fri&series=dl:120,180,150,210,240&line=growth:3.1,3.4,3.2,3.8,4.1&title=Downloads"><img src="https://x-cmd.com/draw?type=combo&labels=Mon,Tue,Wed,Thu,Fri&series=dl:120,180,150,210,240&line=growth:3.1,3.4,3.2,3.8,4.1&title=Downloads" width="360" alt="combo example"></a> |
128
- | `sankey` | 桑基图(流向带宽)<br><br>**<u>`labels=`+`links=A>B:30`,≤24 节点/60 链接</u>** | <a href="https://x-cmd.com/draw?type=sankey&labels=Visitors,Stars,Forks,PRs,Merged&links=Visitors>Stars:84;Stars>Forks:17;Forks>PRs:9;PRs>Merged:7&title=Contributor%20funnel"><img src="https://x-cmd.com/draw?type=sankey&labels=Visitors,Stars,Forks,PRs,Merged&links=Visitors>Stars:84;Stars>Forks:17;Forks>PRs:9;PRs>Merged:7&title=Contributor%20funnel" width="360" alt="sankey example"></a> |
129
- | `qr` | 二维码<br><br>**<u>`d`=文本(≤1000 字符),`fg`/`bg` 配色,`title`/`unit` 标注</u>** | <a href="https://x-cmd.com/draw?type=qr&d=https://github.com/x-cmd/draw&title=scan%20me"><img src="https://x-cmd.com/draw?type=qr&d=https://github.com/x-cmd/draw&title=scan%20me" width="360" alt="qr example"></a> |
130
-
131
- **`GET /draw`**(无参数)或 `?tab=pie` — 演示页(11 图种分类、全部风格变体、URL 双形态面板)
132
- **`POST /draw?type=...`** — 提交 JSON/CSV body 创建永久短链
133
- **`GET /draw/c/<hash>`** — 短链渲染(immutable)
134
-
135
- 通用参数:
136
-
137
- - `t` 风格家族(见下节,按图种取用;该图种未做时回退默认)
138
- - `scheme` 明暗:`auto`(默认,跟随系统)/ `dark` / `light`
139
- - `v` 钉住版本;`w`/`h` 尺寸(200–1600 / 140–1200,qr 为 120–1000 / 140–1000)
140
- - `num` 数值标注:`all` / `peak`(仅最高)/ `none`。默认跟随风格(设计规范变体多为 `none`,`?num=all` 显式全标)。适用于 pie/bar/hbar/line/area/scatter/combo;radar/gauge/sankey/qr 忽略
141
- - `subtitle` 编辑式副标题(仅 area 的编辑式标题风格 `t=opendata` 渲染)、`source` 数据来源脚注(仅 area 渲染,任意 `t`);其余图种解析但忽略
142
-
143
- ## 风格(`?t=`)
144
-
145
- 按图种提供变体,明暗双配色自动切换:
146
-
147
- | type | 可用家族 |
148
- |---|---|
149
- | `pie` | `opendata`(默认,标签全外)、`evil`(圆角环+内标值)、`evil-mono`(实心饼+引线外标)、`market-mono`(灰阶+环心总计)、`progress`(点状进度环)、`revenue`(渐变扇区+虚线内圈) |
150
- | `bar` | `evil`(默认,分组柱)、`base`(卡片柱)、`grid`(表格柱) |
151
- | `hbar` | `base`(默认)、`opendata`(支持 `ref=`/`reflabel=` 参考线)、`xcmd`(像素条,值为 %)、`xcmd-issue`(双系列蝴蝶)、`rank`(双系列实底+斜纹) |
152
- | `line` | `shadcn`(默认)、`evil`、`evil-glow`(发光)、`evil-mono`、`opendata`(线端标签) |
153
- | `area` | `evil`(默认,双系列虚线面积)、`star`(手绘风)、`opendata`(浓渐变+编辑标题)、`pixel`、`polka` |
154
- | `radar` | `base`(默认)、`evil`(多系列)、`xcmd` |
155
- | `sankey` | `base`(默认)、`fund`、`pipeline` |
156
- | `gauge` | `base`(默认)、`gradient`、`reliability`(分区环仪表) |
157
- | `scatter` / `combo` / `qr` | `base`(combo 另有 `evil`) |
158
-
159
- ## 传数据的两种方式
160
-
161
- **扁平参数(URL 永远可读,推荐)**:
162
-
163
- ```
164
- /draw?type=pie&title=Stars by language&unit=stars&labels=TypeScript,Python,Go,Rust&values=4821,2312,980,645
165
- /draw?type=bar&title=Weekly downloads&labels=Mon,Tue&values=1200,1800
166
- ```
167
-
168
- 标签含逗号时用重复参数:`labels=Q1, 2024&labels=Q2&values=1&values=2`
169
-
170
- **多系列对比**(type=bar 分组/堆叠、type=line 多折线、type=area 多面积,≤6 系列):
171
-
172
- ```
173
- /draw?type=area&labels=Mon,Tue,Wed&series=Desktop:120,180,150&series=Mobile:80,90,85
174
- ```
175
-
176
- **JSON 形态(复杂数据)**:`?d=` + URL 编码的 JSON:
177
-
178
- ```json
179
- {"title":"Stars by language","unit":"stars","data":[{"label":"TypeScript","value":4821},{"label":"Python","value":2312}]}
180
- ```
181
-
182
- 多系列 JSON:`{"labels":["Mon","Tue"],"series":[{"name":"draw","values":[120,180]},{"name":"qc","values":[80,90]}]}`
183
-
184
- 二维码:`/draw?type=qr&d=https://github.com/tzw&fg=%236366f1`
185
-
186
- 仪表盘:`/draw?type=gauge&title=Build pass rate&value=87&max=100`
187
-
188
- 散点图:`/draw?type=scatter&x=10,20,30&y=5,8,7`
189
-
190
- 混合图:`/draw?type=combo&labels=Mon,Tue&series=dl:120,180&line=growth:5,8`(柱与线量级差 >5 倍时自动启用双 y 轴)
191
-
192
- ## 短链接(数据存 GitHub 仓库,内容寻址、永不过期)
193
-
194
- ```
195
- POST /draw?type=pie body = 图表 spec JSON
196
- POST /draw?type=bar&t=evil body = CSV(text/csv,首行表头)
197
- → 201 {"hash":"a3f9c2d4e5f60718","url":"https://x-cmd.com/draw/c/a3f9c2d4e5f60718"}
198
-
199
- GET /draw/c/<hash> → SVG,永久 immutable 缓存
200
- ```
201
-
202
- - 指纹 = 规范化数据(template+theme+spec,递归排序 key)的 SHA-256 前 16 位;相同数据 → 相同短链(自动去重、幂等);读取时复核指纹,存档被改即拒绝
203
- - 多系列支持 bar/line/area/radar,以及 hbar(仅 `t=xcmd-issue`/`t=rank`,恰好 2 系列);其余 type 提交多系列会被 400 拒绝;POST 限 30 次/分钟/IP
204
- - 服务端配置:`DATA_REPO`(公开仓,`owner/name`,wrangler.jsonc)、`GITHUB_TOKEN`(secret,fine-grained PAT 仅授该仓 **Contents 写**;读取走 raw 免 token);数据文件存于 `charts/<hash>.json`
205
- - 可见性:数据仓是公开的,任何人可浏览目录——**请勿创建含敏感数据的短链**(私有存储方案规划中,将收费提供)
206
- - 对比 quickchart:短链会过期(6个月/数天),我们的永不过期
207
-
208
- ## 版本语义
209
-
210
- - 不带 `v`:渲染**最新版**,`Cache-Control: max-age=300`(链接随升级变化)
211
- - `?v=1`:钉住版本,`Cache-Control: max-age=86400`(1 天;渲染仍随部署演进,不承诺永久冻结)。`v` 取值 1..当前版本,超出报 400
212
- - `immutable` 仅用于短链 `/c/<hash>`(内容寻址,输出真正永不变化;短链忽略 `v` 参数)
213
-
214
- ## AI 可读
215
-
216
- 每个 SVG 内嵌 `<metadata>`(转义 JSON):`{generator, template, version, spec}`,数据与参数可直接 round-trip。文字全部用 `<text>`(真文本)。
217
-
218
- ## 自部署(一键)
219
-
220
- 部署一套自己的 draw 到你的 Cloudflare 账号(免费计划即可,只需 CF 账号):
221
-
222
- ```sh
223
- curl -fsSL https://raw.githubusercontent.com/x-cmd/draw/main/scripts/setup.sh | bash
224
- ```
225
-
226
- 脚本流程:克隆仓库 → wrangler 浏览器登录 → 部署 → 冒烟测试,结束打印你的 `*.workers.dev` 地址。GET 渲染全家桶(11 图种、全部风格)开箱即用。
227
-
228
- - **短链(POST)第一阶段未默认启用**,调用会返回"未配置"提示。启用方法:建一个公开仓存数据 → 本地 wrangler.jsonc 的 vars 设 `DATA_REPO=owner/name` → `npx wrangler secret put GITHUB_TOKEN`(fine-grained PAT 仅授该仓 Contents 写)→ 重新部署
229
- - 已 clone 仓库的,在仓库目录里跑 `npm run setup` 即可(跳过克隆)
230
- - 路径前缀自动适配:workers.dev 根路径与 `/draw` 子路由都能用,无需改代码;也可用 `BASE_PATH` var 显式钉死
231
- - 绑自有域名:dashboard → Workers → Settings → Domains & Routes 加 route(任意路径前缀)
232
- - Windows 请用 WSL 或 Git Bash 运行
233
-
234
- ## 开发
235
-
236
- ```sh
237
- npm install
238
- npm run dev # wrangler dev 本地起服
239
- npm test # vitest
240
- npm run check # tsc --noEmit × 3(worker / node / build)
241
- npm run build # 产 dist/(npm 库 + CLI)
242
- npm run deploy # wrangler deploy
243
- ```
244
-
245
- ## 许可
246
-
247
- 代码 [Apache-2.0](LICENSE)。内嵌字体遵循各自许可:Inter(OFL,全文见 `src/styles/inter-OFL.txt`)、Handlee(OFL)。