@open-spreadsheet/core 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app/book.ts CHANGED
@@ -19,8 +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, chartFile, chartSvg } from './charts.ts';
23
- import { createAssetsPanel, uploadAsset } from './assets.ts';
22
+ import { type ChartSource, type ChartStyle, chartData, chartFile, chartSvg } from './charts.ts';
23
+ import { createAssetsView, createNotesView, fileStem, uploadAsset } from './assets.ts';
24
24
  import { printHtml } from './print.ts';
25
25
  import { api } from './home.ts';
26
26
  import { helpFor, suggest } from './help.ts';
@@ -159,18 +159,38 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
159
159
  render();
160
160
  });
161
161
  const helpBtn = iconButton('keyboard', T.shortcuts, () => showShortcuts());
162
+ // Also in ⌘K: the first to go when the header is narrow (an editor side panel).
163
+ helpBtn.classList.add('head-extra');
164
+ themeBtn.classList.add('head-extra');
162
165
  const paletteBtn = iconButton('list', `${T.palette.replace('…', '')} (${MOD}K)`, () => void openPalette());
163
166
  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');
167
+ // Sheet · Assets · Notes: one workbook, three views of it.
168
+ type View = 'sheet' | 'assets' | 'notes';
169
+ let view: View = 'sheet';
170
+ const viewSwitch = el('div', 'view-switch');
171
+ viewSwitch.setAttribute('role', 'tablist');
172
+ const viewButtons = (['sheet', 'assets', 'notes'] as const).map((v) => {
173
+ const b = el('button', '', { sheet: T.viewSheet, assets: T.viewAssets, notes: T.viewNotes }[v]);
174
+ b.type = 'button';
175
+ b.dataset.view = v;
176
+ b.setAttribute('role', 'tab');
177
+ b.setAttribute('aria-selected', String(v === 'sheet'));
178
+ b.addEventListener('mousedown', (e) => e.preventDefault());
179
+ b.addEventListener('click', () => void setView(v));
180
+ viewSwitch.append(b);
181
+ return b;
182
+ });
166
183
  const notesBadge = el('span', 'badge');
167
184
  notesBtn.append(notesBadge);
168
185
  const downloadBtn = el('button', 'btn primary');
169
186
  downloadBtn.type = 'button';
170
- downloadBtn.append(icon('download', 15), el('span', '', T.download), icon('chevronDown', 14));
187
+ const downloadChevron = icon('chevronDown', 14);
188
+ downloadChevron.classList.add('btn-chevron');
189
+ downloadBtn.append(icon('download', 15), el('span', 'btn-label', T.download), downloadChevron);
190
+ downloadBtn.title = T.download;
171
191
  const fileMark = el('span', 'brand-mark');
172
192
  fileMark.append(icon('sheet', 14));
173
- head.append(back, fileMark, titleBtn, status, el('div', 'grow'), assetsBtn, notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
193
+ head.append(back, fileMark, titleBtn, status, viewSwitch, el('div', 'grow'), notesBtn, paletteBtn, findBtn, helpBtn, themeBtn, downloadBtn);
174
194
 
175
195
  // Toolbar
176
196
  const toolbar = el('div', 'toolbar');
@@ -296,9 +316,49 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
296
316
  const gridWrap = el('div', 'grid-wrap');
297
317
  // Charts are images in Assets now; a workbook that still has charts on its grid is offered the move.
298
318
  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);
