@open-spreadsheet/core 0.2.0 → 0.3.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 ADDED
@@ -0,0 +1,223 @@
1
+ // The Assets panel: a workbook's images and Markdown notes (sheets/<id>/assets/)
2
+ // and the workspace's shared ones (assets/). Charts are made here as images
3
+ // rather than placed on the grid; notes are what people keep about the numbers,
4
+ // and agents read them as context.
5
+ import { T } from './i18n.ts';
6
+ import { icon } from './icons.ts';
7
+ import { confirmDialog, el, iconButton, pickFile, promptDialog, toast } from './ui.ts';
8
+
9
+ export const SHARED = 'shared';
10
+
11
+ export interface AssetEntry {
12
+ name: string;
13
+ kind: 'image' | 'note';
14
+ size: number;
15
+ updatedAt: string;
16
+ title?: string;
17
+ }
18
+
19
+ const api = (path: string, params: Record<string, string>) => `/__api/assets${path}?${new URLSearchParams(params).toString()}`;
20
+
21
+ export async function listAssets(scope: string): Promise<AssetEntry[]> {
22
+ const res = await fetch(api('', { scope }));
23
+ if (!res.ok) return [];
24
+ return ((await res.json()) as { assets: AssetEntry[] }).assets;
25
+ }
26
+
27
+ /** Stores an image; a taken name comes back numbered. */
28
+ export async function uploadAsset(scope: string, name: string, body: Blob | string, type = 'image/svg+xml'): Promise<string> {
29
+ const res = await fetch(api('/upload', { scope, name }), { method: 'POST', headers: { 'content-type': type }, body });
30
+ const out = (await res.json()) as { name?: string; error?: string };
31
+ if (!res.ok) throw new Error(out.error ?? res.statusText);
32
+ return out.name!;
33
+ }
34
+
35
+ async function readNote(scope: string, name: string): Promise<string> {
36
+ const res = await fetch(api('/file', { scope, name }));
37
+ return res.ok ? res.text() : '';
38
+ }
39
+
40
+ async function writeNote(scope: string, name: string, text: string): Promise<void> {
41
+ const res = await fetch('/__api/assets/note', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ scope, name, text }) });
42
+ if (!res.ok) throw new Error(((await res.json()) as { error?: string }).error ?? res.statusText);
43
+ }
44
+
45
+ async function removeAsset(scope: string, name: string): Promise<void> {
46
+ const res = await fetch(api('', { scope, name }), { method: 'DELETE' });
47
+ if (!res.ok) throw new Error(((await res.json()) as { error?: string }).error ?? res.statusText);
48
+ }
49
+
50
+ /** A file name for a note from its title: letters of any script kept, the rest dashes. */
51
+ export const noteName = (title: string) =>
52
+ `${
53
+ title
54
+ .normalize('NFKC')
55
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
56
+ .replace(/^-+|-+$/g, '')
57
+ .slice(0, 60) || 'note'
58
+ }.md`;
59
+
60
+ export interface AssetsPanel {
61
+ el: HTMLElement;
62
+ open(): void;
63
+ close(): void;
64
+ toggle(): void;
65
+ isOpen(): boolean;
66
+ refresh(): Promise<void>;
67
+ /** Called with a chart's file name once it is saved, so it can be shown first. */
68
+ showSaved(scope: string, name: string): Promise<void>;
69
+ }
70
+
71
+ export function createAssetsPanel(opts: { bookId: string; onClose?: () => void; newChart: (at: HTMLElement) => void }): AssetsPanel {
72
+ const panel = el('aside', 'assets-panel');
73
+ panel.hidden = true;
74
+ panel.setAttribute('aria-label', T.assets);
75
+ const head = el('div', 'assets-head');
76
+ head.append(el('h2', '', T.assets), el('div', 'grow'), iconButton('x', T.close, () => close()));
77
+ const actions = el('div', 'assets-actions');
78
+ const chartBtn = el('button', 'btn', '');
79
+ chartBtn.type = 'button';
80
+ chartBtn.append(icon('chart', 14), el('span', '', T.newChartImage));
81
+ chartBtn.addEventListener('click', () => opts.newChart(chartBtn));
82
+ const noteBtn = el('button', 'btn', '');
83
+ noteBtn.type = 'button';
84
+ noteBtn.append(icon('pencil', 14), el('span', '', T.newNote));
85
+ noteBtn.addEventListener('click', () => void newNote());
86
+ const uploadBtn = el('button', 'btn', '');
87
+ uploadBtn.type = 'button';
88
+ uploadBtn.append(icon('upload', 14), el('span', '', T.uploadImage));
89
+ uploadBtn.addEventListener('click', () => void upload());
90
+ actions.append(chartBtn, noteBtn, uploadBtn);
91
+ const list = el('div', 'assets-list');
92
+ panel.append(head, el('p', 'assets-hint', T.assetsHint), actions, list);
93
+
94
+ let highlight = '';
95
+
96
+ function card(scope: string, a: AssetEntry): HTMLElement {
97
+ const c = el('div', `asset-card ${a.kind}`);
98
+ c.dataset.name = a.name;
99
+ if (`${scope}/${a.name}` === highlight) c.classList.add('fresh');
100
+ const src = api('/file', { scope, name: a.name, v: a.updatedAt });
101
+ if (a.kind === 'image') {
102
+ const img = el('img');
103
+ img.src = src;
104
+ img.alt = a.name;
105
+ img.loading = 'lazy';
106
+ const open = el('a', 'asset-preview');
107
+ open.href = src;
108
+ open.target = '_blank';
109
+ open.rel = 'noopener';
110
+ open.append(img);
111
+ c.append(open);
112
+ } else {
113
+ const body = el('button', 'asset-note');
114
+ body.type = 'button';
115
+ body.append(icon('file', 14), el('span', 'asset-note-title', a.title || a.name));
116
+ body.addEventListener('click', () => void editNote(scope, a.name));
117
+ c.append(body);
118
+ }
119
+ const foot = el('div', 'asset-foot');
120
+ foot.append(el('span', 'asset-name', a.name));
121
+ const dl = el('a', 'icon-link');
122
+ dl.href = api('/file', { scope, name: a.name, download: '1' });
123
+ dl.title = T.download;
124
+ dl.append(icon('download', 13));
125
+ const del = iconButton('trash', T.delete, async () => {
126
+ if (!(await confirmDialog(T.deleteAssetTitle(a.name), T.deleteAssetBody, T.delete, true))) return;
127
+ try {
128
+ await removeAsset(scope, a.name);
129
+ await refresh();
130
+ } catch (e) {
131
+ toast((e as Error).message);
132
+ }
133
+ });
134
+ foot.append(dl, del);
135
+ c.append(foot);
136
+ return c;
137
+ }
138
+
139
+ async function refresh() {
140
+ const [mine, shared] = await Promise.all([listAssets(opts.bookId), listAssets(SHARED)]);
141
+ const section = (title: string, scope: string, items: AssetEntry[]) => {
142
+ const s = el('section', 'assets-section');
143
+ s.dataset.scope = scope;
144
+ s.append(el('h3', '', title));
145
+ if (!items.length) s.append(el('p', 'assets-empty', T.noAssets));
146
+ const notes = items.filter((a) => a.kind === 'note');
147
+ const images = items.filter((a) => a.kind === 'image');
148
+ for (const a of [...notes, ...images]) s.append(card(scope, a));
149
+ return s;
150
+ };
151
+ list.replaceChildren(section(T.assetsThisBook, opts.bookId, mine), section(T.assetsShared, SHARED, shared));
152
+ }
153
+
154
+ async function newNote() {
155
+ const v = await promptDialog({
156
+ title: T.newNote,
157
+ body: T.noteContextHint,
158
+ fields: [
159
+ { name: 'title', label: T.title, value: '', validate: (x) => (x.trim() ? null : T.title) },
160
+ { name: 'text', label: T.noteLabel, value: '', multiline: true },
161
+ { name: 'scope', label: T.saveIn, options: [{ value: opts.bookId, label: T.assetsThisBook }, { value: SHARED, label: T.assetsShared }], value: opts.bookId },
162
+ ],
163
+ ok: T.save,
164
+ });
165
+ if (!v) return;
166
+ const title = v.title!.trim();
167
+ const text = v.text!.trim() ? `# ${title}\n\n${v.text!.trim()}\n` : `# ${title}\n`;
168
+ try {
169
+ await writeNote(v.scope!, noteName(title), text);
170
+ highlight = `${v.scope}/${noteName(title)}`;
171
+ await refresh();
172
+ } catch (e) {
173
+ toast((e as Error).message);
174
+ }
175
+ }
176
+
177
+ async function editNote(scope: string, name: string) {
178
+ const text = await readNote(scope, name);
179
+ const v = await promptDialog({ title: name, body: T.noteContextHint, fields: [{ name: 'text', label: T.noteLabel, value: text, multiline: true }], ok: T.save });
180
+ if (!v) return;
181
+ try {
182
+ await writeNote(scope, name, v.text!);
183
+ await refresh();
184
+ } catch (e) {
185
+ toast((e as Error).message);
186
+ }
187
+ }
188
+
189
+ async function upload() {
190
+ const file = await pickFile('image/png,image/jpeg,image/gif,image/webp,image/svg+xml');
191
+ if (!file) return;
192
+ try {
193
+ const name = await uploadAsset(opts.bookId, file.name.replace(/[^\p{L}\p{N}_ .()-]+/gu, '-'), file, file.type || 'application/octet-stream');
194
+ highlight = `${opts.bookId}/${name}`;
195
+ await refresh();
196
+ } catch (e) {
197
+ toast((e as Error).message);
198
+ }
199
+ }
200
+
201
+ function open() {
202
+ panel.hidden = false;
203
+ void refresh();
204
+ }
205
+ function close() {
206
+ panel.hidden = true;
207
+ opts.onClose?.();
208
+ }
209
+ return {
210
+ el: panel,
211
+ open,
212
+ close,
213
+ toggle: () => (panel.hidden ? open() : close()),
214
+ isOpen: () => !panel.hidden,
215
+ refresh,
216
+ async showSaved(scope, name) {
217
+ highlight = `${scope}/${name}`;
218
+ panel.hidden = false;
219
+ await refresh();
220
+ panel.querySelector(`.asset-card[data-name="${CSS.escape(name)}"]`)?.scrollIntoView({ block: 'nearest' });
221
+ },
222
+ };
223
+ }
package/app/book.ts CHANGED
@@ -19,7 +19,8 @@ import {
19
19
  type Node as FormulaNode,
20
20
  } from '@open-spreadsheet/engine';
