@open-spreadsheet/core 0.3.0 → 0.4.0

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/app/charts.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  /**
2
- * Charts drawn as SVG from a range: bar (grouped), line and pie. Hand-written,
2
+ * Charts drawn as SVG from a range: columns (grouped or stacked), horizontal
3
+ * bars, lines, areas, pie and doughnut, scatter, and combo. Hand-written,
3
4
  * like open-dashboard's: one y-axis, zero in the domain, a fixed categorical
4
5
  * palette, ticks from one formatter, text in ink colours.
5
6
  */
6
7
  import { CellError, formatValue, type Scalar } from '@open-spreadsheet/engine';
7
- import type { ChartSpec } from './types.ts';
8
+ import type { ChartSpec, ChartType } from './types.ts';
9
+
10
+ export const CHART_TYPES: ChartType[] = ['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'];
8
11
 
9
12
  export type { ChartSpec, ChartType } from './types.ts';
10
13
 
@@ -15,6 +18,71 @@ export interface ChartData {
15
18
 
16
19
  export const PALETTE = ['#2a78d6', '#e8710a', '#1e8e3e', '#d93025', '#9334e6', '#12b5cb', '#c5221f', '#7f6000'];
17
20
 
21
+ /**
22
+ * How a chart file looks: series colours, background, text, grid and type.
23
+ * A few come built in; a workspace's own live in assets/chart-styles.json so
24
+ * every workbook, teammate and agent draws with the same house style.
25
+ */
26
+ export interface ChartStyle {
27
+ id: string;
28
+ name: string;
29
+ colors: string[];
30
+ background: string;
31
+ text: string;
32
+ muted: string;
33
+ grid: string;
34
+ /** Grid lines drawn at all. */
35
+ gridLines: boolean;
36
+ font: 'sans' | 'serif' | 'mono' | 'rounded';
37
+ /** Corner radius of bars, 0–8. */
38
+ radius: number;
39
+ }
40
+
41
+ export const CHART_FONTS: Record<ChartStyle['font'], string> = {
42
+ sans: '-apple-system,BlinkMacSystemFont,"PingFang TC","Noto Sans TC","Segoe UI",sans-serif',
43
+ serif: '"Noto Serif TC","Songti TC",Georgia,"Times New Roman",serif',
44
+ mono: '"SF Mono",Menlo,Consolas,"Noto Sans Mono CJK TC",monospace',
45
+ rounded: '"SF Pro Rounded","Hiragino Maru Gothic ProN","Arial Rounded MT Bold",-apple-system,sans-serif',
46
+ };
47
+
48
+ export const BUILTIN_STYLES: ChartStyle[] = [
49
+ { id: 'default', name: 'Default', colors: PALETTE, background: '#ffffff', text: '#1f1f1f', muted: '#5f6368', grid: '#e8eaed', gridLines: true, font: 'sans', radius: 2 },
50
+ { id: 'ocean', name: 'Ocean', colors: ['#0b3c5d', '#1d7ab8', '#4fb0e0', '#8fd0ee', '#328cc1', '#17577e', '#a9d6e5', '#5c7f99'], background: '#ffffff', text: '#0b2233', muted: '#52687a', grid: '#e3edf3', gridLines: true, font: 'sans', radius: 3 },
51
+ { id: 'warm', name: 'Warm', colors: ['#c2410c', '#ea8a2e', '#f2c14e', '#9a3412', '#d9775b', '#7c2d12', '#e7b98a', '#b45309'], background: '#fffaf3', text: '#3b2417', muted: '#8a6a55', grid: '#f1e4d3', gridLines: true, font: 'serif', radius: 0 },
52
+ { id: 'pastel', name: 'Pastel', colors: ['#7aa6e8', '#f4a6a0', '#8fd3b6', '#f6cf7d', '#b9a4e6', '#86d0dc', '#f2b3d6', '#a9c18a'], background: '#ffffff', text: '#2e3440', muted: '#6b7280', grid: '#eef0f3', gridLines: true, font: 'rounded', radius: 6 },
53
+ { id: 'mono', name: 'Mono', colors: ['#111111', '#555555', '#8c8c8c', '#bdbdbd', '#333333', '#707070', '#a6a6a6', '#d4d4d4'], background: '#ffffff', text: '#111111', muted: '#666666', grid: '#ebebeb', gridLines: false, font: 'mono', radius: 0 },
54
+ { id: 'night', name: 'Night', colors: ['#7cc4ff', '#ffb86b', '#7ee2a8', '#ff7a90', '#c4a7ff', '#5ee0e0', '#ffd866', '#a0a8b8'], background: '#15181e', text: '#eef1f6', muted: '#9aa3b2', grid: '#2a2f39', gridLines: true, font: 'sans', radius: 2 },
55
+ ];
56
+ export const DEFAULT_STYLE = BUILTIN_STYLES[0]!;
57
+
58
+ const HEX = /^#[0-9a-f]{6}$/i;
59
+ /** A style read from a file, every field checked; anything missing or wrong falls back to Default's. */
60
+ export function cleanStyle(v: unknown): ChartStyle | null {
61
+ if (!v || typeof v !== 'object') return null;
62
+ const o = v as Record<string, unknown>;
63
+ if (typeof o.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,40}$/.test(o.id)) return null;
64
+ const hex = (x: unknown, d: string) => (typeof x === 'string' && HEX.test(x) ? x.toLowerCase() : d);
65
+ const colors = Array.isArray(o.colors) ? o.colors.filter((c): c is string => typeof c === 'string' && HEX.test(c)).slice(0, 12) : [];
66
+ const d = DEFAULT_STYLE;
67
+ return {
68
+ id: o.id,
69
+ name: typeof o.name === 'string' && o.name.trim() ? o.name.trim().slice(0, 40) : o.id,
70
+ colors: colors.length ? colors.map((c) => c.toLowerCase()) : d.colors,
71
+ background: hex(o.background, d.background),
72
+ text: hex(o.text, d.text),
73
+ muted: hex(o.muted, d.muted),
74
+ grid: hex(o.grid, d.grid),
75
+ gridLines: o.gridLines !== false,
76
+ font: typeof o.font === 'string' && o.font in CHART_FONTS ? (o.font as ChartStyle['font']) : 'sans',
77
+ radius: typeof o.radius === 'number' && Number.isFinite(o.radius) ? Math.max(0, Math.min(8, Math.round(o.radius))) : d.radius,
78
+ };
79
+ }
80
+
81
+ /** The style a chart names, among the workspace's own and the built-in ones; Default when it is gone. */
82
+ export function findStyle(id: string | undefined, own: ChartStyle[] = []): ChartStyle {
83
+ return own.find((s) => s.id === id) ?? BUILTIN_STYLES.find((s) => s.id === id) ?? DEFAULT_STYLE;
84
+ }
85
+
18
86
  const text = (v: Scalar) => (v === null ? '' : v instanceof CellError ? v.code : typeof v === 'number' ? formatValue(v, '').text : String(v));