319
+ const assets = createAssetsView({
320
+ bookId: id,
321
+ charts: {
322
+ sheets: () => data.sheets.map((s) => s.name),
323
+ selection: () => {
324
+ const s = selection();
325
+ const r = s.r0 === s.r1 && s.c0 === s.c1 ? currentRegion(active) : s;
326
+ return { sheet: name(), range: rangeText(r) };
327
+ },
328
+ draw: (source, look) => chartImageSvg(source, look),
329
+ },
330
+ });
331
+ const notes = createNotesView({ bookId: id });
332
+ assets.el.hidden = true;
333
+ notes.el.hidden = true;
334
+ gridWrap.append(grid, findbar);
335
+ root.append(head, toolbar, fbar, legacyBar, gridWrap, tabsBar, assets.el, notes.el);
336
+ // A toolbar wider than the window scrolls; fade its edge while there is more to the right.
337
+ const toolbarEdge = () => toolbar.classList.toggle('more-right', toolbar.scrollLeft + toolbar.clientWidth < toolbar.scrollWidth - 1);
338
+ toolbar.addEventListener('scroll', toolbarEdge, { passive: true });
339
+ new ResizeObserver(toolbarEdge).observe(toolbar);
340
+ /** Switches what the workbook shows; leaving Notes saves the note being written. */
341
+ async function setView(next: View) {
342
+ if (next === view) return;
343
+ if (view === 'notes') await notes.flush();
344
+ if (editing) commitEdit();
345
+ view = next;
346
+ for (const b of viewButtons) b.setAttribute('aria-selected', String(b.dataset.view === next));
347
+ const sheetOn = next === 'sheet';
348
+ for (const n of [toolbar, fbar, gridWrap, tabsBar]) n.hidden = !sheetOn;
349
+ if (sheetOn) paintLegacyBar();
350
+ else legacyBar.hidden = true;
351
+ assets.el.hidden = next !== 'assets';
352
+ notes.el.hidden = next !== 'notes';
353
+ closeMenus();
354
+ if (next === 'assets') await assets.refresh();
355
+ else if (next === 'notes') await notes.refresh();
356
+ else {
357
+ layout();
358
+ render();
359
+ editor.focus();
360
+ }
361
+ }
302
362
  app.replaceChildren(root);
303
363
  document.body.append(popup);
304
364
 
@@ -2643,53 +2703,20 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2643
2703
  window.addEventListener('mouseup', up);
2644
2704
  }
2645
2705
  // ---------- 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 '';
2706
+ /** A range drawn as a standalone SVG that remembers its source; '' when the sheet or range is gone. */
2707
+ function chartImageSvg(source: ChartSource, look?: ChartStyle): string {
2708
+ const r = parseRange(source.range);
2709
+ const sheetName = data.sheets.find((s) => s.name === source.sheet)?.name;
2710
+ if (!r || !sheetName) return '';
2656
2711
  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));
2712
+ const spec: ChartSpec = { id: 'asset', type: source.type, range: source.range, ...(source.title ? { title: source.title } : {}), x: 0, y: 0, w: 720, h: 405 };
2713
+ return chartFile(spec, chartData(cells), 720, 405, source, look);
2659
2714
  }
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) {
2662
- const s = selection();
2663
- const r = s.r0 === s.r1 && s.c0 === s.c1 ? currentRegion(active) : s;
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
- });
2715
+ /** The toolbar's chart button: the new-chart dialog, starting from the selection. */
2716
+ async function newChartFromSheet() {
2717
+ const saved = await assets.newChart();
2672
2718
  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
- );
2719
+ if (saved) toast(T.chartSaved(saved.replace(/\.svg$/i, '')));
2693
2720
  }
2694
2721
  /** Turns every chart on the grid into an image in Assets, then takes them off the grid (one undo step). */
2695
2722
  async function moveChartsToAssets() {
@@ -2697,7 +2724,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2697
2724
  if (!all.length) return;
2698
2725
  try {
2699
2726
  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 ?? ''));
2727
+ await uploadAsset(id, `${fileStem(c.title ?? '', `${sn}-${c.range}`)}.svg`, chartImageSvg({ sheet: sn, range: c.range, type: c.type, ...(c.title ? { title: c.title } : {}) }));
2701
2728
  }
2702
2729
  } catch (e) {
2703
2730
  toast((e as Error).message);
@@ -2707,7 +2734,6 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2707
2734
  for (const sh of data.sheets) delete sh.charts;
2708
2735
  }, { relayout: false });
2709
2736
  paintLegacyBar();
2710
- await assets.showSaved(id, '');
2711
2737
  toast(T.chartsMoved(all.length));
2712
2738
  }
2713
2739
  function paintLegacyBar() {
@@ -2717,7 +2743,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
2717
2743
  const move = el('button', 'btn primary', T.moveChartsToAssets);
2718
2744
  move.type = 'button';
2719
2745
  move.addEventListener('click', () => void moveChartsToAssets());
2720
- legacyBar.replaceChildren(icon('chart', 14), el('span', '', T.chartsOnGrid(n)), el('div', 'grow'), move);
2746
+ legacyBar.replaceChildren(icon('chart', 14), el('span', '', T.chartsOnGrid(n)), move);
2721
2747
  }
