@open-spreadsheet/core 0.3.0 → 0.4.1

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/dist/charts.js 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, } from '@open-spreadsheet/engine';
7
-
8
+
9
+
10
+ export const CHART_TYPES = ['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'];
8
11
 
9
12
 
10
13
 
@@ -15,6 +18,71 @@ import { CellError, formatValue, } from '@open-spreadsheet/engine';
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
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+  
38
+
39
+
40
+
41
+ export const CHART_FONTS = {
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 = [
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 ) {
61
+ if (!v || typeof v !== 'object') return null;
62
+ const o = v ;
63
+ if (typeof o.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,40}$/.test(o.id)) return null;
64
+ const hex = (x , d ) => (typeof x === 'string' && HEX.test(x) ? x.toLowerCase() : d);
65
+ const colors = Array.isArray(o.colors) ? o.colors.filter((c) => 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 ) : '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 , own = []) {
83
+ return own.find((s) => s.id === id) ?? BUILTIN_STYLES.find((s) => s.id === id) ?? DEFAULT_STYLE;
84
+ }
85
+
18
86
  const text = (v ) => (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 ) {
69
137
  }
70
138
  const esc = (s ) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
71
139
 
72
- export function chartSvg(spec , data , w , h ) {
140
+ export function chartSvg(spec , data , w , h , style = DEFAULT_STYLE) {
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 ) => `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${body}</svg>`;
151
+ const color = (i ) => 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 , cat , v ) => `<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 , a ) => `${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 ;
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 ) => list.flatMap((s) => s.values.filter((v) => 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 ) => 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 !== 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 ) => 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 ) => 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 !== null);
257
+ const xt = niceTicks(Math.min(...xn), Math.max(...xn));
258
+ const xfmt = tickFormat(xt);
259
+ const xx = (v ) => 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 , offset ) => {
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)] ));
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 , offset , yy , f , fill ) => {
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)] )));
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 !== 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 ) {
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 , w , h ) {
335
+ function legend(names , w , h , color ) {
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 ) => [...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 , w , h ) {
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 , data , w = 720, h = 405) {
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
+
355
+
356
+
357
+
358
+
359
+
360
+
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 ) {
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;', '&')) ;
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 , data , w = 720, h = 405, source , look = DEFAULT_STYLE) {
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
  }
package/mcp.js CHANGED
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * Speaks JSON-RPC 2.0, one message per line, with no dependencies.
12
12
  */
13
- import { assetsDir, listAssets, readAsset, renderChart, trashAsset, writeNote } from './assets.js';
13
+ import { assetsDir, listAssets, readAsset, readChartStyles, renameAsset, renderChart, trashAsset, writeChartStyles, writeNote } from './assets.js';
14
14
  import { existsSync, cpSync } from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import { createInterface } from 'node:readline';
@@ -142,15 +142,39 @@ const TOOLS = [
142
142
  workbook: str,
143
143
  sheet: str,
144
144
  range: { ...str, description: 'e.g. A1:C13' },
145
- type: { type: 'string', enum: ['bar', 'line', 'pie'] },
145
+ type: { type: 'string', enum: ['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'], description: 'bar (columns), barH (horizontal bars), stacked, line, area, pie, doughnut, scatter (first column is x), combo (first series columns, the rest lines on a right axis)' },
146
146
  title: str,
147
147
  name: { ...str, description: 'file name; from the title when omitted' },
148
148
  scope: { ...str, description: 'where to save: the workbook (default) or "shared"' },
149
149
  replace: { type: 'boolean', description: 'overwrite an image of that name instead of numbering a new one' },
150
+ style: { ...str, description: 'a chart style id from list_chart_styles; omitted, the chart follows the workspace default' },
150
151
  },
151
152
  required: ['workbook', 'range'],
152
153
  },
153
154
  },