19
87
 
20
88
  /**
@@ -69,92 +137,209 @@ function tickFormat(ticks: number[]): (n: number) => string {
69
137
  }
70
138
  const esc = (s: string) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
71
139
 
72
- export function chartSvg(spec: ChartSpec, data: ChartData, w: number, h: number): string {
140
+ export function chartSvg(spec: ChartSpec, data: ChartData, w: number, h: number, style: ChartStyle = DEFAULT_STYLE): string {
141
+ const type = spec.type;
142
+ const round = type === 'pie' || type === 'doughnut';
143
+ const scatter = type === 'scatter';
144
+ // Scatter reads its first numeric column as x: the series are the rest.
145
+ const xs = scatter && data.series.length > 1 ? data.series[0]!.values : null;
146
+ const series = xs ? data.series.slice(1) : data.series;
73
147
  const titleH = spec.title ? 26 : 8;
74
- const legendH = data.series.length > 1 || spec.type === 'pie' ? 22 : 0;
148
+ const legendH = series.length > 1 || round ? 22 : 0;
75
149
  const title = spec.title ? `<text x="${w / 2}" y="18" text-anchor="middle" class="c-title">${esc(spec.title)}</text>` : '';
76
- const empty = !data.series.length || data.series.every((s) => s.values.every((v) => v === null));
77
- if (empty) return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}<text x="${w / 2}" y="${h / 2}" text-anchor="middle" class="c-muted">—</text></svg>`;
150
+ const svg = (body: string) => `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${body}</svg>`;
151
+ const color = (i: number) => style.colors[i % style.colors.length]!;
152
+ const empty = !series.length || series.every((s) => s.values.every((v) => v === null));
153
+ if (empty) return svg(`<text x="${w / 2}" y="${h / 2}" text-anchor="middle" class="c-muted">—</text>`);
154
+ const tip = (name: string, cat: string, v: string) => `<title>${esc(name)}${cat ? ` · ${esc(cat)}` : ''}: ${esc(v)}</title>`;
78
155
 
79
- if (spec.type === 'pie') {
80
- const s = data.series[0]!;
156
+ if (round) {
157
+ const s = series[0]!;
81
158
  const items = s.values.map((v, i) => ({ v: Math.max(0, v ?? 0), name: data.categories[i] ?? '' })).filter((x) => x.v > 0);
82
159
  const total = items.reduce((a, b) => a + b.v, 0);
83
160
  const r = Math.max(10, Math.min(w, h - titleH - legendH) / 2 - 10);
161
+ const inner = type === 'doughnut' ? r * 0.58 : 0;
84
162
  const cx = w / 2;
85
163
  const cy = titleH + (h - titleH - legendH) / 2;
86
164
  let angle = -Math.PI / 2;
165
+ const at = (rad: number, a: number) => `${cx + rad * Math.cos(a)},${cy + rad * Math.sin(a)}`;
87
166
  const slices = items
88
167
  .map((it, i) => {
89
168
  const a = (it.v / total) * Math.PI * 2;
90
- const x0 = cx + r * Math.cos(angle);
91
- const y0 = cy + r * Math.sin(angle);
169
+ const a0 = angle;
92
170
  angle += a;
93
- const x1 = cx + r * Math.cos(angle);
94
- const y1 = cy + r * Math.sin(angle);
95
- const path = items.length === 1 ? `M${cx - r},${cy}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0` : `M${cx},${cy}L${x0},${y0}A${r},${r} 0 ${a > Math.PI ? 1 : 0},1 ${x1},${y1}Z`;
96
- return `<path d="${path}" fill="${PALETTE[i % PALETTE.length]}" stroke="var(--sheet)" stroke-width="2"><title>${esc(it.name)}: ${esc(formatValue(it.v, '#,##0.##').text.replace(/\.$/, ''))} (${Math.round((it.v / total) * 100)}%)</title></path>`;
171
+ const large = a > Math.PI ? 1 : 0;
172
+ let path: string;
173
+ if (items.length === 1) {
174
+ path = `M${cx - r},${cy}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0` + (inner ? `M${cx - inner},${cy}a${inner},${inner} 0 1,1 ${2 * inner},0a${inner},${inner} 0 1,1 ${-2 * inner},0` : '');
175
+ } else if (inner) {
176
+ path = `M${at(r, a0)}A${r},${r} 0 ${large},1 ${at(r, angle)}L${at(inner, angle)}A${inner},${inner} 0 ${large},0 ${at(inner, a0)}Z`;
177
+ } else path = `M${cx},${cy}L${at(r, a0)}A${r},${r} 0 ${large},1 ${at(r, angle)}Z`;
178
+ return `<path d="${path}" fill="${color(i)}" fill-rule="evenodd" stroke="var(--sheet)" stroke-width="2">${tip(it.name, '', `${formatValue(it.v, '#,##0.##').text.replace(/\.$/, '')} (${Math.round((it.v / total) * 100)}%)`)}</path>`;
97
179
  })
98
180
  .join('');
99
- return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${slices}${legend(items.map((it) => it.name), w, h)}</svg>`;
181
+ const centre = inner ? `<text x="${cx}" y="${cy + 6}" text-anchor="middle" class="c-total">${esc(tickFormat([total])(total))}</text>` : '';
182
+ return svg(`${slices}${centre}${legend(items.map((it) => it.name), w, h, color)}`);
100
183
  }
101
184
 
102
- const padL = 44;
103
- const padR = 12;
185
+ const horizontal = type === 'barH';
186
+ const combo = type === 'combo' && series.length > 1;
187
+ const left = combo ? series.slice(0, 1) : series;
188
+ const right = combo ? series.slice(1) : [];
189
+ const n = data.categories.length;
190
+ const nums = (list: typeof series) => list.flatMap((s) => s.values.filter((v): v is number => v !== null));
191
+ // Stacked columns reach the sum of each category, above and below zero.
192
+ const stackExtent = () => {
193
+ let lo = 0;
194
+ let hi = 0;
195
+ for (let i = 0; i < n; i++) {
196
+ const pos = series.reduce((a, s) => a + Math.max(0, s.values[i] ?? 0), 0);
197
+ const neg = series.reduce((a, s) => a + Math.min(0, s.values[i] ?? 0), 0);
198
+ hi = Math.max(hi, pos);
199
+ lo = Math.min(lo, neg);
200
+ }
201
+ return [lo, hi];
202
+ };
203
+ const [vLo, vHi] = type === 'stacked' ? stackExtent() : [Math.min(0, ...nums(left)), Math.max(0, ...nums(left))];
204
+ const ticks = scatter ? niceTicks(Math.min(...nums(series)), Math.max(...nums(series))) : niceTicks(vLo!, vHi!);
205
+ const fmt = tickFormat(ticks);
206
+ const lo = ticks[0]!;
207
+ const hi = ticks[ticks.length - 1]!;
208
+ const ticks2 = combo ? niceTicks(Math.min(0, ...nums(right)), Math.max(0, ...nums(right))) : [];
209
+ const fmt2 = combo ? tickFormat(ticks2) : fmt;
210
+
211
+ // Horizontal bars: categories down the left, values along the bottom.
212
+ if (horizontal) {
213
+ const labelW = Math.min(140, Math.max(40, ...data.categories.map((c) => textWidth(c) + 10)));
214
+ const padL = labelW + 6;
215
+ const padR = 16;
216
+ const top = titleH + 6;
217
+ const bottom = h - legendH - 22;
218
+ const plotW = Math.max(10, w - padL - padR);
219
+ const band = (bottom - top) / Math.max(1, n);
220
+ const x = (v: number) => padL + ((v - lo) / (hi - lo)) * plotW;
221
+ const k = series.length;
222
+ const barH = Math.min(22, (band * 0.72) / k);
223
+ const grid = ticks.map((t) => `<line x1="${x(t)}" x2="${x(t)}" y1="${top}" y2="${bottom}" class="c-grid"/><text x="${x(t)}" y="${bottom + 15}" text-anchor="middle" class="c-tick">${esc(fmt(t))}</text>`).join('');
224
+ const labels = data.categories.map((c, i) => `<text x="${padL - 8}" y="${top + band * (i + 0.5) + 4}" text-anchor="end" class="c-tick">${esc(c.length > 16 ? `${c.slice(0, 15)}…` : c)}</text>`).join('');
225
+ let marks = '';
226
+ series.forEach((s, si) =>
227
+ s.values.forEach((v, i) => {
228
+ if (v === null) return;
229
+ const yy = top + band * i + band / 2 - (barH * k) / 2 + si * barH;
230
+ marks += `<rect x="${Math.min(x(0), x(v))}" y="${yy + 1}" width="${Math.max(1, Math.abs(x(v) - x(0)))}" height="${Math.max(1, barH - 2)}" rx="${style.radius}" fill="${color(si)}">${tip(s.name, data.categories[i] ?? '', fmt(v))}</rect>`;
231
+ }),
232
+ );
233
+ const axis = `<line x1="${x(0)}" x2="${x(0)}" y1="${top}" y2="${bottom}" class="c-axis"/>`;
234
+ return svg(`${grid}${axis}${marks}${labels}${legendH ? legend(series.map((s) => s.name), w, h, color) : ''}`);
235
+ }
236
+
237
+ const padL = 46;
238
+ const padR = combo ? 46 : 14;
104
239
  const top = titleH + 4;
105
240
  const bottom = h - legendH - 22;
106
241
  const plotW = Math.max(10, w - padL - padR);
107
242
  const plotH = Math.max(10, bottom - top);
108
- const all = data.series.flatMap((s) => s.values.filter((v): v is number => v !== null));
109
- const ticks = niceTicks(Math.min(0, ...all), Math.max(0, ...all));
110
- const lo = ticks[0]!;
111
- const hi = ticks[ticks.length - 1]!;
112
243
  const y = (v: number) => bottom - ((v - lo) / (hi - lo)) * plotH;
113
- const fmt = tickFormat(ticks);
114
- const n = data.categories.length;
244
+ const lo2 = ticks2[0] ?? 0;
245
+ const hi2 = ticks2[ticks2.length - 1] ?? 1;
246
+ const y2 = (v: number) => bottom - ((v - lo2) / (hi2 - lo2)) * plotH;
115
247
  const band = plotW / Math.max(1, n);
116
248
  const grid = ticks.map((t) => `<line x1="${padL}" x2="${w - padR}" y1="${y(t)}" y2="${y(t)}" class="c-grid"/><text x="${padL - 6}" y="${y(t) + 4}" text-anchor="end" class="c-tick">${esc(fmt(t))}</text>`).join('');
249
+ const rightAxis = combo ? ticks2.map((t) => `<text x="${w - padR + 6}" y="${y2(t) + 4}" class="c-tick">${esc(fmt2(t))}</text>`).join('') : '';
250
+ let marks = '';
251
+ let xLabels = '';
252
+
253
+ if (scatter) {
254
+ // x is the first column when it is numbers, else the row's position.
255
+ const xv = xs ?? data.categories.map((_, i) => i + 1);
256
+ const xn = xv.filter((v): v is number => v !== null);
257
+ const xt = niceTicks(Math.min(...xn), Math.max(...xn));
258
+ const xfmt = tickFormat(xt);
259
+ const xx = (v: number) => padL + ((v - xt[0]!) / (xt[xt.length - 1]! - xt[0]!)) * plotW;
260
+ xLabels = xt.map((t) => `<line x1="${xx(t)}" x2="${xx(t)}" y1="${top}" y2="${bottom}" class="c-grid"/><text x="${xx(t)}" y="${bottom + 15}" text-anchor="middle" class="c-tick">${esc(xfmt(t))}</text>`).join('');
261
+ series.forEach((s, si) =>
262
+ s.values.forEach((v, i) => {
263
+ const xi = xv[i];
264
+ if (v === null || xi === null || xi === undefined) return;
265
+ marks += `<circle cx="${xx(xi)}" cy="${y(v)}" r="4" fill="${color(si)}" fill-opacity="0.8">${tip(s.name, xfmt(xi), fmt(v))}</circle>`;
266
+ }),
267
+ );
268
+ return svg(`${grid}${xLabels}${marks}${legendH ? legend(series.map((s) => s.name), w, h, color) : ''}`);
269
+ }
270
+
117
271
  const every = Math.max(1, Math.ceil((n * 48) / plotW));
118
- const xLabels = data.categories
272
+ xLabels = data.categories
119
273
  .map((c, i) => (i % every ? '' : `<text x="${padL + band * (i + 0.5)}" y="${bottom + 15}" text-anchor="middle" class="c-tick">${esc(c.length > 10 ? `${c.slice(0, 9)}…` : c)}</text>`))
120
274
  .join('');
121
- let marks = '';
122
- if (spec.type === 'bar') {
123
- const k = data.series.length;
124
- const barW = Math.min(24, (band * 0.72) / k);
125
- data.series.forEach((s, si) => {
275
+
276
+ const columns = (list: typeof series, offset: number) => {
277
+ const k = list.length;
278
+ const barW = Math.min(28, (band * 0.72) / k);
279
+ list.forEach((s, si) =>
126
280
  s.values.forEach((v, i) => {
127
281
  if (v === null) return;
128
282
  const x = padL + band * i + band / 2 - (barW * k) / 2 + si * barW;
129
- const y0 = y(Math.max(0, v));
130
- const hgt = Math.max(1, Math.abs(y(v) - y(0)));
131
- marks += `<rect x="${x + 1}" y="${y0}" width="${Math.max(1, barW - 2)}" height="${hgt}" rx="2" fill="${PALETTE[si % PALETTE.length]}"><title>${esc(s.name)} · ${esc(data.categories[i] ?? '')}: ${esc(fmt(v))}</title></rect>`;
132
- });
133
- });
134
- } else {
135
- data.series.forEach((s, si) => {
136
- const pts = s.values.map((v, i) => (v === null ? null : [padL + band * (i + 0.5), y(v)] as const));
283
+ marks += `<rect x="${x + 1}" y="${y(Math.max(0, v))}" width="${Math.max(1, barW - 2)}" height="${Math.max(1, Math.abs(y(v) - y(0)))}" rx="${style.radius}" fill="${color(si + offset)}">${tip(s.name, data.categories[i] ?? '', fmt(v))}</rect>`;
284
+ }),
285
+ );
286
+ };
287
+ const lines = (list: typeof series, offset: number, yy: (v: number) => number, f: (n: number) => string, fill: boolean) => {
288
+ list.forEach((s, si) => {
289
+ const c = color(si + offset);
290
+ const pts = s.values.map((v, i) => (v === null ? null : ([padL + band * (i + 0.5), yy(v)] as const)));
137
291
  const d = pts.reduce((acc, p, i) => (p ? `${acc}${acc && pts[i - 1] ? 'L' : 'M'}${p[0]},${p[1]}` : acc), '');
138
- marks += `<path d="${d}" fill="none" stroke="${PALETTE[si % PALETTE.length]}" stroke-width="2" stroke-linejoin="round"/>`;
292
+ if (fill) {
293
+ const run = pts.filter((p): p is readonly [number, number] => p !== null);
294
+ if (run.length) marks += `<path d="M${run[0]![0]},${yy(Math.max(lo, 0))}${run.map((p) => `L${p[0]},${p[1]}`).join('')}L${run[run.length - 1]![0]},${yy(Math.max(lo, 0))}Z" fill="${c}" fill-opacity="0.16"/>`;
295
+ }
296
+ marks += `<path d="${d}" fill="none" stroke="${c}" stroke-width="2" stroke-linejoin="round"/>`;
139
297
  pts.forEach((p, i) => {
140
- if (p) marks += `<circle cx="${p[0]}" cy="${p[1]}" r="3" fill="${PALETTE[si % PALETTE.length]}"><title>${esc(s.name)} · ${esc(data.categories[i] ?? '')}: ${esc(fmt(s.values[i]!))}</title></circle>`;
298
+ if (p) marks += `<circle cx="${p[0]}" cy="${p[1]}" r="3" fill="${c}">${tip(s.name, data.categories[i] ?? '', f(s.values[i]!))}</circle>`;
141
299
  });
142
300
  });
143
- }
144
- const zero = `<line x1="${padL}" x2="${w - padR}" y1="${y(0)}" y2="${y(0)}" class="c-axis"/>`;
145
- return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${grid}${zero}${marks}${xLabels}${legendH ? legend(data.series.map((s) => s.name), w, h) : ''}</svg>`;
301
+ };
302
+
303
+ if (type === 'bar') columns(series, 0);
304
+ else if (type === 'stacked') {
305
+ const k = 1;
306
+ const barW = Math.min(36, band * 0.62 * k);
307
+ for (let i = 0; i < n; i++) {
308
+ let pos = 0;
309
+ let neg = 0;
310
+ series.forEach((s, si) => {
311
+ const v = s.values[i];
312
+ if (v === null || v === undefined || v === 0) return;
313
+ const from = v > 0 ? pos : neg;
314
+ const to = from + v;
315
+ if (v > 0) pos = to;
316
+ else neg = to;
317
+ const x = padL + band * (i + 0.5) - barW / 2;
318
+ marks += `<rect x="${x}" y="${Math.min(y(from), y(to))}" width="${barW}" height="${Math.max(1, Math.abs(y(to) - y(from)))}" fill="${color(si)}">${tip(s.name, data.categories[i] ?? '', fmt(v))}</rect>`;
319
+ });
320
+ }
321
+ } else if (type === 'combo') {
322
+ columns(left, 0);
323
+ lines(right, 1, combo ? y2 : y, fmt2, false);
324
+ } else lines(series, 0, y, fmt, type === 'area');
325
+
326
+ const zero = `<line x1="${padL}" x2="${w - padR}" y1="${y(Math.max(lo, Math.min(0, hi)))}" y2="${y(Math.max(lo, Math.min(0, hi)))}" class="c-axis"/>`;
327
+ return svg(`${grid}${rightAxis}${zero}${marks}${xLabels}${legendH ? legend(series.map((s) => s.name), w, h, color) : ''}`);
328
+ }
329
+
330
+ /** Wide (CJK) characters take about twice the room of Latin ones at 11px. */
331
+ function textWidth(n: string): number {
332
+ return [...n.slice(0, 16)].reduce((w, ch) => w + (/[ᄀ-ᇿ⺀-꓏가-힯豈-﫿＀-￯]/.test(ch) ? 11.5 : 6.5), 0);
146
333
  }