21
21
  import { isProtectedCell, touchesProtected, BLANK, columnValues, conditionalLook, type CellLook, DEFAULT_HIGHLIGHT, filteredRows, shiftRange, validationAt } from './features.ts';
22
- import { chartData, chartSvg } from './charts.ts';
22
+ import { chartData, chartFile, chartSvg } from './charts.ts';
23
+ import { createAssetsPanel, uploadAsset } from './assets.ts';
23
24
  import { printHtml } from './print.ts';
24
25
  import { api } from './home.ts';
25
26
  import { helpFor, suggest } from './help.ts';
@@ -160,6 +161,8 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
160
161
  const helpBtn = iconButton('keyboard', T.shortcuts, () => showShortcuts());
161
162
  const paletteBtn = iconButton('list', `${T.palette.replace('…', '')} (${MOD}K)`, () => void openPalette());
162
163
  const notesBtn = iconButton('pencil', T.notes, () => notesMenu());
164
+ const assetsBtn = iconButton('file', `${T.assets} — ${T.assetsHint}`, () => assets.toggle(), T.assets);
165
+ assetsBtn.classList.add('with-label');
163
166
  const notesBadge = el('span', 'badge');
164
167
  notesBtn.append(notesBadge);
165
168
  const downloadBtn = el('button', 'btn primary');
@@ -167,7 +170,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
167
170
  downloadBtn.append(icon('download', 15), el('span', '', T.download), icon('chevronDown', 14));
168
171
  const fileMark = el('span', 'brand-mark');
169
172
  fileMark.append(icon('sheet', 14));