2722
2748
  function chartMenu(id: string, at: { x: number; y: number } | HTMLElement) {
2723
2749
  const spec = chartSpec(id);
@@ -3256,10 +3282,8 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3256
3282
  );
3257
3283
  };
3258
3284
  tb.cond.addEventListener('click', () => conditionalMenu(tb.cond));
3259
- tb.chart.title = T.newChartImage;
3260
- tb.chart.addEventListener('click', () =>
3261
- chartImageMenu(tb.chart),
3262
- );
3285
+ tb.chart.title = T.newChart;
3286
+ tb.chart.addEventListener('click', () => void newChartFromSheet());
3263
3287
  tb.border.addEventListener('click', () => showMenu(borderItems(), tb.border, () => editor.focus()));
3264
3288
  tb.filter.addEventListener('click', () => {
3265
3289
  if (!sheet().filter) return toggleFilter();
@@ -3468,8 +3492,10 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3468
3492
  cmd(T.gRowsCols, T.hideCols(s.c1 - s.c0 + 1), () => hideCols(s.c0, s.c1), 'eyeOff', undefined, 'hide columns'),
3469
3493
  cmd(T.gRowsCols, T.unhideRows, () => unhideRows(s.r0, s.r1), 'eye', undefined, 'unhide show rows'),
3470
3494
  cmd(T.gRowsCols, T.unhideCols, () => unhideCols(s.c0, s.c1), 'eye', undefined, 'unhide show columns'),
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'),
3495
+ cmd(T.chart, T.newChart, () => void newChartFromSheet(), 'chart', undefined, 'chart graph image asset bar line pie'),
3496
+ cmd(T.gView, T.viewSheet, () => void setView('sheet'), 'sheet', undefined, 'sheet grid table view'),
3497
+ cmd(T.gView, T.viewAssets, () => void setView('assets'), 'chart', undefined, 'assets images charts pictures view'),
3498
+ cmd(T.gView, T.viewNotes, () => void setView('notes'), 'file', undefined, 'notes markdown context view'),
3473
3499
  cmd(T.gFormat, T.conditional, () => conditionalMenu(tb.cond), 'conditional', undefined, 'conditional formatting color scale data bar highlight'),
3474
3500
  cmd(T.gEdit, T.sortDesc, () => sortBy(true), 'sortDesc', undefined, 'sort descending'),
3475
3501
  ...['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN'].map((f) => cmd(T.autosum, `${f}( )`, () => autosum(f), 'sigma', undefined, `autosum ${f.toLowerCase()}`)),
@@ -3555,7 +3581,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
3555
3581
  // Keys pressed while a button (a tab, a toolbar button) has focus still reach the grid.
3556
3582
  const onWindowKey = (e: KeyboardEvent) => {
3557
3583
  const t = e.target as HTMLElement;
3558
- if (t === editor || t.closest('input, textarea, select, .dialog, .menu') || !root.isConnected) return;
3584
+ if (t === editor || t.closest('input, textarea, select, .dialog, .menu') || !root.isConnected || view !== 'sheet') return;
3559
3585
  if (e.key.length === 1 && !e.metaKey && !e.ctrlKey) {
3560
3586
  editor.focus();
3561
3587
  return; // the character lands in the editor
@@ -4250,7 +4276,9 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
4250
4276
  import.meta.hot?.on('open-spreadsheet:changed', onExternal);
4251
4277
  // An agent (or apply-notes) wrote an image or note: the open panel shows it.
4252
4278
  const onAssets = (d: { scope: string }) => {
4253
- if (assets.isOpen() && (d.scope === id || d.scope === 'shared')) void assets.refresh();
4279
+ if (d.scope !== id && d.scope !== 'shared') return;
4280
+ if (view === 'assets') void assets.refresh();
4281
+ else if (view === 'notes') void notes.refresh();
4254
4282
  };
4255
4283
  import.meta.hot?.on('open-spreadsheet:assets', onAssets);
4256
4284
  paintLegacyBar();
@@ -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
+ });