147
334
 
148
- function legend(names: string[], w: number, h: number): string {
335
+ function legend(names: string[], w: number, h: number, color: (i: number) => string): string {
149
336
  const items = names.slice(0, 8);
150
- // Wide (CJK) characters take about twice the room of Latin ones at 11px.
151
- const textWidth = (n: string) => [...n.slice(0, 14)].reduce((w, ch) => w + (/[\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/.test(ch) ? 11.5 : 6.5), 0);
152
337
  const widths = items.map((n) => 26 + textWidth(n));
153
338
  const total = widths.reduce((a, b) => a + b, 0);
154
339
  let x = Math.max(4, (w - total) / 2);
155
340
  return items
156
341
  .map((name, i) => {
157
- const out = `<rect x="${x}" y="${h - 15}" width="9" height="9" rx="2" fill="${PALETTE[i % PALETTE.length]}"/><text x="${x + 13}" y="${h - 7}" class="c-tick">${esc(name.length > 14 ? `${name.slice(0, 13)}…` : name)}</text>`;
342
+ const out = `<rect x="${x}" y="${h - 15}" width="9" height="9" rx="2" fill="${color(i)}"/><text x="${x + 13}" y="${h - 7}" class="c-tick">${esc(name.length > 14 ? `${name.slice(0, 13)}…` : name)}</text>`;
158
343
  x += widths[i]!;
159
344
  return out;
160
345
  })
@@ -166,13 +351,34 @@ function legend(names: string[], w: number, h: number): string {
166
351
  * program: the SVG with its namespace, a white background and the colours the
167
352
  * page would give it written in, since no stylesheet comes with it.
168
353
  */
169
- export function chartFile(spec: ChartSpec, data: ChartData, w = 720, h = 405): string {
170
- const style =
171
- '<style>text{font-family:-apple-system,BlinkMacSystemFont,"PingFang TC","Noto Sans TC","Segoe UI",sans-serif}' +
172
- '.c-title{font-weight:600;font-size:13px;fill:#1f1f1f}.c-tick{font-size:11px;fill:#5f6368}.c-muted{font-size:14px;fill:#5f6368}' +
173
- '.c-grid{stroke:#e8eaed;stroke-width:1}.c-axis{stroke:#9aa0a6;stroke-width:1}</style>';
174
- return chartSvg(spec, data, w, h)
354
+ export interface ChartSource {
355
+ sheet: string;
356
+ range: string;
357
+ type: ChartSpec['type'];
358
+ title?: string;
359
+ /** A chart style's id; Default when absent. */
360
+ style?: string;
361
+ }
362
+
363
+ /** Where a chart file was drawn from, read back from its <metadata>; null for any other SVG. */
364
+ export function chartSourceOf(svg: string): ChartSource | null {
365
+ const m = /<metadata id="open-spreadsheet-chart">([^<]*)<\/metadata>/.exec(svg);
366
+ if (!m) return null;
367
+ try {
368
+ const v = JSON.parse(m[1]!.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&amp;', '&')) as ChartSource;
369
+ return typeof v.sheet === 'string' && typeof v.range === 'string' && CHART_TYPES.includes(v.type) ? v : null;
370
+ } catch {
371
+ return null;
372
+ }
373
+ }
374
+
375
+ export function chartFile(spec: ChartSpec, data: ChartData, w = 720, h = 405, source?: ChartSource, look: ChartStyle = DEFAULT_STYLE): string {
376
+ const css =
377
+ `<style>text{font-family:${CHART_FONTS[look.font]}}` +
378
+ `.c-title{font-weight:600;font-size:13px;fill:${look.text}}.c-tick{font-size:11px;fill:${look.muted}}.c-muted{font-size:14px;fill:${look.muted}}` +
379
+ `.c-grid{stroke:${look.gridLines ? look.grid : 'none'};stroke-width:1}.c-axis{stroke:${look.muted};stroke-opacity:.6;stroke-width:1}.c-total{font-weight:650;font-size:22px;fill:${look.text}}</style>`;
380
+ return chartSvg(spec, data, w, h, look)
175
381
  .replace(/^<svg /, '<svg xmlns="http://www.w3.org/2000/svg" ')
176
- .replace('>', `>${style}<rect width="100%" height="100%" fill="#ffffff"/>`)
177
- .replaceAll('var(--sheet)', '#ffffff');
382
+ .replace('>', `>${source ? `<metadata id="open-spreadsheet-chart">${esc(JSON.stringify(source))}</metadata>` : ''}${css}<rect width="100%" height="100%" fill="${look.background}"/>`)
383
+ .replaceAll('var(--sheet)', look.background);
178
384
  }