@open-spreadsheet/core 0.2.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/assets.ts +1479 -0
- package/app/book.ts +115 -24
- package/app/charts.test.ts +62 -1
- package/app/charts.ts +268 -46
- package/app/i18n-more.ts +230 -2
- package/app/i18n.ts +154 -2
- package/app/icons.ts +5 -0
- package/app/markdown.test.ts +25 -0
- package/app/markdown.ts +150 -0
- package/app/note-editor.ts +252 -0
- package/app/style.css +154 -0
- package/app/types.ts +3 -1
- package/assets.js +232 -0
- package/dist/charts.js +384 -0
- package/mcp.js +97 -5
- package/ops.js +6 -1
- package/package.json +6 -3
- package/server.js +81 -2
- package/skills/apply-notes/SKILL.md +3 -1
- package/skills/sheet-authoring/SKILL.md +11 -1
- package/templates/AGENTS.md +1 -0
package/dist/charts.js
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
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,
|
|
4
|
+
* like open-dashboard's: one y-axis, zero in the domain, a fixed categorical
|
|
5
|
+
* palette, ticks from one formatter, text in ink colours.
|
|
6
|
+
*/
|
|
7
|
+
import { CellError, formatValue, } from '@open-spreadsheet/engine';
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
export const CHART_TYPES = ['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'];
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
export const PALETTE = ['#2a78d6', '#e8710a', '#1e8e3e', '#d93025', '#9334e6', '#12b5cb', '#c5221f', '#7f6000'];
|
|
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
|
+
|
|
86
|
+
const text = (v ) => (v === null ? '' : v instanceof CellError ? v.code : typeof v === 'number' ? formatValue(v, '').text : String(v));
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Reads a block of cells the way Excel's chart wizard does: if the top-left
|
|
90
|
+
* cell is empty or the first column is text, the first column holds the
|
|
91
|
+
* categories; a first row of text holds the series names.
|
|
92
|
+
*/
|
|
93
|
+
/** Whether a block's first row holds series names and its first column categories. */
|
|
94
|
+
export function chartShape(cells ) {
|
|
95
|
+
const cols = cells[0]?.length ?? 0;
|
|
96
|
+
const isText = (v ) => typeof v === 'string' && v !== '';
|
|
97
|
+
const headerRow = Boolean(cells[0]?.slice(1).some(isText)) || (cols === 1 && isText(cells[0]?.[0] ?? null));
|
|
98
|
+
const labelCol = cols > 1 && cells.slice(headerRow ? 1 : 0).some((r) => typeof r[0] !== 'number');
|
|
99
|
+
return { headerRow, labelCol };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function chartData(cells ) {
|
|
103
|
+
if (!cells.length || !cells[0]?.length) return { categories: [], series: [] };
|
|
104
|
+
const cols = cells[0] .length;
|
|
105
|
+
const { headerRow, labelCol } = chartShape(cells);
|
|
106
|
+
const r0 = headerRow ? 1 : 0;
|
|
107
|
+
const c0 = labelCol ? 1 : 0;
|
|
108
|
+
const categories = cells.slice(r0).map((r, i) => (labelCol ? text(r[0] ?? null) : String(i + 1)));
|
|
109
|
+
const series = [];
|
|
110
|
+
for (let c = c0; c < cols; c++) {
|
|
111
|
+
series.push({
|
|
112
|
+
name: headerRow ? text(cells[0] [c] ?? null) : `Series ${c - c0 + 1}`,
|
|
113
|
+
values: cells.slice(r0).map((r) => (typeof r[c] === 'number' ? (r[c] ) : null)),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return { categories, series };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Round axis steps: 1, 2 or 5 times a power of ten. */
|
|
120
|
+
export function niceTicks(min , max , count = 5) {
|
|
121
|
+
if (min === max) max = min + 1;
|
|
122
|
+
const raw = (max - min) / count;
|
|
123
|
+
const mag = 10 ** Math.floor(Math.log10(raw));
|
|
124
|
+
const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
|
|
125
|
+
// From the step at or below the minimum to the step at or above the maximum, so every mark fits.
|
|
126
|
+
const start = Math.floor(min / step) * step;
|
|
127
|
+
const end = Math.ceil(max / step - 1e-9) * step;
|
|
128
|
+
const out = [];
|
|
129
|
+
for (let v = start; v <= end + step * 1e-9; v += step) out.push(Number.parseFloat(v.toPrecision(12)));
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
function tickFormat(ticks ) {
|
|
133
|
+
const max = Math.max(...ticks.map(Math.abs));
|
|
134
|
+
if (max >= 1e6) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e6).toPrecision(3))}M`);
|
|
135
|
+
if (max >= 1e4) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e3).toPrecision(3))}K`);
|
|
136
|
+
return (n) => formatValue(n, '#,##0.##').text.replace(/\.$/, '');
|
|
137
|
+
}
|
|
138
|
+
const esc = (s ) => s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
|
139
|
+
|
|
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;
|
|
147
|
+
const titleH = spec.title ? 26 : 8;
|
|
148
|
+
const legendH = series.length > 1 || round ? 22 : 0;
|
|
149
|
+
const title = spec.title ? `<text x="${w / 2}" y="18" text-anchor="middle" class="c-title">${esc(spec.title)}</text>` : '';
|
|
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>`;
|
|
155
|
+
|
|
156
|
+
if (round) {
|
|
157
|
+
const s = series[0] ;
|
|
158
|
+
const items = s.values.map((v, i) => ({ v: Math.max(0, v ?? 0), name: data.categories[i] ?? '' })).filter((x) => x.v > 0);
|
|
159
|
+
const total = items.reduce((a, b) => a + b.v, 0);
|
|
160
|
+
const r = Math.max(10, Math.min(w, h - titleH - legendH) / 2 - 10);
|
|
161
|
+
const inner = type === 'doughnut' ? r * 0.58 : 0;
|
|
162
|
+
const cx = w / 2;
|
|
163
|
+
const cy = titleH + (h - titleH - legendH) / 2;
|
|
164
|
+
let angle = -Math.PI / 2;
|
|
165
|
+
const at = (rad , a ) => `${cx + rad * Math.cos(a)},${cy + rad * Math.sin(a)}`;
|
|
166
|
+
const slices = items
|
|
167
|
+
.map((it, i) => {
|
|
168
|
+
const a = (it.v / total) * Math.PI * 2;
|
|
169
|
+
const a0 = angle;
|
|
170
|
+
angle += a;
|
|
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>`;
|
|
179
|
+
})
|
|
180
|
+
.join('');
|
|
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)}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
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;
|
|
239
|
+
const top = titleH + 4;
|
|
240
|
+
const bottom = h - legendH - 22;
|
|
241
|
+
const plotW = Math.max(10, w - padL - padR);
|
|
242
|
+
const plotH = Math.max(10, bottom - top);
|
|
243
|
+
const y = (v ) => bottom - ((v - lo) / (hi - lo)) * plotH;
|
|
244
|
+
const lo2 = ticks2[0] ?? 0;
|
|
245
|
+
const hi2 = ticks2[ticks2.length - 1] ?? 1;
|
|
246
|
+
const y2 = (v ) => bottom - ((v - lo2) / (hi2 - lo2)) * plotH;
|
|
247
|
+
const band = plotW / Math.max(1, n);
|
|
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
|
+
|
|
271
|
+
const every = Math.max(1, Math.ceil((n * 48) / plotW));
|
|
272
|
+
xLabels = data.categories
|
|
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>`))
|
|
274
|
+
.join('');
|
|
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) =>
|
|
280
|
+
s.values.forEach((v, i) => {
|
|
281
|
+
if (v === null) return;
|
|
282
|
+
const x = padL + band * i + band / 2 - (barW * k) / 2 + si * barW;
|
|
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)] )));
|
|
291
|
+
const d = pts.reduce((acc, p, i) => (p ? `${acc}${acc && pts[i - 1] ? 'L' : 'M'}${p[0]},${p[1]}` : acc), '');
|
|
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"/>`;
|
|
297
|
+
pts.forEach((p, i) => {
|
|
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>`;
|
|
299
|
+
});
|
|
300
|
+
});
|
|
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);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function legend(names , w , h , color ) {
|
|
336
|
+
const items = names.slice(0, 8);
|
|
337
|
+
const widths = items.map((n) => 26 + textWidth(n));
|
|
338
|
+
const total = widths.reduce((a, b) => a + b, 0);
|
|
339
|
+
let x = Math.max(4, (w - total) / 2);
|
|
340
|
+
return items
|
|
341
|
+
.map((name, i) => {
|
|
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>`;
|
|
343
|
+
x += widths[i] ;
|
|
344
|
+
return out;
|
|
345
|
+
})
|
|
346
|
+
.join('');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* A chart as a file of its own — for the Assets folder, a note or another
|
|
351
|
+
* program: the SVG with its namespace, a white background and the colours the
|
|
352
|
+
* page would give it written in, since no stylesheet comes with it.
|
|
353
|
+
*/
|
|
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('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll('&', '&')) ;
|
|
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)
|
|
381
|
+
.replace(/^<svg /, '<svg xmlns="http://www.w3.org/2000/svg" ')
|
|
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);
|
|
384
|
+
}
|
package/mcp.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
*
|
|
11
11
|
* Speaks JSON-RPC 2.0, one message per line, with no dependencies.
|
|
12
12
|
*/
|
|
13
|
-
import {
|
|
13
|
+
import { assetsDir, listAssets, readAsset, readChartStyles, renameAsset, renderChart, trashAsset, writeChartStyles, writeNote } from './assets.js';
|
|
14
|
+
import { existsSync, cpSync } from 'node:fs';
|
|
14
15
|
import path from 'node:path';
|
|
15
16
|
import { createInterface } from 'node:readline';
|
|
16
17
|
import { columnIndex, columnName, formatA1, parseA1, Workbook } from '@open-spreadsheet/engine';
|
|
@@ -94,8 +95,7 @@ const TOOLS = [
|
|
|
94
95
|
charts: {
|
|
95
96
|
type: 'array',
|
|
96
97
|
items: { type: 'object' },
|
|
97
|
-
description:
|
|
98
|
-
'Replaces the charts: [{ "id": "sales", "type": "bar"|"line"|"pie", "range": "A1:C13" (first column categories, first row series names), "title": "…", "x": 520, "y": 0, "w": 440, "h": 270 }] in px at 100% zoom',
|
|
98
|
+
description: 'Only [] is accepted: it removes charts an older workbook still has on its grid. New charts are images in Assets — use render_chart.',
|
|
99
99
|
},
|
|
100
100
|
hidden_rows: { type: 'array', items: { type: 'number' }, description: 'Replaces the rows hidden by hand (1-based numbers); [] shows them all' },
|
|
101
101
|
hidden_cols: { type: 'array', items: { type: 'string' }, description: 'Replaces the columns hidden by hand (letters); [] shows them all' },
|
|
@@ -116,6 +116,71 @@ const TOOLS = [
|
|
|
116
116
|
description: 'Create a workbook at sheets/<id>/workbook.json. sheets is optional: [{ name, cells, styles, cols, freeze }]; a blank Sheet1 otherwise.',
|
|
117
117
|
inputSchema: { type: 'object', properties: { id: { ...str, description: 'lowercase letters, numbers and dashes' }, title: str, sheets: { type: 'array', items: { type: 'object' } } }, required: ['id', 'title'] },
|
|
118
118
|
},
|
|
119
|
+
{
|
|
120
|
+
name: 'list_assets',
|
|
121
|
+
description:
|
|
122
|
+
"A workbook's images and Markdown notes (sheets/<id>/assets/), or the workspace's shared ones (scope \"shared\"). Notes are context people keep about the numbers — read them with read_asset before working on a workbook.",
|
|
123
|
+
inputSchema: { type: 'object', properties: { scope: { ...str, description: 'A workbook id, or "shared"' } }, required: ['scope'] },
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: 'read_asset',
|
|
127
|
+
description: 'The text of a Markdown note in a scope. Images are listed by list_assets; their content is not returned.',
|
|
128
|
+
inputSchema: { type: 'object', properties: { scope: str, name: { ...str, description: 'e.g. notes.md' } }, required: ['scope', 'name'] },
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: 'write_note',
|
|
132
|
+
description: 'Create or replace a Markdown note (a .md file) in a workbook\'s assets or the shared ones: explanations, sources, decisions, a summary of what you found.',
|
|
133
|
+
inputSchema: { type: 'object', properties: { scope: str, name: { ...str, description: 'ends in .md' }, text: str }, required: ['scope', 'name', 'text'] },
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
name: 'render_chart',
|
|
137
|
+
description:
|
|
138
|
+
'Draw a chart from a range and save it as an SVG image in the workbook\'s assets (or shared): first column the categories, first row the series names when they are text. Charts are not placed on the grid; they live in Assets. Use it when a note or a person asks for a chart.',
|
|
139
|
+
inputSchema: {
|
|
140
|
+
type: 'object',
|
|
141
|
+
properties: {
|
|
142
|
+
workbook: str,
|
|
143
|
+
sheet: str,
|
|
144
|
+
range: { ...str, description: 'e.g. A1:C13' },
|
|
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
|
+
title: str,
|
|
147
|
+
name: { ...str, description: 'file name; from the title when omitted' },
|
|
148
|
+
scope: { ...str, description: 'where to save: the workbook (default) or "shared"' },
|
|
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' },
|
|
151
|
+
},
|
|
152
|
+
required: ['workbook', 'range'],
|
|
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
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: 'delete_asset',
|
|
180
|
+
description: 'Move an image or note to its folder\'s .trash (nothing is erased). Only when the person asked.',
|
|
181
|
+
inputSchema: { type: 'object', properties: { scope: str, name: str }, required: ['scope', 'name'] },
|
|
182
|
+
annotations: { destructiveHint: true },
|
|
183
|
+
},
|
|
119
184
|
{
|
|
120
185
|
name: 'rename_workbook',
|
|
121
186
|
description: "Change a workbook's title (what the list shows). Its id, and so its address, stay.",
|
|
@@ -378,8 +443,8 @@ async function callTool(root, name, a) {
|
|
|
378
443
|
}
|
|
379
444
|
}
|
|
380
445
|
if (a.charts !== undefined) {
|
|
381
|
-
|
|
382
|
-
sheet.charts =
|
|
446
|
+
if (a.charts.length) throw new OpsError('charts_in_assets', 'Charts are not placed on the grid any more. Use render_chart to save one as an image in the workbook\'s Assets.');
|
|
447
|
+
sheet.charts = undefined;
|
|
383
448
|
}
|
|
384
449
|
if (a.hidden_rows !== undefined) sheet.hiddenRows = a.hidden_rows.length ? [...new Set(a.hidden_rows.map(Math.trunc))].sort((x, y) => x - y) : undefined;
|
|
385
450
|
if (a.hidden_cols !== undefined) sheet.hiddenCols = a.hidden_cols.length ? [...new Set(a.hidden_cols.map((l) => String(l).toUpperCase()))] : undefined;
|
|
@@ -399,6 +464,31 @@ async function callTool(root, name, a) {
|
|
|
399
464
|
const { hash } = await writeWorkbook(root, a.id, data, { create: true });
|
|
400
465
|
return { id: a.id, hash, url: `/#/w/${a.id}`, problems: checkWorkbook(data) };
|
|
401
466
|
}
|
|
467
|
+
case 'list_assets':
|
|
468
|
+
return { scope: a.scope, assets: listAssets(root, a.scope) };
|
|
469
|
+
case 'read_asset': {
|
|
470
|
+
if (!/\.md$/i.test(String(a.name ?? ''))) throw new OpsError('bad_name', 'read_asset reads notes (.md); images are listed by list_assets');
|
|
471
|
+
return { scope: a.scope, name: a.name, text: readAsset(root, a.scope, a.name) };
|
|
472
|
+
}
|
|
473
|
+
case 'write_note':
|
|
474
|
+
return writeNote(root, a.scope, a.name, a.text);
|
|
475
|
+
case 'render_chart':
|
|
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);
|
|
490
|
+
case 'delete_asset':
|
|
491
|
+
return trashAsset(root, a.scope, a.name);
|
|
402
492
|
case 'rename_workbook': {
|
|
403
493
|
const title = String(a.title ?? '').trim();
|
|
404
494
|
if (!title || title.length > 200 || /[\n\r]/.test(title)) throw new OpsError('bad_title', 'A title is one line of 1 to 200 characters.');
|
|
@@ -416,6 +506,8 @@ async function callTool(root, name, a) {
|
|
|
416
506
|
const id = a.new_id ?? nextCopyId(a.workbook, taken);
|
|
417
507
|
const title = /\(copy( \d+)?\)$/.test(data.title) ? data.title : `${data.title} (copy)`;
|
|
418
508
|
const { hash } = await writeWorkbook(root, id, { ...data, title }, { create: true });
|
|
509
|
+
const from = assetsDir(root, a.workbook);
|
|
510
|
+
if (existsSync(from)) cpSync(from, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
|
|
419
511
|
return { id, title, hash, url: `/#/w/${id}` };
|
|
420
512
|
}
|
|
421
513
|
case 'delete_workbook':
|
package/ops.js
CHANGED
|
@@ -119,6 +119,11 @@ export function nextCopyId(id, taken) {
|
|
|
119
119
|
|
|
120
120
|
// ---------- reading cells for agents ----------
|
|
121
121
|
|
|
122
|
+
/** "B2:D9" or "B2" (with $ allowed) as rows and columns, or null. */
|
|
123
|
+
export function parseRangeText(text) {
|
|
124
|
+
return parseRange(text);
|
|
125
|
+
}
|
|
126
|
+
|
|
122
127
|
function parseRange(text) {
|
|
123
128
|
const [a, b] = String(text).toUpperCase().replaceAll('$', '').split(':');
|
|
124
129
|
const p = parseA1(a ?? '');
|
|
@@ -280,7 +285,7 @@ export function checkWorkbook(data) {
|
|
|
280
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.');
|
|
281
286
|
}
|
|
282
287
|
for (const ch of s.charts ?? []) {
|
|
283
|
-
if (!['bar', 'line', 'pie'].includes(ch.type)) add('error', s.name, ch.id ?? '', `Unknown chart type "${ch.type}"
|
|
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}".`);
|
|
284
289
|
if (!parseRange(ch.range ?? '')) add('error', s.name, ch.id ?? '', 'A chart needs a data range like A1:C13.');
|
|
285
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.');
|
|
286
291
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-spreadsheet/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
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",
|
|
@@ -23,11 +23,14 @@
|
|
|
23
23
|
"mcp.js",
|
|
24
24
|
"server.js",
|
|
25
25
|
"ops.js",
|
|
26
|
+
"assets.js",
|
|
26
27
|
"app",
|
|
27
28
|
"skills",
|
|
28
|
-
"templates"
|
|
29
|
+
"templates",
|
|
30
|
+
"dist"
|
|
29
31
|
],
|
|
30
32
|
"publishConfig": {
|
|
31
33
|
"access": "public"
|
|
32
|
-
}
|
|
34
|
+
},
|
|
35
|
+
"scripts": {}
|
|
33
36
|
}
|