155
+ {
156
+ name: 'list_chart_styles',
157
+ description: 'The chart styles charts can be drawn in: the built-in ones, the workspace\'s own (assets/chart-styles.json) and which one is the default.',
158
+ inputSchema: { type: 'object', properties: {} },
159
+ },
160
+ {
161
+ name: 'save_chart_style',
162
+ description:
163
+ 'Add or change one of the workspace\'s chart styles (a house style, e.g. from brand colours): { id, name, colors: [hex…], background, text, muted, grid, gridLines, font: sans|serif|mono|rounded, radius 0–8 }. Charts that use it are redrawn the next time they are shown.',
164
+ inputSchema: {
165
+ type: 'object',
166
+ properties: {
167
+ style: { type: 'object', description: 'the style; id is lowercase letters, numbers and dashes' },
168
+ make_default: { type: 'boolean', description: 'new charts follow it' },
169
+ },
170
+ required: ['style'],
171
+ },
172
+ },
173
+ {
174
+ name: 'rename_asset',
175
+ description: 'Rename an image or note in its folder (same ending: .svg stays .svg). To retitle a chart drawn by render_chart, render it again with the new title and replace: true, then rename.',
176
+ inputSchema: { type: 'object', properties: { scope: str, name: str, to: { ...str, description: 'the new file name' } }, required: ['scope', 'name', 'to'] },
177
+ },
154
178
  {
155
179
  name: 'delete_asset',
156
180
  description: 'Move an image or note to its folder\'s .trash (nothing is erased). Only when the person asked.',
@@ -450,6 +474,19 @@ async function callTool(root, name, a) {
450
474
  return writeNote(root, a.scope, a.name, a.text);
451
475
  case 'render_chart':
452
476
  return renderChart(root, a.workbook, a);
477
+ case 'list_chart_styles': {
478
+ const { BUILTIN_STYLES } = await import(new URL(import.meta.url.includes('/node_modules/') ? './dist/charts.js' : './app/charts.ts', import.meta.url).href);
479
+ const own = await readChartStyles(root);
480
+ return { default: own.default, builtin: BUILTIN_STYLES, styles: own.styles };
481
+ }
482
+ case 'save_chart_style': {
483
+ const own = await readChartStyles(root);
484
+ const id = a.style?.id;
485
+ const styles = own.styles.some((s) => s.id === id) ? own.styles.map((s) => (s.id === id ? a.style : s)) : [...own.styles, a.style];
486
+ return writeChartStyles(root, { default: a.make_default ? id : own.default, styles });
487
+ }
488
+ case 'rename_asset':
489
+ return renameAsset(root, a.scope, a.name, a.to);
453
490
  case 'delete_asset':
454
491
  return trashAsset(root, a.scope, a.name);
455
492
  case 'rename_workbook': {
package/ops.js CHANGED
@@ -285,7 +285,7 @@ export function checkWorkbook(data) {
285
285
  if (!Array.isArray(v.list) || !v.list.length) add('error', s.name, v.range ?? '', 'A validation rule needs a non-empty list of allowed values.');
286
286
  }
287
287
  for (const ch of s.charts ?? []) {
288
- if (!['bar', 'line', 'pie'].includes(ch.type)) add('error', s.name, ch.id ?? '', `Unknown chart type "${ch.type}" (bar, line or pie).`);
288
+ if (!['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'].includes(ch.type)) add('error', s.name, ch.id ?? '', `Unknown chart type "${ch.type}".`);
289
289
  if (!parseRange(ch.range ?? '')) add('error', s.name, ch.id ?? '', 'A chart needs a data range like A1:C13.');
290
290
  if (![ch.x, ch.y, ch.w, ch.h].every((n) => typeof n === 'number' && n >= 0)) add('error', s.name, ch.id ?? '', 'A chart needs x, y, w and h in pixels.');
291
291
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-spreadsheet/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "open-spreadsheet: an Excel-like spreadsheet for agents and people. The dev server, the grid editor and the CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { assetPath, assetsDir, listAssets, MIME, readAsset, renderChart, saveImage, SHARED, trashAsset, writeNote } from './assets.js';
4
+ import { assetPath, assetsDir, listAssets, MIME, readAsset, readChartStyles, readFavorites, renameAsset, renderChart, saveImage, setFavorite, SHARED, trashAsset, writeChartStyles, writeNote } from './assets.js';
5
5
  import { currentFile, hashOf, ID, listWorkbooks, OpsError, readWorkbook, trashWorkbook, workbookFile, writeWorkbook } from './ops.js';
6
6
 
7
7
  const CORE = path.dirname(fileURLToPath(import.meta.url));
@@ -55,7 +55,7 @@ export function initWorkspace(dir) {
55
55
  path.join(root, 'assets', 'README.md'),
56
56
  '# Shared notes\n\nMarkdown notes here are context for every workbook in this workspace: what the numbers mean, where they come from, conventions to keep. Agents read them before they work. Images here are shared too.\n',
57
57
  );
58
- writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n**/assets/.trash\n');
58
+ writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n**/assets/.trash\n# your own picks, such as favourite notes\n.open-spreadsheet/\n');
59
59
  const agents = readFileSync(path.join(CORE, 'templates', 'AGENTS.md'), 'utf8');
60
60
  writeFileSync(path.join(root, 'AGENTS.md'), agents);
61
61
  writeFileSync(path.join(root, 'CLAUDE.md'), agents);
@@ -120,7 +120,7 @@ function allowedWrite(req) {
120
120
  }
121
121
  }
122
122
 
123
- const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412, bad_name: 400, bad_range: 400, bad_type: 400, no_sheet: 404, too_big: 413 };
123
+ const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412, bad_name: 400, bad_range: 400, bad_type: 400, no_sheet: 404, too_big: 413, bad_style: 400 };
124
124
 
125
125
  /** A request body as bytes, for image uploads; refused past `max`. */
126
126
  const readBytes = (req, max = 15_000_000) =>
@@ -216,6 +216,19 @@ function apiPlugin(root) {
216
216
  if (fromAssets && existsSync(fromAssets)) cpSync(fromAssets, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
217
217
  return json(res, 201, { id });
218
218
  }
219
+ if (url.pathname === '/__api/chart-styles') {
220
+ if (req.method === 'GET') return json(res, 200, await readChartStyles(root));
221
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
222
+ if (req.method === 'PUT') return json(res, 200, await writeChartStyles(root, JSON.parse(await readBody(req))));
223
+ }
224
+ if (url.pathname === '/__api/favorites') {
225
+ if (req.method === 'GET') return json(res, 200, { favorites: readFavorites(root) });
226
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
227
+ if (req.method === 'PUT') {
228
+ const b = JSON.parse(await readBody(req));
229
+ return json(res, 200, { favorites: setFavorite(root, b.scope, b.name, Boolean(b.on)) });
230
+ }
231
+ }
219
232
  // ---------- assets ----------
220
233
  if (url.pathname.startsWith('/__api/assets')) {
221
234
  const scope = url.searchParams.get('scope') ?? '';
@@ -241,12 +254,13 @@ function apiPlugin(root) {
241
254
  }
242
255
  if (url.pathname === '/__api/assets/upload' && req.method === 'POST') {
243
256
  assetPath(root, scope, name);
244
- return json(res, 201, saveImage(root, scope, name, await readBytes(req)));
257
+ return json(res, 201, saveImage(root, scope, name, await readBytes(req), { replace: url.searchParams.get('replace') === '1' }));
245
258
  }
246
259
  if (url.pathname === '/__api/assets/chart' && req.method === 'POST') {
247
260
  const b = JSON.parse(await readBody(req));
248
261
  return json(res, 201, await renderChart(root, b.workbook, b));
249
262
  }
263
+ if (url.pathname === '/__api/assets/rename' && req.method === 'POST') return json(res, 200, renameAsset(root, scope, name, url.searchParams.get('to') ?? ''));
250
264
  if (url.pathname === '/__api/assets' && req.method === 'DELETE') return json(res, 200, trashAsset(root, scope, name));
251
265
  return json(res, 404, { error: 'not found' });
252
266
  }
@@ -14,7 +14,7 @@ People leave notes on cells in the editor (right-click → Add note, or ⇧F2).
14
14
  1. **Find them.** With the MCP server, call `list_notes` (all workbooks, or one). Otherwise read the `notes` of every sheet in `sheets/*/workbook.json`.
15
15
  2. **Sort them.** A note that asks for something ("make this a percentage", "add a total under this column", "this should use the March numbers") is a request. A note that only explains ("source: 2025 annual report") is documentation: leave it.
16
16
  3. **Do each request** on the cell the note is on and whatever it names — cells, formulas, styles, formats, layout — following the `sheet-authoring` skill. Keep totals as formulas.
17
- - **A note asking for a chart or a picture** ("make a bar chart of this", "chart sales by month") gets an image in the workbook's Assets, never a chart on the grid: call `render_chart` with the range the note is about (its data, header row and first column included) and a title from the note. Say the file name in your report.
17
+ - **A note asking for a chart or a picture** ("make a bar chart of this", "chart sales by month") gets an image in the workbook's Assets, never a chart on the grid: call `render_chart` with the range the note is about (its data, header row and first column included) and a title from the note. If the request sits in a note, put the chart in it with `![title](file.svg)` (the path from the note). Say the file name in your report.
18
18
  - **A note to remember** ("these figures are in thousands", "source: 2025 report") can go into a Markdown note in Assets with `write_note`, then the cell note is done.
19
19
  4. **Remove each note you carried out** (`set_note` with empty `text`, or delete the key from `notes`). If a request is unclear or impossible, leave the note and say why.
20
20
  5. **Check.** Run `open-spreadsheet check` (or the `check` tool) and fix what it reports.
@@ -79,7 +79,7 @@ Math and trigonometry (SUM, SUMIF(S), SUMPRODUCT, SUBTOTAL, ROUND/ROUNDUP/ROUNDD
79
79
 
80
80
  Each workbook has an assets folder, `sheets/<id>/assets/`, and the workspace has a shared one, `assets/`. They hold:
81
81
 
82
- - **Chart images.** Charts are never placed on the grid. Draw one from a range with the MCP `render_chart` tool (`workbook`, `sheet`, `range`, `type` = `bar` | `line` | `pie`, `title`); it saves an SVG in the workbook's assets, the same picture the editor makes. The range's first column holds the categories and its first row the series names.
82
+ - **Chart images.** Charts are never placed on the grid. Draw one from a range with the MCP `render_chart` tool (`workbook`, `sheet`, `range`, `type`, `title`); it saves an SVG in the workbook's assets, the same picture the editor makes, and the editor redraws it whenever the numbers change. The range's first column holds the categories and its first row the series names. Types: `bar` (columns), `barH` (horizontal bars, for long names or rankings), `stacked` (a total and its parts), `line` (a trend), `area` (a trend with its volume), `pie` / `doughnut` (shares; the doughnut shows the total), `scatter` (two numbers against each other; the first column is x), `combo` (the first series as columns, the rest as lines on a right-hand axis — amounts with a rate). Charts take a **style** (`style`: a built-in one — `default`, `ocean`, `warm`, `pastel`, `mono`, `night` — or the workspace's own); leave it out and the chart follows the workspace default. `list_chart_styles` shows them; `save_chart_style` adds a house style (e.g. from brand colours) to `assets/chart-styles.json`.
83
83
  - **Notes (`.md`).** What people know about the numbers: sources, meanings, rules to keep. **Read the notes before you change a workbook** (`list_assets` then `read_asset`, or the files themselves), for that workbook and for `shared`. Write what you found or decided with `write_note` when it will help next time.
84
84
 
85
85
  Without MCP, read and write the files directly. Never put an image or note anywhere else, and never name one with a folder in it.
@@ -45,7 +45,7 @@ npx open-spreadsheet export <id> --range A1:F200 --out data.csv # computed val
45
45
  - Sizes are pixels: `cols` by letter, `rows` by 1-based row number.
46
46
  - **Defined names** sit at the top level: `"names": { "Sales": "Orders!$F$2:$F$200" }`, then `=SUM(Sales)`.
47
47
  - **Conditional formats, dropdown lists and filters** live beside the cells too (`conditional`, `validation`, `filter`); see the `sheet-authoring` skill.
48
- - **Assets** sit beside each workbook in `sheets/<id>/assets/` (and shared in `assets/`): chart images and Markdown notes. **Read a workbook's notes and the shared ones before you change it** — they say what the numbers mean and what to keep. Charts are never on the grid: make one with the MCP `render_chart` tool (an SVG in Assets). Keep what you learn with `write_note`.
48
+ - **Assets** sit beside each workbook in `sheets/<id>/assets/` (and shared in `assets/`): chart images and Markdown notes. **Read a workbook's notes and the shared ones before you change it** — they say what the numbers mean and what to keep. Charts are never on the grid: make one with the MCP `render_chart` tool (an SVG in Assets), in the workspace's chart style unless asked for another (`list_chart_styles`). Keep what you learn with `write_note`. A note shows an asset with a Markdown image by its path from the note: `![Sales](sales.svg)` beside it, `../../../assets/x.svg` for a shared one.
49
49
  - **Protected ranges** (`"protected": ["A1:D1"]` on a sheet) are cells a person locked. Do not change them, by MCP or by editing the JSON; if a task needs them changed, ask the person to unprotect them in the editor.
50
50
  - **Notes** are comments people leave on cells, often requests for you. "Apply the notes" means: do what each asks, then remove it (the `apply-notes` skill).
51
51