@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/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 { type ChartSource, type ChartStyle, chartData, chartFile, chartSvg } from './charts.ts';
|
|
23
|
+
import { createAssetsView, createNotesView, fileStem, 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,22 @@ 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
|
+
// Sheet · Assets · Notes: one workbook, three views of it.
|
|
165
|
+
type View = 'sheet' | 'assets' | 'notes';
|
|
166
|
+
let view: View = 'sheet';
|
|
167
|
+
const viewSwitch = el('div', 'view-switch');
|
|
168
|
+
viewSwitch.setAttribute('role', 'tablist');
|
|
169
|
+
const viewButtons = (['sheet', 'assets', 'notes'] as const).map((v) => {
|
|
170
|
+
const b = el('button', '', { sheet: T.viewSheet, assets: T.viewAssets, notes: T.viewNotes }[v]);
|
|
171
|
+
b.type = 'button';
|
|
172
|
+
b.dataset.view = v;
|
|
173
|
+
b.setAttribute('role', 'tab');
|
|
174
|
+
b.setAttribute('aria-selected', String(v === 'sheet'));
|
|
175
|
+
b.addEventListener('mousedown', (e) => e.preventDefault());
|
|
176
|
+
b.addEventListener('click', () => void setView(v));
|
|
177
|
+
viewSwitch.append(b);
|
|
178
|
+
return b;
|
|
179
|
+
});
|
|
163
180
|
const notesBadge = el('span', 'badge');
|
|
164
181
|
notesBtn.append(notesBadge);
|
|
165
182
|
const downloadBtn = el('button', 'btn primary');
|
|
@@ -167,7 +184,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
167
184
|
downloadBtn.append(icon('download', 15), el('span', '', T.download), icon('chevronDown', 14));
|
|
168
185
|
const fileMark = el('span', 'brand-mark');
|
|
169
186
|
fileMark.append(icon('sheet', 14));
|
|
170
|
-
head.append(back, fileMark, titleBtn, status, el('div', 'grow'), notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
|
|
187
|
+
head.append(back, fileMark, titleBtn, status, viewSwitch, el('div', 'grow'), notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
|
|
171
188
|
|
|
172
189
|
// Toolbar
|
|
173
190
|
const toolbar = el('div', 'toolbar');
|
|
@@ -291,8 +308,47 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
291
308
|
tabsBar.append(addTab, listTabs, tabs, el('div', 'grow'), stats, zoomSel);
|
|
292
309
|
|
|
293
310
|
const gridWrap = el('div', 'grid-wrap');
|
|
311
|
+
// Charts are images in Assets now; a workbook that still has charts on its grid is offered the move.
|
|
312
|
+
const legacyBar = el('div', 'legacy-charts');
|
|
313
|
+
const assets = createAssetsView({
|
|
314
|
+
bookId: id,
|
|
315
|
+
charts: {
|
|
316
|
+
sheets: () => data.sheets.map((s) => s.name),
|
|
317
|
+
selection: () => {
|
|
318
|
+
const s = selection();
|
|
319
|
+
const r = s.r0 === s.r1 && s.c0 === s.c1 ? currentRegion(active) : s;
|
|
320
|
+
return { sheet: name(), range: rangeText(r) };
|
|
321
|
+
},
|
|
322
|
+
draw: (source, look) => chartImageSvg(source, look),
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
const notes = createNotesView({ bookId: id });
|
|
326
|
+
assets.el.hidden = true;
|
|
327
|
+
notes.el.hidden = true;
|
|
294
328
|
gridWrap.append(grid, findbar);
|
|
295
|
-
root.append(head, toolbar, fbar, gridWrap, tabsBar);
|
|
329
|
+
root.append(head, toolbar, fbar, legacyBar, gridWrap, tabsBar, assets.el, notes.el);
|
|
330
|
+
/** Switches what the workbook shows; leaving Notes saves the note being written. */
|
|
331
|
+
async function setView(next: View) {
|
|
332
|
+
if (next === view) return;
|
|
333
|
+
if (view === 'notes') await notes.flush();
|
|
334
|
+
if (editing) commitEdit();
|
|
335
|
+
view = next;
|
|
336
|
+
for (const b of viewButtons) b.setAttribute('aria-selected', String(b.dataset.view === next));
|
|
337
|
+
const sheetOn = next === 'sheet';
|
|
338
|
+
for (const n of [toolbar, fbar, gridWrap, tabsBar]) n.hidden = !sheetOn;
|
|
339
|
+
if (sheetOn) paintLegacyBar();
|
|
340
|
+
else legacyBar.hidden = true;
|
|
341
|
+
assets.el.hidden = next !== 'assets';
|
|
342
|
+
notes.el.hidden = next !== 'notes';
|
|
343
|
+
closeMenus();
|
|
344
|
+
if (next === 'assets') await assets.refresh();
|
|
345
|
+
else if (next === 'notes') await notes.refresh();
|
|
346
|
+
else {
|
|
347
|
+
layout();
|
|
348
|
+
render();
|
|
349
|
+
editor.focus();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
296
352
|
app.replaceChildren(root);
|
|
297
353
|
document.body.append(popup);
|
|
298
354
|
|
|
@@ -2636,16 +2692,48 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
2636
2692
|
window.addEventListener('mousemove', move);
|
|
2637
2693
|
window.addEventListener('mouseup', up);
|
|
2638
2694
|
}
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
const
|
|
2643
|
-
const
|
|
2695
|
+
// ---------- chart images (Assets) ----------
|
|
2696
|
+
/** A range drawn as a standalone SVG that remembers its source; '' when the sheet or range is gone. */
|
|
2697
|
+
function chartImageSvg(source: ChartSource, look?: ChartStyle): string {
|
|
2698
|
+
const r = parseRange(source.range);
|
|
2699
|
+
const sheetName = data.sheets.find((s) => s.name === source.sheet)?.name;
|
|
2700
|
+
if (!r || !sheetName) return '';
|
|
2701
|
+
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)));
|
|
2702
|
+
const spec: ChartSpec = { id: 'asset', type: source.type, range: source.range, ...(source.title ? { title: source.title } : {}), x: 0, y: 0, w: 720, h: 405 };
|
|
2703
|
+
return chartFile(spec, chartData(cells), 720, 405, source, look);
|
|
2704
|
+
}
|
|
2705
|
+
/** The toolbar's chart button: the new-chart dialog, starting from the selection. */
|
|
2706
|
+
async function newChartFromSheet() {
|
|
2707
|
+
const saved = await assets.newChart();
|
|
2708
|
+
editor.focus();
|
|
2709
|
+
if (saved) toast(T.chartSaved(saved.replace(/\.svg$/i, '')));
|
|
2710
|
+
}
|
|
2711
|
+
/** Turns every chart on the grid into an image in Assets, then takes them off the grid (one undo step). */
|
|
2712
|
+
async function moveChartsToAssets() {
|
|
2713
|
+
const all = data.sheets.flatMap((sh) => (sh.charts ?? []).map((c) => ({ sheet: sh.name, c })));
|
|
2714
|
+
if (!all.length) return;
|
|
2715
|
+
try {
|
|
2716
|
+
for (const { sheet: sn, c } of all) {
|
|
2717
|
+
await uploadAsset(id, `${fileStem(c.title ?? '', `${sn}-${c.range}`)}.svg`, chartImageSvg({ sheet: sn, range: c.range, type: c.type, ...(c.title ? { title: c.title } : {}) }));
|
|
2718
|
+
}
|
|
2719
|
+
} catch (e) {
|
|
2720
|
+
toast((e as Error).message);
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2644
2723
|
change(() => {
|
|
2645
|
-
const sh
|
|
2646
|
-
sh.charts = [...(sh.charts ?? []), spec];
|
|
2724
|
+
for (const sh of data.sheets) delete sh.charts;
|
|
2647
2725
|
}, { relayout: false });
|
|
2648
|
-
|
|
2726
|
+
paintLegacyBar();
|
|
2727
|
+
toast(T.chartsMoved(all.length));
|
|
2728
|
+
}
|
|
2729
|
+
function paintLegacyBar() {
|
|
2730
|
+
const n = data.sheets.reduce((k, sh) => k + (sh.charts?.length ?? 0), 0);
|
|
2731
|
+
legacyBar.hidden = n === 0;
|
|
2732
|
+
if (!n) return;
|
|
2733
|
+
const move = el('button', 'btn primary', T.moveChartsToAssets);
|
|
2734
|
+
move.type = 'button';
|
|
2735
|
+
move.addEventListener('click', () => void moveChartsToAssets());
|
|
2736
|
+
legacyBar.replaceChildren(icon('chart', 14), el('span', '', T.chartsOnGrid(n)), move);
|
|
2649
2737
|
}
|
|
2650
2738
|
function chartMenu(id: string, at: { x: number; y: number } | HTMLElement) {
|
|
2651
2739
|
const spec = chartSpec(id);
|
|
@@ -3184,17 +3272,8 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
3184
3272
|
);
|
|
3185
3273
|
};
|
|
3186
3274
|
tb.cond.addEventListener('click', () => conditionalMenu(tb.cond));
|
|
3187
|
-
tb.chart.
|
|
3188
|
-
|
|
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
|
-
),
|
|
3197
|
-
);
|
|
3275
|
+
tb.chart.title = T.newChart;
|
|
3276
|
+
tb.chart.addEventListener('click', () => void newChartFromSheet());
|
|
3198
3277
|
tb.border.addEventListener('click', () => showMenu(borderItems(), tb.border, () => editor.focus()));
|
|
3199
3278
|
tb.filter.addEventListener('click', () => {
|
|
3200
3279
|
if (!sheet().filter) return toggleFilter();
|
|
@@ -3403,7 +3482,10 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
3403
3482
|
cmd(T.gRowsCols, T.hideCols(s.c1 - s.c0 + 1), () => hideCols(s.c0, s.c1), 'eyeOff', undefined, 'hide columns'),
|
|
3404
3483
|
cmd(T.gRowsCols, T.unhideRows, () => unhideRows(s.r0, s.r1), 'eye', undefined, 'unhide show rows'),
|
|
3405
3484
|
cmd(T.gRowsCols, T.unhideCols, () => unhideCols(s.c0, s.c1), 'eye', undefined, 'unhide show columns'),
|
|
3406
|
-
|
|
3485
|
+
cmd(T.chart, T.newChart, () => void newChartFromSheet(), 'chart', undefined, 'chart graph image asset bar line pie'),
|
|
3486
|
+
cmd(T.gView, T.viewSheet, () => void setView('sheet'), 'sheet', undefined, 'sheet grid table view'),
|
|
3487
|
+
cmd(T.gView, T.viewAssets, () => void setView('assets'), 'chart', undefined, 'assets images charts pictures view'),
|
|
3488
|
+
cmd(T.gView, T.viewNotes, () => void setView('notes'), 'file', undefined, 'notes markdown context view'),
|
|
3407
3489
|
cmd(T.gFormat, T.conditional, () => conditionalMenu(tb.cond), 'conditional', undefined, 'conditional formatting color scale data bar highlight'),
|
|
3408
3490
|
cmd(T.gEdit, T.sortDesc, () => sortBy(true), 'sortDesc', undefined, 'sort descending'),
|
|
3409
3491
|
...['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN'].map((f) => cmd(T.autosum, `${f}( )`, () => autosum(f), 'sigma', undefined, `autosum ${f.toLowerCase()}`)),
|
|
@@ -3489,7 +3571,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
3489
3571
|
// Keys pressed while a button (a tab, a toolbar button) has focus still reach the grid.
|
|
3490
3572
|
const onWindowKey = (e: KeyboardEvent) => {
|
|
3491
3573
|
const t = e.target as HTMLElement;
|
|
3492
|
-
if (t === editor || t.closest('input, textarea, select, .dialog, .menu') || !root.isConnected) return;
|
|
3574
|
+
if (t === editor || t.closest('input, textarea, select, .dialog, .menu') || !root.isConnected || view !== 'sheet') return;
|
|
3493
3575
|
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey) {
|
|
3494
3576
|
editor.focus();
|
|
3495
3577
|
return; // the character lands in the editor
|
|
@@ -4182,6 +4264,14 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
4182
4264
|
status.textContent = T.saved;
|
|
4183
4265
|
}
|
|
4184
4266
|
import.meta.hot?.on('open-spreadsheet:changed', onExternal);
|
|
4267
|
+
// An agent (or apply-notes) wrote an image or note: the open panel shows it.
|
|
4268
|
+
const onAssets = (d: { scope: string }) => {
|
|
4269
|
+
if (d.scope !== id && d.scope !== 'shared') return;
|
|
4270
|
+
if (view === 'assets') void assets.refresh();
|
|
4271
|
+
else if (view === 'notes') void notes.refresh();
|
|
4272
|
+
};
|
|
4273
|
+
import.meta.hot?.on('open-spreadsheet:assets', onAssets);
|
|
4274
|
+
paintLegacyBar();
|
|
4185
4275
|
|
|
4186
4276
|
const onBeforeUnload = () => {
|
|
4187
4277
|
if (saveTimer) void flush();
|
|
@@ -4199,6 +4289,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
4199
4289
|
notePop.remove();
|
|
4200
4290
|
closeMenus();
|
|
4201
4291
|
import.meta.hot?.off?.('open-spreadsheet:changed', onExternal);
|
|
4292
|
+
import.meta.hot?.off?.('open-spreadsheet:assets', onAssets);
|
|
4202
4293
|
teardown = null;
|
|
4203
4294
|
};
|
|
4204
4295
|
const onHash = () => {
|
package/app/charts.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { chartData, niceTicks } from './charts.ts';
|
|
2
|
+
import { BUILTIN_STYLES, chartData, chartFile, chartSvg, cleanStyle, findStyle, niceTicks } from './charts.ts';
|
|
3
3
|
|
|
4
4
|
describe('chart axes', () => {
|
|
5
5
|
it('reach past the largest value and below the smallest', () => {
|
|
@@ -23,3 +23,64 @@ describe('chart data', () => {
|
|
|
23
23
|
expect(chartData([['Qty'], [3], [5]])).toEqual({ categories: ['1', '2'], series: [{ name: 'Qty', values: [3, 5] }] });
|
|
24
24
|
});
|
|
25
25
|
});
|
|
26
|
+
|
|
27
|
+
describe('every chart type', () => {
|
|
28
|
+
const cells = [
|
|
29
|
+
['月', '營收', '成長率'],
|
|
30
|
+
['1月', 120, 0.05],
|
|
31
|
+
['2月', 150, 0.25],
|
|
32
|
+
['3月', 90, -0.4],
|
|
33
|
+
];
|
|
34
|
+
const draw = (type: Parameters<typeof chartSvg>[0]['type'], data = chartData(cells as never)) =>
|
|
35
|
+
chartSvg({ id: 'c', type, range: 'A1:C4', title: 'T', x: 0, y: 0, w: 1, h: 1 }, data, 720, 405);
|
|
36
|
+
|
|
37
|
+
it('draws each type without a broken number', () => {
|
|
38
|
+
for (const t of ['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'] as const) {
|
|
39
|
+
const svg = draw(t);
|
|
40
|
+
expect(svg, t).toMatch(/^<svg /);
|
|
41
|
+
expect(svg, t).not.toMatch(/NaN|Infinity|undefined/);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('gives each its shape', () => {
|
|
46
|
+
// horizontal: 3 months × 2 series, each bar with its tooltip (the legend swatches have none)
|
|
47
|
+
expect((draw('barH').match(/<rect [^>]*><title>/g) ?? []).length).toBe(6);
|
|
48
|
+
expect(draw('doughnut')).toContain('class="c-total"');
|
|
49
|
+
expect(draw('area')).toContain('fill-opacity="0.16"');
|
|
50
|
+
// stacked: one column per month, its parts on top of each other
|
|
51
|
+
const xs = [...draw('stacked').matchAll(/<rect x="([\d.]+)" y="[\d.]+" width="[\d.]+" height="[\d.]+" fill/g)].map((m) => m[1]);
|
|
52
|
+
expect(new Set(xs).size).toBe(3);
|
|
53
|
+
// combo: the rate is on its own right-hand axis
|
|
54
|
+
expect(draw('combo')).toMatch(/<text x="(6[89]\d|7\d\d)[\d.]*" y="[\d.]+" class="c-tick">/);
|
|
55
|
+
// scatter: the first numeric column is x
|
|
56
|
+
const pts = chartData([
|
|
57
|
+
['單價', '數量'],
|
|
58
|
+
[100, 3],
|
|
59
|
+
[200, 5],
|
|
60
|
+
[300, 2],
|
|
61
|
+
] as never);
|
|
62
|
+
expect((draw('scatter', pts).match(/<circle /g) ?? []).length).toBe(3);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('a chart file takes its style: colours, background, type and grid', () => {
|
|
67
|
+
const data = chartData([['', 'A', 'B'], ['x', 1, 2], ['y', 3, 4]] as never);
|
|
68
|
+
const spec = { id: 'c', type: 'bar' as const, range: 'A1:C3', x: 0, y: 0, w: 1, h: 1 };
|
|
69
|
+
const mono = findStyle('mono');
|
|
70
|
+
const svg = chartFile(spec, data, 720, 405, undefined, mono);
|
|
71
|
+
expect(svg).toContain(`fill="${mono.colors[0]}"`);
|
|
72
|
+
expect(svg).toContain('.c-grid{stroke:none');
|
|
73
|
+
expect(svg).toContain('monospace');
|
|
74
|
+
expect(chartFile(spec, data, 720, 405, undefined, findStyle('night'))).toContain('<rect width="100%" height="100%" fill="#15181e"/>');
|
|
75
|
+
// a style that is gone falls back to Default
|
|
76
|
+
expect(findStyle('gone', [])).toBe(BUILTIN_STYLES[0]);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('a style read from a file is checked field by field', () => {
|
|
80
|
+
expect(cleanStyle({ id: 'Bad Id' })).toBeNull();
|
|
81
|
+
const s = cleanStyle({ id: 'brand', colors: ['#ABCDEF', 'red', '#123'], radius: 99, font: 'comic', background: 'url(x)' })!;
|
|
82
|
+
expect(s.colors).toEqual(['#abcdef']);
|
|
83
|
+
expect(s.radius).toBe(8);
|
|
84
|
+
expect(s.font).toBe('sans');
|
|
85
|
+
expect(s.background).toBe('#ffffff');
|
|
86
|
+
});
|