170
- head.append(back, fileMark, titleBtn, status, el('div', 'grow'), notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
173
+ head.append(back, fileMark, titleBtn, status, el('div', 'grow'), assetsBtn, notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
171
174
 
172
175
  // Toolbar
173
176
  const toolbar = el('div', 'toolbar');
@@ -291,8 +294,11 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
291
294
  tabsBar.append(addTab, listTabs, tabs, el('div', 'grow'), stats, zoomSel);
292
295
 
293
296
  const gridWrap = el('div', 'grid-wrap');
294
- gridWrap.append(grid, findbar);
295
- root.append(head, toolbar, fbar, gridWrap, tabsBar);
297
+ // Charts are images in Assets now; a workbook that still has charts on its grid is offered the move.
298
+ const legacyBar = el('div', 'legacy-charts');
299
+ const assets = createAssetsPanel({ bookId: id, newChart: (at) => chartImageMenu(at), onClose: () => editor.focus() });
300
+ gridWrap.append(grid, findbar, assets.el);
301
+ root.append(head, toolbar, fbar, legacyBar, gridWrap, tabsBar);
296
302
  app.replaceChildren(root);
297
303
  document.body.append(popup);
298
304
 
@@ -2636,16 +2642,82 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2636
2642
  window.addEventListener('mousemove', move);
2637
2643
  window.addEventListener('mouseup', up);
2638
2644
  }
2639
- function insertChart(type: ChartType) {
2645
+ // ---------- chart images (Assets) ----------
2646
+ const fileSlug = (text: string) =>
2647
+ text
2648
+ .normalize('NFKC')
2649
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
2650
+ .replace(/^-+|-+$/g, '')
2651
+ .slice(0, 60);
2652
+ /** A range drawn as a standalone SVG, the same picture the MCP render_chart tool makes. */
2653
+ function chartImageSvg(sheetName: string, range: string, type: ChartType, title: string): string {
2654
+ const r = parseRange(range);
2655
+ if (!r) return '';
2656
+ const cells = Array.from({ length: r.r1 - r.r0 + 1 }, (_, i) => Array.from({ length: r.c1 - r.c0 + 1 }, (_, k) => wb.value(sheetName, r.r0 + i, r.c0 + k)));
2657
+ const spec: ChartSpec = { id: 'asset', type, range, ...(title ? { title } : {}), x: 0, y: 0, w: 720, h: 405 };
2658
+ return chartFile(spec, chartData(cells));
2659
+ }
2660
+ /** Draws the selection (or the data around the cursor) as a chart image in this workbook's Assets. */
2661
+ async function chartImage(type: ChartType) {
2640
2662
  const s = selection();
2641
2663
  const r = s.r0 === s.r1 && s.c0 === s.c1 ? currentRegion(active) : s;
2642
- const id = `chart-${Date.now().toString(36)}`;
2643
- const spec: ChartSpec = { id, type, range: rangeText(r), x: Math.round(colX[Math.min(r.c1 + 1, nCols)]! / zoom) + 16, y: Math.round(rowY[r.r0]! / zoom), w: 440, h: 270 };
2664
+ const range = rangeText(r);
2665
+ const head = wb.value(name(), r.r0, r.c0);
2666
+ const v = await promptDialog({
2667
+ title: T.newChartImage,
2668
+ body: `${name()}!${range}`,
2669
+ fields: [{ name: 't', label: T.title, value: typeof head === 'string' && head ? head : '' }],
2670
+ ok: T.save,
2671
+ });
2672
+ editor.focus();
2673
+ if (!v) return;
2674
+ const title = v.t!.trim();
2675
+ try {
2676
+ const saved = await uploadAsset(id, `${fileSlug(title || `${name()}-${range}`) || 'chart'}.svg`, chartImageSvg(name(), range, type, title));
2677
+ await assets.showSaved(id, saved);
2678
+ toast(T.chartSaved(saved));
2679
+ } catch (e) {
2680
+ toast((e as Error).message);
2681
+ }
2682
+ }
2683
+ function chartImageMenu(at: HTMLElement) {
2684
+ showMenu(
2685
+ [
2686
+ { label: T.chartBar, icon: 'chart', action: () => void chartImage('bar') },
2687
+ { label: T.chartLine, icon: 'lineChart', action: () => void chartImage('line') },
2688
+ { label: T.chartPie, icon: 'pieChart', action: () => void chartImage('pie') },
2689
+ ],
2690
+ at,
2691
+ () => editor.focus(),
2692
+ );
2693
+ }
2694
+ /** Turns every chart on the grid into an image in Assets, then takes them off the grid (one undo step). */
2695
+ async function moveChartsToAssets() {
2696
+ const all = data.sheets.flatMap((sh) => (sh.charts ?? []).map((c) => ({ sheet: sh.name, c })));
2697
+ if (!all.length) return;
2698
+ try {
2699
+ for (const { sheet: sn, c } of all) {
2700
+ await uploadAsset(id, `${fileSlug(c.title || `${sn}-${c.range}`) || 'chart'}.svg`, chartImageSvg(sn, c.range, c.type, c.title ?? ''));
2701
+ }
2702
+ } catch (e) {
2703
+ toast((e as Error).message);
2704
+ return;
2705
+ }
2644
2706
  change(() => {
2645
- const sh = sheet();
2646
- sh.charts = [...(sh.charts ?? []), spec];
2707
+ for (const sh of data.sheets) delete sh.charts;
2647
2708
  }, { relayout: false });
2648
- selectChart(id);
2709
+ paintLegacyBar();
2710
+ await assets.showSaved(id, '');
2711
+ toast(T.chartsMoved(all.length));
2712
+ }
2713
+ function paintLegacyBar() {
2714
+ const n = data.sheets.reduce((k, sh) => k + (sh.charts?.length ?? 0), 0);
2715
+ legacyBar.hidden = n === 0;
2716
+ if (!n) return;
2717
+ const move = el('button', 'btn primary', T.moveChartsToAssets);
2718
+ move.type = 'button';
2719
+ move.addEventListener('click', () => void moveChartsToAssets());
2720
+ legacyBar.replaceChildren(icon('chart', 14), el('span', '', T.chartsOnGrid(n)), el('div', 'grow'), move);
2649
2721
  }
2650
2722
  function chartMenu(id: string, at: { x: number; y: number } | HTMLElement) {
2651
2723
  const spec = chartSpec(id);
@@ -3184,16 +3256,9 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3184
3256
  );
3185
3257
  };
3186
3258
  tb.cond.addEventListener('click', () => conditionalMenu(tb.cond));
3259
+ tb.chart.title = T.newChartImage;
3187
3260
  tb.chart.addEventListener('click', () =>
3188
- showMenu(
3189
- [
3190
- { label: T.chartBar, icon: 'chart', action: () => insertChart('bar') },
3191
- { label: T.chartLine, icon: 'lineChart', action: () => insertChart('line') },
3192
- { label: T.chartPie, icon: 'pieChart', action: () => insertChart('pie') },
3193
- ],
3194
- tb.chart,
3195
- () => editor.focus(),
3196
- ),
3261
+ chartImageMenu(tb.chart),
3197
3262
  );
3198
3263
  tb.border.addEventListener('click', () => showMenu(borderItems(), tb.border, () => editor.focus()));
3199
3264
  tb.filter.addEventListener('click', () => {
@@ -3403,7 +3468,8 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3403
3468
  cmd(T.gRowsCols, T.hideCols(s.c1 - s.c0 + 1), () => hideCols(s.c0, s.c1), 'eyeOff', undefined, 'hide columns'),
3404
3469
  cmd(T.gRowsCols, T.unhideRows, () => unhideRows(s.r0, s.r1), 'eye', undefined, 'unhide show rows'),
3405
3470
  cmd(T.gRowsCols, T.unhideCols, () => unhideCols(s.c0, s.c1), 'eye', undefined, 'unhide show columns'),
3406
- ...(['bar', 'line', 'pie'] as const).map((k) => cmd(T.chart, `${T.insertChart}:${{ bar: T.chartBar, line: T.chartLine, pie: T.chartPie }[k]}`, () => insertChart(k), k === 'bar' ? 'chart' : k === 'line' ? 'lineChart' : 'pieChart', undefined, `chart graph ${k}`)),
3471
+ ...(['bar', 'line', 'pie'] as const).map((k) => cmd(T.chart, `${T.newChartImage}:${{ bar: T.chartBar, line: T.chartLine, pie: T.chartPie }[k]}`, () => void chartImage(k), k === 'bar' ? 'chart' : k === 'line' ? 'lineChart' : 'pieChart', undefined, `chart graph image asset ${k}`)),
3472
+ cmd(T.chart, T.assets, () => assets.open(), 'file', undefined, 'assets images notes markdown'),
3407
3473
  cmd(T.gFormat, T.conditional, () => conditionalMenu(tb.cond), 'conditional', undefined, 'conditional formatting color scale data bar highlight'),
3408
3474
  cmd(T.gEdit, T.sortDesc, () => sortBy(true), 'sortDesc', undefined, 'sort descending'),
3409
3475
  ...['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN'].map((f) => cmd(T.autosum, `${f}( )`, () => autosum(f), 'sigma', undefined, `autosum ${f.toLowerCase()}`)),
@@ -4182,6 +4248,12 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
4182
4248
  status.textContent = T.saved;
4183
4249
  }
4184
4250
  import.meta.hot?.on('open-spreadsheet:changed', onExternal);
4251
+ // An agent (or apply-notes) wrote an image or note: the open panel shows it.
4252
+ const onAssets = (d: { scope: string }) => {
4253
+ if (assets.isOpen() && (d.scope === id || d.scope === 'shared')) void assets.refresh();
4254
+ };
4255
+ import.meta.hot?.on('open-spreadsheet:assets', onAssets);
4256
+ paintLegacyBar();
4185
4257
 
4186
4258
  const onBeforeUnload = () => {
4187
4259
  if (saveTimer) void flush();
@@ -4199,6 +4271,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
4199
4271
  notePop.remove();
4200
4272
  closeMenus();
4201
4273
  import.meta.hot?.off?.('open-spreadsheet:changed', onExternal);
4274
+ import.meta.hot?.off?.('open-spreadsheet:assets', onAssets);
4202
4275
  teardown = null;
4203
4276
  };
4204
4277
  const onHash = () => {
package/app/charts.ts CHANGED
@@ -160,3 +160,19 @@ function legend(names: string[], w: number, h: number): string {
160
160
  })
161
161
  .join('');
162
162
  }
163
+
164
+ /**
165
+ * A chart as a file of its own — for the Assets folder, a note or another
166
+ * program: the SVG with its namespace, a white background and the colours the
167
+ * page would give it written in, since no stylesheet comes with it.
168
+ */
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)
175
+ .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');
178
+ }
package/app/i18n-more.ts CHANGED
@@ -216,6 +216,23 @@ export const zhCN: Dict = {
216
216
  protectedOn: (r: string) => `已保护 ${r}:取消保护前不能修改。`,
217
217
  protectedOff: '已取消保护。',
218
218
  protectedRefused: '这个区域受保护。请先取消保护(右键 → 取消保护)。',
219
+ assets: 'Assets',
220
+ assetsHint: '这个工作簿的图片和笔记;笔记也是 agent 处理时的背景资料。',
221
+ assetsThisBook: '这个工作簿',
222
+ assetsShared: '共享',
223
+ newChartImage: '图表图片',
224
+ newNote: '新建笔记',
225
+ uploadImage: '上传图片',
226
+ noAssets: '还没有内容。',
227
+ saveIn: '保存在',
228
+ noteContextHint: 'Markdown 格式。Agent 处理这个工作簿前会先读这些笔记:数字的含义、来源、要遵守的规则。',
229
+ deleteAssetTitle: (n: string) => `删除 ${n}?`,
230
+ deleteAssetBody: '会移到 assets 的 .trash 文件夹。',
231
+ chartSaved: (n: string) => `已保存到 Assets:${n}`,
232
+ chartsMoved: (k: number) => `已把 ${k} 个图表移到 Assets`,
233
+ chartsOnGrid: (k: number) => `这个工作簿的单元格上有 ${k} 个图表;图表现在改以图片放在 Assets。`,
234
+ moveChartsToAssets: '移到 Assets',
235
+ close: '关闭',
219
236
  fontSize: '字号',
220
237
  fontSizeOther: '其他字号…',
221
238
  customSort: '自定义排序…',
@@ -484,6 +501,23 @@ export const ja: Dict = {
484
501
  protectedOn: (r: string) => `${r} を保護しました。解除するまで変更できません。`,
485
502
  protectedOff: '保護を解除しました。',
486
503
  protectedRefused: 'この範囲は保護されています。先に保護を解除してください(右クリック → 範囲の保護を解除)。',
504
+ assets: 'Assets',
505
+ assetsHint: 'このブックの画像とメモ。メモはエージェントの作業時の前提情報にもなります。',
506
+ assetsThisBook: 'このブック',
507
+ assetsShared: '共有',
508
+ newChartImage: 'グラフ画像',
509
+ close: '閉じる',
510
+ newNote: '新しいメモ',
511
+ uploadImage: '画像をアップロード',
512
+ noAssets: 'まだありません。',
513
+ saveIn: '保存先',
514
+ noteContextHint: 'Markdown。エージェントはブックを扱う前にこれらのメモを読みます:数字の意味、出典、守るべきルール。',
515
+ deleteAssetTitle: (n: string) => `${n} を削除しますか?`,
516
+ deleteAssetBody: 'assets の .trash フォルダーに移動します。',
517
+ chartSaved: (n: string) => `Assets に保存しました:${n}`,
518
+ chartsMoved: (k: number) => `${k} 個のグラフを Assets に移動しました`,
519
+ chartsOnGrid: (k: number) => `このブックのセル上に ${k} 個のグラフがあります。グラフは画像として Assets に置くようになりました。`,
520
+ moveChartsToAssets: 'Assets へ移動',
487
521
  fontSize: 'フォント サイズ',
488
522
  fontSizeOther: 'その他のサイズ…',
489
523
  customSort: 'ユーザー設定の並べ替え…',
@@ -752,6 +786,23 @@ export const ko: Dict = {
752
786
  protectedOn: (r: string) => `${r}을(를) 보호했습니다. 해제하기 전에는 변경할 수 없습니다.`,
753
787
  protectedOff: '보호를 해제했습니다.',
754
788
  protectedRefused: '이 범위는 보호되어 있습니다. 먼저 보호를 해제하세요(오른쪽 클릭 → 범위 보호 해제).',
789
+ assets: 'Assets',
790
+ assetsHint: '이 통합 문서의 이미지와 메모입니다. 메모는 에이전트 작업의 배경 정보가 됩니다.',
791
+ assetsThisBook: '이 통합 문서',
792
+ assetsShared: '공유',
793
+ newChartImage: '차트 이미지',
794
+ close: '닫기',
795
+ newNote: '새 메모',
796
+ uploadImage: '이미지 업로드',
797
+ noAssets: '아직 없습니다.',
798
+ saveIn: '저장 위치',
799
+ noteContextHint: 'Markdown 형식입니다. 에이전트는 통합 문서를 다루기 전에 이 메모를 읽습니다: 숫자의 의미, 출처, 지킬 규칙.',
800
+ deleteAssetTitle: (n: string) => `${n}을(를) 삭제할까요?`,
801
+ deleteAssetBody: 'assets의 .trash 폴더로 이동합니다.',
802
+ chartSaved: (n: string) => `Assets에 저장했습니다: ${n}`,
803
+ chartsMoved: (k: number) => `차트 ${k}개를 Assets로 옮겼습니다`,
804
+ chartsOnGrid: (k: number) => `이 통합 문서의 셀 위에 차트가 ${k}개 있습니다. 차트는 이제 이미지로 Assets에 둡니다.`,
805
+ moveChartsToAssets: 'Assets로 이동',
755
806
  fontSize: '글꼴 크기',
756
807
  fontSizeOther: '다른 크기…',
757
808
  customSort: '사용자 지정 정렬…',
package/app/i18n.ts CHANGED
@@ -216,6 +216,23 @@ export const en = {
216
216
  protectedOn: (r: string) => `Protected: ${r}. Its cells cannot be changed until unprotected.`,
217
217
  protectedOff: 'Protection removed.',
218
218
  protectedRefused: 'This range is protected. Unprotect it first (right-click → Unprotect range).',
219
+ assets: 'Assets',
220
+ assetsHint: "This workbook's images and notes. Notes are context for agents.",
221
+ assetsThisBook: 'This workbook',
222
+ assetsShared: 'Shared',
223
+ newChartImage: 'Chart image',
224
+ newNote: 'New note',
225
+ uploadImage: 'Upload image',
226
+ noAssets: 'Nothing here yet.',
227
+ saveIn: 'Save in',
228
+ noteContextHint: 'Markdown. Agents read these notes before working on the workbook: what the numbers mean, where they come from, what to keep.',
229
+ deleteAssetTitle: (n: string) => `Delete ${n}?`,
230
+ deleteAssetBody: 'It moves to the assets .trash folder.',
231
+ chartSaved: (n: string) => `Saved ${n} in Assets`,
232
+ chartsMoved: (k: number) => `Moved ${k} chart${k === 1 ? '' : 's'} to Assets`,
233
+ chartsOnGrid: (k: number) => `This workbook has ${k} chart${k === 1 ? '' : 's'} on the grid. Charts now live in Assets as images.`,
234
+ moveChartsToAssets: 'Move to Assets',
235
+ close: 'Close',
219
236
  fontSize: 'Font size',
220
237
  fontSizeOther: 'Other size…',
221
238
  customSort: 'Custom sort…',
@@ -484,6 +501,23 @@ const zh: Dict = {
484
501
  protectedOn: (r: string) => `已保護 ${r}:取消保護前不能修改。`,
485
502
  protectedOff: '已取消保護。',
486
503
  protectedRefused: '這個範圍受保護。請先取消保護(右鍵 → 取消保護)。',
504
+ assets: 'Assets',
505
+ assetsHint: '這本活頁簿的圖片和筆記;筆記也是 agent 處理時的背景資料。',
506
+ assetsThisBook: '這本活頁簿',
507
+ assetsShared: '共用',
508
+ newChartImage: '圖表圖片',
509
+ close: '關閉',
510
+ newNote: '新增筆記',
511
+ uploadImage: '上傳圖片',
512
+ noAssets: '還沒有內容。',
513
+ saveIn: '存放在',
514
+ noteContextHint: 'Markdown 格式。Agent 處理這本活頁簿前會先讀這些筆記:數字的意思、來源、要遵守的規則。',
515
+ deleteAssetTitle: (n: string) => `刪除 ${n}?`,
516
+ deleteAssetBody: '會移到 assets 的 .trash 資料夾。',
517
+ chartSaved: (n: string) => `已存到 Assets:${n}`,
518
+ chartsMoved: (k: number) => `已把 ${k} 個圖表移到 Assets`,
519
+ chartsOnGrid: (k: number) => `這本活頁簿的格子上有 ${k} 個圖表;圖表現在改以圖片放在 Assets。`,
520
+ moveChartsToAssets: '移到 Assets',
487
521
  fontSize: '字型大小',
488
522
  fontSizeOther: '其他大小…',
489
523
  customSort: '自訂排序…',
package/app/style.css CHANGED
@@ -189,6 +189,32 @@ kbd { font: 10.5px var(--mono); color: var(--muted-foreground); border: 1px soli
189
189
  .finput { flex: 1; min-width: 0; border: 0; outline: none; padding: 0 12px; background: transparent; font: 13px var(--mono); }
190
190
 
191
191
  .grid-wrap { flex: 1; min-height: 0; position: relative; }
192
+
193
+ /* Assets: a drawer over the grid's right side. */
194
+ .assets-panel { position: absolute; top: 0; right: 0; bottom: 0; width: min(360px, 92vw); z-index: 30; display: flex; flex-direction: column; background: var(--background); border-left: 1px solid var(--border); box-shadow: -12px 0 24px -16px rgb(0 0 0 / 0.25); }
195
+ .assets-panel[hidden] { display: none; }
196
+ .assets-head { display: flex; align-items: center; gap: 8px; padding: 12px 12px 4px 16px; }
197
+ .assets-head h2 { margin: 0; font-size: 15px; font-weight: 600; }
198
+ .assets-hint { margin: 0 16px 10px; font-size: 12px; line-height: 1.5; color: var(--muted-foreground); }
199
+ .assets-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 16px 12px; border-bottom: 1px solid var(--border); }
200
+ .assets-actions .btn { height: 30px; padding: 0 10px; font-size: 12.5px; }
201
+ .assets-list { flex: 1; overflow: auto; padding: 4px 16px 20px; }
202
+ .assets-section h3 { margin: 14px 0 8px; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted-foreground); }
203
+ .assets-empty { margin: 0; font-size: 12.5px; color: var(--muted-foreground); }
204
+ .asset-card { margin-bottom: 10px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--background); }
205
+ .asset-card.fresh { border-color: var(--select); box-shadow: 0 0 0 2px color-mix(in srgb, var(--select) 25%, transparent); }
206
+ .asset-preview { display: block; background: #fff; }
207
+ .asset-preview img { display: block; width: 100%; height: auto; }
208
+ .asset-note { display: flex; align-items: center; gap: 8px; width: 100%; padding: 10px 12px; border: 0; background: none; color: var(--foreground); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
209
+ .asset-note:hover { background: var(--muted); }
210
+ .asset-note-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
211
+ .asset-foot { display: flex; align-items: center; gap: 4px; padding: 4px 6px 4px 12px; border-top: 1px solid var(--border); }
212
+ .asset-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11.5px; color: var(--muted-foreground); }
213
+ .asset-foot .icon-link { display: inline-grid; place-items: center; width: 28px; height: 28px; border-radius: 6px; color: var(--muted-foreground); }
214
+ .asset-foot .icon-link:hover { background: var(--muted); color: var(--foreground); }
215
+ .legacy-charts { display: flex; align-items: center; gap: 10px; padding: 6px 12px; font-size: 12.5px; background: color-mix(in srgb, var(--select) 8%, var(--background)); border-bottom: 1px solid var(--border); }
216
+ .legacy-charts[hidden] { display: none; }
217
+ .legacy-charts .btn { height: 26px; padding: 0 10px; font-size: 12px; }
192
218
  .grid { position: absolute; inset: 0; overflow: hidden; background: var(--sheet); color: var(--cell-fg); --z: 1; user-select: none; -webkit-user-select: none; }
193
219
  .corner { position: absolute; left: 0; top: 0; width: 46px; height: 24px; z-index: 6; background: var(--head); border-right: 1px solid var(--grid); border-bottom: 1px solid var(--grid); }
194
220
  .corner.picked { background: var(--head-picked); }
package/assets.js ADDED
@@ -0,0 +1,138 @@
1
+ // Assets: images and Markdown notes that sit beside a workbook
2
+ // (sheets/<id>/assets/) or are shared by the whole workspace (assets/).
3
+ // Charts are drawn here from a range — the editor's renderer — so a person, an
4
+ // agent and `apply-notes` all get the same picture. Notes are context: agents
5
+ // read them before working on a workbook.
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { Workbook } from '@open-spreadsheet/engine';
9
+ import { ID, OpsError, parseRangeText, readWorkbook, workbookFile } from './ops.js';
10
+
11
+ export const SHARED = 'shared';
12
+ /** One file name, no folders: letters (any script), digits, space, _ . ( ) -, and a kind we serve. */
13
+ const NAME = /^[\p{L}\p{N}_][\p{L}\p{N}_ .()-]{0,118}\.(svg|png|jpe?g|gif|webp|md)$/iu;
14
+ export const IMAGE = /\.(svg|png|jpe?g|gif|webp)$/i;
15
+ export const MIME = { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', md: 'text/markdown; charset=utf-8' };
16
+
17
+ // The editor's renderer: its source in this repo, the stripped copy once installed.
18
+ const charts = () => import(new URL(import.meta.url.includes('/node_modules/') ? './dist/charts.js' : './app/charts.ts', import.meta.url).href);
19
+
20
+ /** Where a scope's assets live: a workbook's folder, or the workspace's shared one. */
21
+ export function assetsDir(root, scope) {
22
+ if (scope === SHARED) return path.join(root, 'assets');
23
+ if (!ID.test(String(scope ?? '')) || !existsSync(workbookFile(root, scope))) throw new OpsError('not_found', `No workbook ${scope} (or use scope "${SHARED}")`);
24
+ return path.join(path.dirname(workbookFile(root, scope)), 'assets');
25
+ }
26
+
27
+ export function assetPath(root, scope, name) {
28
+ if (!NAME.test(String(name ?? '')) || name.includes('..')) {
29
+ throw new OpsError('bad_name', `"${name}" is not an asset name: one file name ending in .md, .svg, .png, .jpg, .gif or .webp`);
30
+ }
31
+ return path.join(assetsDir(root, scope), name);
32
+ }
33
+
34
+ const firstLine = (text) => (text.split('\n').find((l) => l.trim()) ?? '').replace(/^#+\s*/, '').slice(0, 120);
35
+
36
+ /** A scope's images and notes, newest first; a note carries its first line as a title. */
37
+ export function listAssets(root, scope) {
38
+ const dir = assetsDir(root, scope);
39
+ if (!existsSync(dir)) return [];
40
+ return readdirSync(dir)
41
+ .filter((n) => NAME.test(n))
42
+ .map((name) => {
43
+ const st = statSync(path.join(dir, name));
44
+ const kind = IMAGE.test(name) ? 'image' : 'note';
45
+ return { name, kind, size: st.size, updatedAt: st.mtime.toISOString(), ...(kind === 'note' ? { title: firstLine(readFileSync(path.join(dir, name), 'utf8')) } : {}) };
46
+ })
47
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
48
+ }
49
+
50
+ /** A note's text, or an image's bytes. */
51
+ export function readAsset(root, scope, name) {
52
+ const file = assetPath(root, scope, name);
53
+ if (!existsSync(file)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
54
+ return IMAGE.test(name) ? readFileSync(file) : readFileSync(file, 'utf8');
55
+ }
56
+
57
+ function writeAtomic(file, content) {
58
+ mkdirSync(path.dirname(file), { recursive: true });
59
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
60
+ writeFileSync(tmp, content);
61
+ renameSync(tmp, file);
62
+ }
63
+
64
+ /** The name itself when free, else name-2, name-3… before the extension. */
65
+ function freeName(root, scope, name) {
66
+ const dir = assetsDir(root, scope);
67
+ const dot = name.lastIndexOf('.');
68
+ const stem = name.slice(0, dot);
69
+ const ext = name.slice(dot);
70
+ let candidate = name;
71
+ for (let n = 2; existsSync(path.join(dir, candidate)); n++) candidate = `${stem}-${n}${ext}`;
72
+ return candidate;
73
+ }
74
+
75
+ export function writeNote(root, scope, name, text) {
76
+ if (!/\.md$/i.test(String(name ?? ''))) throw new OpsError('bad_name', 'A note is a .md file');
77
+ const file = assetPath(root, scope, name);
78
+ writeAtomic(file, String(text ?? ''));
79
+ return { scope, name };
80
+ }
81
+
82
+ /** Stores an image (an upload); a taken name gets a number rather than replacing the file. */
83
+ export function saveImage(root, scope, name, bytes) {
84
+ if (!IMAGE.test(String(name ?? ''))) throw new OpsError('bad_name', 'An image is a .svg, .png, .jpg, .gif or .webp file');
85
+ assetPath(root, scope, name);
86
+ const free = freeName(root, scope, name);
87
+ writeAtomic(assetPath(root, scope, free), bytes);
88
+ return { scope, name: free };
89
+ }
90
+
91
+ /** Moves an asset to the scope's .trash folder; nothing is erased. */
92
+ export function trashAsset(root, scope, name) {
93
+ const file = assetPath(root, scope, name);
94
+ if (!existsSync(file)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
95
+ const trash = path.join(path.dirname(file), '.trash');
96
+ mkdirSync(trash, { recursive: true });
97
+ const to = path.join(trash, `${Date.now()}-${name}`);
98
+ renameSync(file, to);
99
+ return { scope, name, trashedTo: path.relative(root, to) };
100
+ }
101
+
102
+ const slug = (text) =>
103
+ String(text)
104
+ .normalize('NFKC')
105
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
106
+ .replace(/^-+|-+$/g, '')
107
+ .slice(0, 60);
108
+
109
+ /**
110
+ * Draws a chart from a workbook range and saves it as an SVG in the workbook's
111
+ * assets (or the shared ones): the same picture the editor shows.
112
+ */
113
+ export async function renderChart(root, workbook, opts) {
114
+ const { data } = readWorkbook(root, workbook);
115
+ const sheet = opts.sheet ? data.sheets.find((s) => s.name.toLowerCase() === String(opts.sheet).toLowerCase()) : data.sheets[0];
116
+ if (!sheet) throw new OpsError('no_sheet', `No sheet "${opts.sheet}". Sheets: ${data.sheets.map((s) => s.name).join(', ')}`);
117
+ const type = opts.type ?? 'bar';
118
+ if (!['bar', 'line', 'pie'].includes(type)) throw new OpsError('bad_type', 'type is bar, line or pie');
119
+ const r = parseRangeText(opts.range);
120
+ if (!r) throw new OpsError('bad_range', `Not a range: ${opts.range}`);
121
+ if ((r.r1 - r.r0 + 1) * (r.c1 - r.c0 + 1) > 5000) throw new OpsError('too_big', 'Chart at most 5,000 cells; pass a smaller range.');
122
+ const wb = Workbook.fromJSON(data);
123
+ const cells = [];
124
+ for (let row = r.r0; row <= r.r1; row++) {
125
+ const line = [];
126
+ for (let col = r.c0; col <= r.c1; col++) line.push(wb.value(sheet.name, row, col));
127
+ cells.push(line);
128
+ }
129
+ const { chartData, chartFile } = await charts();
130
+ const spec = { id: 'asset', type, range: opts.range, title: opts.title ?? '', x: 0, y: 0, w: 720, h: 405 };
131
+ const svg = chartFile(spec, chartData(cells), Number(opts.width) || 720, Number(opts.height) || 405);
132
+ const scope = opts.scope ?? workbook;
133
+ const wanted = opts.name ? (/\.svg$/i.test(opts.name) ? opts.name : `${opts.name}.svg`) : `${slug(opts.title || `${sheet.name}-${opts.range}`) || 'chart'}.svg`;
134
+ assetPath(root, scope, wanted);
135
+ const name = opts.replace ? wanted : freeName(root, scope, wanted);
136
+ writeAtomic(assetPath(root, scope, name), svg);
137
+ return { scope, name, sheet: sheet.name, range: opts.range, type, bytes: Buffer.byteLength(svg) };
138
+ }
package/dist/charts.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Charts drawn as SVG from a range: bar (grouped), line and pie. Hand-written,
3
+ * like open-dashboard's: one y-axis, zero in the domain, a fixed categorical
4
+ * palette, ticks from one formatter, text in ink colours.
5
+ */
6
+ import { CellError, formatValue, } from '@open-spreadsheet/engine';
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ export const PALETTE = ['#2a78d6', '#e8710a', '#1e8e3e', '#d93025', '#9334e6', '#12b5cb', '#c5221f', '#7f6000'];
17
+
18
+ const text = (v ) => (v === null ? '' : v instanceof CellError ? v.code : typeof v === 'number' ? formatValue(v, '').text : String(v));
19
+
20
+ /**
21
+ * Reads a block of cells the way Excel's chart wizard does: if the top-left
22
+ * cell is empty or the first column is text, the first column holds the
23
+ * categories; a first row of text holds the series names.
24
+ */
25
+ /** Whether a block's first row holds series names and its first column categories. */
26
+ export function chartShape(cells ) {
27
+ const cols = cells[0]?.length ?? 0;
28
+ const isText = (v ) => typeof v === 'string' && v !== '';
29
+ const headerRow = Boolean(cells[0]?.slice(1).some(isText)) || (cols === 1 && isText(cells[0]?.[0] ?? null));
30
+ const labelCol = cols > 1 && cells.slice(headerRow ? 1 : 0).some((r) => typeof r[0] !== 'number');
31
+ return { headerRow, labelCol };
32
+ }
33
+
34
+ export function chartData(cells ) {
35
+ if (!cells.length || !cells[0]?.length) return { categories: [], series: [] };
36
+ const cols = cells[0] .length;
37
+ const { headerRow, labelCol } = chartShape(cells);
38
+ const r0 = headerRow ? 1 : 0;
39
+ const c0 = labelCol ? 1 : 0;
40
+ const categories = cells.slice(r0).map((r, i) => (labelCol ? text(r[0] ?? null) : String(i + 1)));
41
+ const series = [];
42
+ for (let c = c0; c < cols; c++) {
43
+ series.push({
44
+ name: headerRow ? text(cells[0] [c] ?? null) : `Series ${c - c0 + 1}`,
45
+ values: cells.slice(r0).map((r) => (typeof r[c] === 'number' ? (r[c] ) : null)),
46
+ });
47
+ }
48
+ return { categories, series };
49
+ }
50
+
51
+ /** Round axis steps: 1, 2 or 5 times a power of ten. */
52
+ export function niceTicks(min , max , count = 5) {
53
+ if (min === max) max = min + 1;
54
+ const raw = (max - min) / count;
55
+ const mag = 10 ** Math.floor(Math.log10(raw));
56
+ const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
57
+ // From the step at or below the minimum to the step at or above the maximum, so every mark fits.
58
+ const start = Math.floor(min / step) * step;
59
+ const end = Math.ceil(max / step - 1e-9) * step;
60
+ const out = [];
61
+ for (let v = start; v <= end + step * 1e-9; v += step) out.push(Number.parseFloat(v.toPrecision(12)));
62
+ return out;
63
+ }
64
+ function tickFormat(ticks ) {
65
+ const max = Math.max(...ticks.map(Math.abs));
66
+ if (max >= 1e6) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e6).toPrecision(3))}M`);
67
+ if (max >= 1e4) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e3).toPrecision(3))}K`);
68
+ return (n) => formatValue(n, '#,##0.##').text.replace(/\.$/, '');
69
+ }
70
+ const esc = (s ) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
71
+
72
+ export function chartSvg(spec , data , w , h ) {
73
+ const titleH = spec.title ? 26 : 8;
74
+ const legendH = data.series.length > 1 || spec.type === 'pie' ? 22 : 0;
75
+ 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>`;
78
+
79
+ if (spec.type === 'pie') {
80
+ const s = data.series[0] ;
81
+ const items = s.values.map((v, i) => ({ v: Math.max(0, v ?? 0), name: data.categories[i] ?? '' })).filter((x) => x.v > 0);
82
+ const total = items.reduce((a, b) => a + b.v, 0);
83
+ const r = Math.max(10, Math.min(w, h - titleH - legendH) / 2 - 10);
84
+ const cx = w / 2;
85
+ const cy = titleH + (h - titleH - legendH) / 2;
86
+ let angle = -Math.PI / 2;
87
+ const slices = items
88
+ .map((it, i) => {
89
+ const a = (it.v / total) * Math.PI * 2;
90
+ const x0 = cx + r * Math.cos(angle);
91
+ const y0 = cy + r * Math.sin(angle);
92
+ 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>`;
97
+ })
98
+ .join('');
99
+ return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${slices}${legend(items.map((it) => it.name), w, h)}</svg>`;
100
+ }
101
+
102
+ const padL = 44;
103
+ const padR = 12;
104
+ const top = titleH + 4;
105
+ const bottom = h - legendH - 22;
106
+ const plotW = Math.max(10, w - padL - padR);
107
+ 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
+ const y = (v ) => bottom - ((v - lo) / (hi - lo)) * plotH;
113
+ const fmt = tickFormat(ticks);
114
+ const n = data.categories.length;
115
+ const band = plotW / Math.max(1, n);
116
+ 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('');
117
+ const every = Math.max(1, Math.ceil((n * 48) / plotW));
118
+ const xLabels = data.categories
119
+ .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
+ .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) => {
126
+ s.values.forEach((v, i) => {
127
+ if (v === null) return;
128
+ 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)] ));
137
+ 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"/>`;
139
+ 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>`;
141
+ });
142
+ });
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>`;
146
+ }
147
+
148
+ function legend(names , w , h ) {
149
+ 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
+ const widths = items.map((n) => 26 + textWidth(n));
153
+ const total = widths.reduce((a, b) => a + b, 0);
154
+ let x = Math.max(4, (w - total) / 2);
155
+ return items
156
+ .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>`;
158
+ x += widths[i] ;
159
+ return out;
160
+ })
161
+ .join('');
162
+ }
163
+
164
+ /**
165
+ * A chart as a file of its own — for the Assets folder, a note or another
166
+ * program: the SVG with its namespace, a white background and the colours the
167
+ * page would give it written in, since no stylesheet comes with it.
168
+ */
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)
175
+ .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');
178
+ }
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 { existsSync } from 'node:fs';
13
+ import { assetsDir, listAssets, readAsset, renderChart, trashAsset, 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,47 @@ 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', 'line', 'pie'] },
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
+ },
151
+ required: ['workbook', 'range'],
152
+ },
153
+ },
154
+ {
155
+ name: 'delete_asset',
156
+ description: 'Move an image or note to its folder\'s .trash (nothing is erased). Only when the person asked.',
157
+ inputSchema: { type: 'object', properties: { scope: str, name: str }, required: ['scope', 'name'] },
158
+ annotations: { destructiveHint: true },
159
+ },
119
160
  {
120
161
  name: 'rename_workbook',
121
162
  description: "Change a workbook's title (what the list shows). Its id, and so its address, stay.",
@@ -378,8 +419,8 @@ async function callTool(root, name, a) {
378
419
  }
379
420
  }
380
421
  if (a.charts !== undefined) {
381
- for (const ch of a.charts) parseRange(ch.range);
382
- sheet.charts = a.charts.length ? a.charts : undefined;
422
+ 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.');
423
+ sheet.charts = undefined;
383
424
  }
384
425
  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
426
  if (a.hidden_cols !== undefined) sheet.hiddenCols = a.hidden_cols.length ? [...new Set(a.hidden_cols.map((l) => String(l).toUpperCase()))] : undefined;
@@ -399,6 +440,18 @@ async function callTool(root, name, a) {
399
440
  const { hash } = await writeWorkbook(root, a.id, data, { create: true });
400
441
  return { id: a.id, hash, url: `/#/w/${a.id}`, problems: checkWorkbook(data) };
401
442
  }
443
+ case 'list_assets':
444
+ return { scope: a.scope, assets: listAssets(root, a.scope) };
445
+ case 'read_asset': {
446
+ if (!/\.md$/i.test(String(a.name ?? ''))) throw new OpsError('bad_name', 'read_asset reads notes (.md); images are listed by list_assets');
447
+ return { scope: a.scope, name: a.name, text: readAsset(root, a.scope, a.name) };
448
+ }
449
+ case 'write_note':
450
+ return writeNote(root, a.scope, a.name, a.text);
451
+ case 'render_chart':
452
+ return renderChart(root, a.workbook, a);
453
+ case 'delete_asset':
454
+ return trashAsset(root, a.scope, a.name);
402
455
  case 'rename_workbook': {
403
456
  const title = String(a.title ?? '').trim();
404
457
  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 +469,8 @@ async function callTool(root, name, a) {
416
469
  const id = a.new_id ?? nextCopyId(a.workbook, taken);
417
470
  const title = /\(copy( \d+)?\)$/.test(data.title) ? data.title : `${data.title} (copy)`;
418
471
  const { hash } = await writeWorkbook(root, id, { ...data, title }, { create: true });
472
+ const from = assetsDir(root, a.workbook);
473
+ if (existsSync(from)) cpSync(from, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
419
474
  return { id, title, hash, url: `/#/w/${id}` };
420
475
  }
421
476
  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 ?? '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-spreadsheet/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.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
  }
package/server.js CHANGED
@@ -1,6 +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
5
  import { currentFile, hashOf, ID, listWorkbooks, OpsError, readWorkbook, trashWorkbook, workbookFile, writeWorkbook } from './ops.js';
5
6
 
6
7
  const CORE = path.dirname(fileURLToPath(import.meta.url));
@@ -49,7 +50,12 @@ export function initWorkspace(dir) {
49
50
  )}\n`,
50
51
  );
51
52
  writeFileSync(path.join(root, 'open-spreadsheet.config.json'), '{}\n');
52
- 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');
53
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
54
+ writeFileSync(
55
+ path.join(root, 'assets', 'README.md'),
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
+ );
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');
53
59
  const agents = readFileSync(path.join(CORE, 'templates', 'AGENTS.md'), 'utf8');
54
60
  writeFileSync(path.join(root, 'AGENTS.md'), agents);
55
61
  writeFileSync(path.join(root, 'CLAUDE.md'), agents);
@@ -114,7 +120,21 @@ function allowedWrite(req) {
114
120
  }
115
121
  }
116
122
 
117
- const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412 };
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 };
124
+
125
+ /** A request body as bytes, for image uploads; refused past `max`. */
126
+ const readBytes = (req, max = 15_000_000) =>
127
+ new Promise((resolve, reject) => {
128
+ const parts = [];
129
+ let size = 0;
130
+ req.on('data', (c) => {
131
+ size += c.length;
132
+ if (size > max) reject(new OpsError('too_big', 'An image is at most 15 MB.'));
133
+ else parts.push(c);
134
+ });
135
+ req.on('end', () => resolve(Buffer.concat(parts)));
136
+ req.on('error', reject);
137
+ });
118
138
 
119
139
  function apiPlugin(root) {
120
140
  // Bodies this server just wrote, so its own write does not come back as an outside change.
@@ -123,6 +143,14 @@ function apiPlugin(root) {
123
143
  name: 'open-spreadsheet:api',
124
144
  configureServer(server) {
125
145
  server.watcher.add(path.join(root, 'sheets'));
146
+ server.watcher.add(path.join(root, 'assets'));
147
+ // An asset written or removed (by an agent, apply-notes, the CLI): the Assets panel reloads its list.
148
+ const assetEvent = (file) => {
149
+ const rel = path.relative(root, file).split(path.sep);
150
+ const scope = rel[0] === 'assets' && rel.length === 2 ? SHARED : rel[0] === 'sheets' && rel[2] === 'assets' && rel.length === 4 ? rel[1] : null;
151
+ if (scope) server.ws.send({ type: 'custom', event: 'open-spreadsheet:assets', data: { scope } });
152
+ };
153
+ for (const ev of ['add', 'change', 'unlink']) server.watcher.on(ev, assetEvent);
126
154
  server.watcher.on('change', (file) => {
127
155
  const m = /sheets[\\/]([^\\/]+)[\\/]workbook\.json$/.exec(file);
128
156
  if (!m) return;
@@ -179,13 +207,50 @@ function apiPlugin(root) {
179
207
  const { id, title, data, from } = JSON.parse(await readBody(req));
180
208
  if (!ID.test(id ?? '')) return json(res, 400, { error: 'Use lowercase letters, numbers and dashes.' });
181
209
  if (existsSync(workbookFile(root, id))) return json(res, 409, { error: 'That name is taken.' });
210
+ const fromAssets = from !== undefined && ID.test(from) ? assetsDir(root, from) : null;
182
211
  let book = blankWorkbook(title || id);
183
212
  if (from !== undefined) book = { ...readWorkbook(root, from).data, ...(title ? { title } : {}) };
184
213
  else if (data !== undefined) book = { ...data, title: title || data.title || id };
185
214
  const { text } = await writeWorkbook(root, id, book, { create: true });
186
215
  ownWrites.set(id, text);
216
+ if (fromAssets && existsSync(fromAssets)) cpSync(fromAssets, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
187
217
  return json(res, 201, { id });
188
218
  }
219
+ // ---------- assets ----------
220
+ if (url.pathname.startsWith('/__api/assets')) {
221
+ const scope = url.searchParams.get('scope') ?? '';
222
+ const name = url.searchParams.get('name') ?? '';
223
+ if (url.pathname === '/__api/assets' && req.method === 'GET') return json(res, 200, { scope, assets: listAssets(root, scope) });
224
+ if (url.pathname === '/__api/assets/file' && req.method === 'GET') {
225
+ const body = readAsset(root, scope, name);
226
+ const ext = name.split('.').pop().toLowerCase();
227
+ res.writeHead(200, {
228
+ 'content-type': MIME[ext] ?? 'application/octet-stream',
229
+ // An SVG or note from the folder is shown, never run: no scripts, no requests, its own origin.
230
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
231
+ 'x-content-type-options': 'nosniff',
232
+ 'cache-control': 'no-store',
233
+ ...(url.searchParams.has('download') ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}` } : {}),
234
+ });
235
+ return res.end(body);
236
+ }
237
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
238
+ if (url.pathname === '/__api/assets/note' && req.method === 'PUT') {
239
+ const b = JSON.parse(await readBody(req));
240
+ return json(res, 200, writeNote(root, b.scope, b.name, b.text));
241
+ }
242
+ if (url.pathname === '/__api/assets/upload' && req.method === 'POST') {
243
+ assetPath(root, scope, name);
244
+ return json(res, 201, saveImage(root, scope, name, await readBytes(req)));
245
+ }
246
+ if (url.pathname === '/__api/assets/chart' && req.method === 'POST') {
247
+ const b = JSON.parse(await readBody(req));
248
+ return json(res, 201, await renderChart(root, b.workbook, b));
249
+ }
250
+ if (url.pathname === '/__api/assets' && req.method === 'DELETE') return json(res, 200, trashAsset(root, scope, name));
251
+ return json(res, 404, { error: 'not found' });
252
+ }
253
+
189
254
  const m = /^\/__api\/workbooks\/([^/]+)$/.exec(url.pathname);
190
255
  if (m && ID.test(m[1])) {
191
256
  const id = m[1];
@@ -14,8 +14,10 @@ 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.
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.
17
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.
18
20
  5. **Check.** Run `open-spreadsheet check` (or the `check` tool) and fix what it reports.
19
- 6. **Report** which notes you applied, which you left and why.
21
+ 6. **Report** which notes you applied, which you left and why, and any chart images or notes you saved in Assets.
20
22
 
21
23
  The editor reloads as you write, so the person sees each change and the note disappear.
@@ -35,7 +35,7 @@ Each workbook is `sheets/<id>/workbook.json`. The grid editor at `pnpm dev` relo
35
35
  | `hiddenRows` / `hiddenCols` | Rows (1-based numbers) and columns (letters) hidden by hand |
36
36
  | `names` (top level, beside `sheets`) | Defined names: `{ "Sales": "Orders!$F$2:$F$200" }`, used in formulas as `=SUM(Sales)`; each points at a cell or range with its sheet |
37
37
  | `protected` | Ranges a person locked, `["A1:D1", "F2"]`. The editor and MCP refuse to change them; never edit or remove them yourself — ask the person |
38
- | `charts` | Charts over the grid: `[{ "id": "sales", "type": "bar", "range": "A1:C13", "title": "Sales by month", "x": 520, "y": 0, "w": 440, "h": 270 }]` — `type` is `bar`, `line` or `pie`; the range's first column holds the categories and its first row the series names; `x`/`y`/`w`/`h` are px at 100% zoom from the sheet's top-left |
38
+ | `charts` | Not used for new work: charts are images in Assets (below). An older workbook may still have charts here; the editor offers to move them |
39
39
  | `color` | The sheet tab's colour |
40
40
  | `notes` | A1 address → a note left on the cell (see the `apply-notes` skill) |
41
41
  | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`), `top` (`rank`, optional `percent`, `bottom`), `average` (optional `below`, `equal`), `iconSet` (`set` as Excel names it — `3Arrows`, `3TrafficLights1`, `4Rating`, `5Arrows`…; optional `thresholds` in percent, `reverse`). All of them go to and from .xlsx |
@@ -74,3 +74,13 @@ Math and trigonometry (SUM, SUMIF(S), SUMPRODUCT, SUBTOTAL, ROUND/ROUNDUP/ROUNDD
74
74
 
75
75
  1. Run `open-spreadsheet check` (or the MCP `check` tool). It lists formulas that show `#NAME?`, `#REF!`, `#CIRC!`, `#VALUE!` and malformed entries.
76
76
  2. Read the result back with the MCP `read_range` tool, or open the workbook in the viewer.
77
+
78
+ ## Assets: chart images and notes
79
+
80
+ Each workbook has an assets folder, `sheets/<id>/assets/`, and the workspace has a shared one, `assets/`. They hold:
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.
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
+
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.
86
+
@@ -45,6 +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
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.
49
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).
50
51