@open-spreadsheet/core 0.1.1 → 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 +223 -0
- package/app/book.ts +166 -23
- package/app/charts.ts +16 -0
- package/app/features.test.ts +42 -0
- package/app/features.ts +69 -3
- package/app/i18n-more.ts +66 -0
- package/app/i18n.ts +44 -0
- package/app/io.ts +41 -1
- package/app/style.css +29 -0
- package/app/types.ts +16 -1
- package/assets.js +138 -0
- package/dist/charts.js +178 -0
- package/mcp.js +108 -7
- package/ops.js +9 -1
- package/package.json +6 -3
- package/server.js +67 -2
- package/skills/apply-notes/SKILL.md +3 -1
- package/skills/sheet-authoring/SKILL.md +13 -2
- package/templates/AGENTS.md +2 -0
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
|
@@ -18,8 +18,9 @@ import {
|
|
|
18
18
|
parseFormula,
|
|
19
19
|
type Node as FormulaNode,
|
|
20
20
|
} from '@open-spreadsheet/engine';
|
|
21
|
-
import { BLANK, columnValues, conditionalLook, type CellLook, DEFAULT_HIGHLIGHT, filteredRows, shiftRange, validationAt } from './features.ts';
|
|
22
|
-
import { chartData, chartSvg } from './charts.ts';
|
|
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';
|
|
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
|
-
|
|
295
|
-
|
|
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
|
|
|
@@ -526,7 +532,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
526
532
|
}
|
|
527
533
|
const input = wb.inputAt(name, r, c);
|
|
528
534
|
const style = styleAt(r, c);
|
|
529
|
-
if (!input && !style?.bg && !style?.border && !style?.check && !noteAt(r, c) && !isFilterHead(r, c)) continue;
|
|
535
|
+
if (!input && !style?.bg && !style?.border && !style?.check && !noteAt(r, c) && !isFilterHead(r, c) && !isProtectedCell(sheet(), r, c)) continue;
|
|
530
536
|
let w = colX[c + 1]! - colX[c]!;
|
|
531
537
|
const s = input ? show(r, c) : null;
|
|
532
538
|
const isText = s && (typeof s.v === 'string' || s.v === null) && !style?.wrap && (style?.align ?? 'left') === 'left';
|
|
@@ -617,6 +623,11 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
617
623
|
if (look.bg) d.style.background = look.bg;
|
|
618
624
|
if (look.color) d.style.color = look.color;
|
|
619
625
|
if (look.b) d.classList.add('b');
|
|
626
|
+
if (look.icon) {
|
|
627
|
+
const ic = el('span', 'cf-icon', look.icon.glyph);
|
|
628
|
+
ic.style.color = look.icon.color;
|
|
629
|
+
d.prepend(ic);
|
|
630
|
+
}
|
|
620
631
|
if (look.bar) {
|
|
621
632
|
const bar = el('span', 'data-bar');
|
|
622
633
|
bar.style.width = `${Math.round(look.bar.pct * 100)}%`;
|
|
@@ -632,6 +643,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
632
643
|
d.classList.add('filter-head');
|
|
633
644
|
}
|
|
634
645
|
if (merged || spills) d.classList.add('solid');
|
|
646
|
+
if (isProtectedCell(sheet(), row, col)) d.classList.add('locked');
|
|
635
647
|
if (noteAt(row, col)) {
|
|
636
648
|
const mark = el('span', 'note-mark');
|
|
637
649
|
// On a spilling cell the mark belongs to the cell's own corner, not the spill's.
|
|
@@ -1057,6 +1069,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1057
1069
|
if (s.hiddenRows?.length) out.hiddenRows = s.hiddenRows;
|
|
1058
1070
|
if (s.hiddenCols?.length) out.hiddenCols = s.hiddenCols;
|
|
1059
1071
|
if (s.charts?.length) out.charts = s.charts;
|
|
1072
|
+
if (s.protected?.length) out.protected = s.protected;
|
|
1060
1073
|
return out;
|
|
1061
1074
|
}),
|
|
1062
1075
|
};
|
|
@@ -1132,9 +1145,21 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1132
1145
|
}
|
|
1133
1146
|
}
|
|
1134
1147
|
/** Every change: undo point, the change, then layout, paint and save. */
|
|
1148
|
+
/** Thrown by a write into a protected range; `change` undoes the whole step and says why. */
|
|
1149
|
+
class LockedError extends Error {}
|
|
1135
1150
|
function change(fn: () => void, opts: { relayout?: boolean } = {}) {
|
|
1136
1151
|
checkpoint();
|
|
1137
|
-
|
|
1152
|
+
try {
|
|
1153
|
+
fn();
|
|
1154
|
+
} catch (e) {
|
|
1155
|
+
if (!(e instanceof LockedError)) throw e;
|
|
1156
|
+
const before = undoStack.pop();
|
|
1157
|
+
if (before) restore(before);
|
|
1158
|
+
layout();
|
|
1159
|
+
render();
|
|
1160
|
+
toast(T.protectedRefused);
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1138
1163
|
if (opts.relayout !== false) layout();
|
|
1139
1164
|
render();
|
|
1140
1165
|
save();
|
|
@@ -1143,6 +1168,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1143
1168
|
// ---------- cell edits ----------
|
|
1144
1169
|
const name = () => sname();
|
|
1145
1170
|
function setInputs(cells: { row: number; col: number; input: string }[]) {
|
|
1171
|
+
if (cells.some((c) => isProtectedCell(sheet(), c.row, c.col))) throw new LockedError();
|
|
1146
1172
|
wb.setCells(name(), cells);
|
|
1147
1173
|
}
|
|
1148
1174
|
function forEachCell(r: Rect, fn: (row: number, col: number) => void) {
|
|
@@ -1152,6 +1178,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1152
1178
|
for (let row = r.r0; row <= r1; row++) for (let col = r.c0; col <= c1; col++) fn(row, col);
|
|
1153
1179
|
}
|
|
1154
1180
|
function setStyle(r: Rect, patch: Partial<CellStyle> | null) {
|
|
1181
|
+
if (touchesProtected(sheet(), r)) throw new LockedError();
|
|
1155
1182
|
const sh = sheet();
|
|
1156
1183
|
sh.styles ??= {};
|
|
1157
1184
|
for (let row = r.r0; row <= r.r1; row++) {
|
|
@@ -1178,6 +1205,38 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1178
1205
|
const on = !styleAt(active.row, active.col)?.[k];
|
|
1179
1206
|
change(() => setStyle(styleRect(), { [k]: on }), { relayout: false });
|
|
1180
1207
|
}
|
|
1208
|
+
// ---------- protection ----------
|
|
1209
|
+
/** Protects the selection: one range added, the ones it covers folded in. */
|
|
1210
|
+
function protectSelection() {
|
|
1211
|
+
const s = selection();
|
|
1212
|
+
const text = rangeText(s);
|
|
1213
|
+
checkpoint();
|
|
1214
|
+
const sh = sheet();
|
|
1215
|
+
const rest = (sh.protected ?? []).filter((t) => {
|
|
1216
|
+
const r = parseRange(t);
|
|
1217
|
+
return !(r && r.r0 >= s.r0 && r.r1 <= s.r1 && r.c0 >= s.c0 && r.c1 <= s.c1);
|
|
1218
|
+
});
|
|
1219
|
+
sh.protected = [...rest, text];
|
|
1220
|
+
render();
|
|
1221
|
+
save();
|
|
1222
|
+
toast(T.protectedOn(text));
|
|
1223
|
+
}
|
|
1224
|
+
/** Removes every protected range that touches the selection. */
|
|
1225
|
+
function unprotectSelection() {
|
|
1226
|
+
const s = selection();
|
|
1227
|
+
const sh = sheet();
|
|
1228
|
+
const keep = (sh.protected ?? []).filter((t) => {
|
|
1229
|
+
const r = parseRange(t);
|
|
1230
|
+
return !(r && r.r0 <= s.r1 && s.r0 <= r.r1 && r.c0 <= s.c1 && s.c0 <= r.c1);
|
|
1231
|
+
});
|
|
1232
|
+
if (keep.length === (sh.protected ?? []).length) return;
|
|
1233
|
+
checkpoint();
|
|
1234
|
+
sh.protected = keep.length ? keep : undefined;
|
|
1235
|
+
render();
|
|
1236
|
+
save();
|
|
1237
|
+
toast(T.protectedOff);
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1181
1240
|
// ---------- checkboxes ----------
|
|
1182
1241
|
const isCheck = (row: number, col: number) => Boolean(styleAt(row, col)?.check);
|
|
1183
1242
|
/**
|
|
@@ -1255,6 +1314,11 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1255
1314
|
// ---------- editing ----------
|
|
1256
1315
|
const draft = () => (editing?.source === 'bar' ? finput.value : editor.value);
|
|
1257
1316
|
function beginEdit(mode: 'enter' | 'edit', initial?: string, source: 'cell' | 'bar' = 'cell') {
|
|
1317
|
+
if (isProtectedCell(sheet(), active.row, active.col)) {
|
|
1318
|
+
// The key that tried to start the edit is already in the editor; drop it so it cannot reach a later edit.
|
|
1319
|
+
editor.value = '';
|
|
1320
|
+
return void toast(T.protectedRefused);
|
|
1321
|
+
}
|
|
1258
1322
|
const m = mergeOf(active.row, active.col);
|
|
1259
1323
|
if (m) {
|
|
1260
1324
|
active = { row: m.r0, col: m.c0 };
|
|
@@ -1756,6 +1820,13 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1756
1820
|
const range = shiftRange(r.range, axis, at, count);
|
|
1757
1821
|
return range ? [{ ...r, range }] : [];
|
|
1758
1822
|
});
|
|
1823
|
+
if (sh.protected) {
|
|
1824
|
+
sh.protected = sh.protected.flatMap((t) => {
|
|
1825
|
+
const range = shiftRange(t, axis, at, count);
|
|
1826
|
+
return range ? [range] : [];
|
|
1827
|
+
});
|
|
1828
|
+
if (!sh.protected.length) sh.protected = undefined;
|
|
1829
|
+
}
|
|
1759
1830
|
if (sh.validation) sh.validation = sh.validation.flatMap((v) => {
|
|
1760
1831
|
const range = shiftRange(v.range, axis, at, count);
|
|
1761
1832
|
return range ? [{ ...v, range }] : [];
|
|
@@ -1811,6 +1882,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1811
1882
|
});
|
|
1812
1883
|
}
|
|
1813
1884
|
function deleteRows(r0: number, r1: number) {
|
|
1885
|
+
if (touchesProtected(sheet(), { r0, c0: 0, r1, c1: MAX_COLS })) return toast(T.protectedRefused);
|
|
1814
1886
|
change(() => {
|
|
1815
1887
|
wb.insertRows(name(), r0, -(r1 - r0 + 1));
|
|
1816
1888
|
shiftMeta('row', r0, -(r1 - r0 + 1));
|
|
@@ -1818,6 +1890,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
1818
1890
|
moveTo({ row: r0, col: active.col });
|
|
1819
1891
|
}
|
|
1820
1892
|
function deleteCols(c0: number, c1: number) {
|
|
1893
|
+
if (touchesProtected(sheet(), { r0: 0, c0, r1: MAX_ROWS, c1 })) return toast(T.protectedRefused);
|
|
1821
1894
|
change(() => {
|
|
1822
1895
|
wb.insertColumns(name(), c0, -(c1 - c0 + 1));
|
|
1823
1896
|
shiftMeta('col', c0, -(c1 - c0 + 1));
|
|
@@ -2251,6 +2324,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
2251
2324
|
{ label: T.validation, icon: 'listCheck', action: () => void editValidation() },
|
|
2252
2325
|
isCheck(active.row, active.col) ? { label: T.removeCheckbox, icon: 'check', action: removeCheckboxes } : { label: T.insertCheckbox, icon: 'check', action: insertCheckboxes },
|
|
2253
2326
|
{ label: T.defineName, icon: 'pencil', action: () => void defineName() },
|
|
2327
|
+
touchesProtected(sheet(), selection()) ? { label: T.unprotectRange, icon: 'eye', action: unprotectSelection } : { label: T.protectRange, icon: 'eyeOff', action: protectSelection },
|
|
2254
2328
|
...(linkAt(active.row, active.col) ? [{ label: T.openLink, icon: 'arrowRight', action: () => openLink(linkAt(active.row, active.col)!) }] : []),
|
|
2255
2329
|
{ label: T.tracePrecedents, icon: 'arrowRight', disabled: !wb.inputAt(sname(), active.row, active.col).startsWith('='), action: () => traceCells('pre') },
|
|
2256
2330
|
{ label: T.traceDependents, icon: 'arrowLeft', action: () => traceCells('dep') },
|
|
@@ -2568,16 +2642,82 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
2568
2642
|
window.addEventListener('mousemove', move);
|
|
2569
2643
|
window.addEventListener('mouseup', up);
|
|
2570
2644
|
}
|
|
2571
|
-
|
|
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) {
|
|
2572
2662
|
const s = selection();
|
|
2573
2663
|
const r = s.r0 === s.r1 && s.c0 === s.c1 ? currentRegion(active) : s;
|
|
2574
|
-
const
|
|
2575
|
-
const
|
|
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
|
+
}
|
|
2576
2706
|
change(() => {
|
|
2577
|
-
const sh
|
|
2578
|
-
sh.charts = [...(sh.charts ?? []), spec];
|
|
2707
|
+
for (const sh of data.sheets) delete sh.charts;
|
|
2579
2708
|
}, { relayout: false });
|
|
2580
|
-
|
|
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);
|
|
2581
2721
|
}
|
|
2582
2722
|
function chartMenu(id: string, at: { x: number; y: number } | HTMLElement) {
|
|
2583
2723
|
const spec = chartSpec(id);
|
|
@@ -3116,16 +3256,9 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
3116
3256
|
);
|
|
3117
3257
|
};
|
|
3118
3258
|
tb.cond.addEventListener('click', () => conditionalMenu(tb.cond));
|
|
3259
|
+
tb.chart.title = T.newChartImage;
|
|
3119
3260
|
tb.chart.addEventListener('click', () =>
|
|
3120
|
-
|
|
3121
|
-
[
|
|
3122
|
-
{ label: T.chartBar, icon: 'chart', action: () => insertChart('bar') },
|
|
3123
|
-
{ label: T.chartLine, icon: 'lineChart', action: () => insertChart('line') },
|
|
3124
|
-
{ label: T.chartPie, icon: 'pieChart', action: () => insertChart('pie') },
|
|
3125
|
-
],
|
|
3126
|
-
tb.chart,
|
|
3127
|
-
() => editor.focus(),
|
|
3128
|
-
),
|
|
3261
|
+
chartImageMenu(tb.chart),
|
|
3129
3262
|
);
|
|
3130
3263
|
tb.border.addEventListener('click', () => showMenu(borderItems(), tb.border, () => editor.focus()));
|
|
3131
3264
|
tb.filter.addEventListener('click', () => {
|
|
@@ -3335,12 +3468,15 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
3335
3468
|
cmd(T.gRowsCols, T.hideCols(s.c1 - s.c0 + 1), () => hideCols(s.c0, s.c1), 'eyeOff', undefined, 'hide columns'),
|
|
3336
3469
|
cmd(T.gRowsCols, T.unhideRows, () => unhideRows(s.r0, s.r1), 'eye', undefined, 'unhide show rows'),
|
|
3337
3470
|
cmd(T.gRowsCols, T.unhideCols, () => unhideCols(s.c0, s.c1), 'eye', undefined, 'unhide show columns'),
|
|
3338
|
-
...(['bar', 'line', 'pie'] as const).map((k) => cmd(T.chart, `${T.
|
|
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'),
|
|
3339
3473
|
cmd(T.gFormat, T.conditional, () => conditionalMenu(tb.cond), 'conditional', undefined, 'conditional formatting color scale data bar highlight'),
|
|
3340
3474
|
cmd(T.gEdit, T.sortDesc, () => sortBy(true), 'sortDesc', undefined, 'sort descending'),
|
|
3341
3475
|
...['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN'].map((f) => cmd(T.autosum, `${f}( )`, () => autosum(f), 'sigma', undefined, `autosum ${f.toLowerCase()}`)),
|
|
3342
3476
|
cmd(T.gFormat, T.bold, () => toggleStyle('b'), 'bold', `${MOD}B`, 'bold'),
|
|
3343
3477
|
cmd(T.gEdit, T.insertCheckbox, insertCheckboxes, 'check', undefined, 'checkbox tick box todo'),
|
|
3478
|
+
cmd(T.gEdit, T.protectRange, protectSelection, 'eyeOff', undefined, 'protect lock range read only'),
|
|
3479
|
+
cmd(T.gEdit, T.unprotectRange, unprotectSelection, 'eye', undefined, 'unprotect unlock range'),
|
|
3344
3480
|
cmd(T.gEdit, T.removeCheckbox, removeCheckboxes, 'check', undefined, 'checkbox remove'),
|
|
3345
3481
|
...(['top', 'middle', 'bottom'] as const).map((v) => cmd(T.gFormat, `${T.valign}:${T[`valign_${v}`]}`, () => setValign(v), 'alignCenter', undefined, `vertical align ${v}`)),
|
|
3346
3482
|
cmd(T.gFormat, T.italic, () => toggleStyle('i'), 'italic', `${MOD}I`, 'italic'),
|
|
@@ -4112,6 +4248,12 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
4112
4248
|
status.textContent = T.saved;
|
|
4113
4249
|
}
|
|
4114
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();
|
|
4115
4257
|
|
|
4116
4258
|
const onBeforeUnload = () => {
|
|
4117
4259
|
if (saveTimer) void flush();
|
|
@@ -4129,6 +4271,7 @@ export async function openBook(app: HTMLElement, id: string): Promise<void> {
|
|
|
4129
4271
|
notePop.remove();
|
|
4130
4272
|
closeMenus();
|
|
4131
4273
|
import.meta.hot?.off?.('open-spreadsheet:changed', onExternal);
|
|
4274
|
+
import.meta.hot?.off?.('open-spreadsheet:assets', onAssets);
|
|
4132
4275
|
teardown = null;
|
|
4133
4276
|
};
|
|
4134
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
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import type { Scalar } from '../../engine/src/index.ts';
|
|
3
|
+
import { conditionalLook, iconCount, iconGlyph } from './features.ts';
|
|
4
|
+
import type { ConditionalRule, SheetData } from './types.ts';
|
|
5
|
+
|
|
6
|
+
// A1:A5 = 10, 20, 30, 40, 50
|
|
7
|
+
const values: Scalar[] = [10, 20, 30, 40, 50];
|
|
8
|
+
const lookFor = (rule: ConditionalRule) => {
|
|
9
|
+
const sheet: SheetData = { name: 'S', cells: {}, conditional: [rule] };
|
|
10
|
+
const look = conditionalLook(sheet, (row) => values[row] ?? null, { rows: 5, cols: 1 });
|
|
11
|
+
return values.map((_, row) => look(row, 0));
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
describe('Excel conditional formats from xlsx', () => {
|
|
15
|
+
it('Top and Bottom N, by count and by percent', () => {
|
|
16
|
+
expect(lookFor({ range: 'A1:A5', type: 'top', rank: 2 }).map(Boolean)).toEqual([false, false, false, true, true]);
|
|
17
|
+
expect(lookFor({ range: 'A1:A5', type: 'top', rank: 2, bottom: true }).map(Boolean)).toEqual([true, true, false, false, false]);
|
|
18
|
+
expect(lookFor({ range: 'A1:A5', type: 'top', rank: 40, percent: true }).map(Boolean)).toEqual([false, false, false, true, true]);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('above and below the average, with or without it', () => {
|
|
22
|
+
expect(lookFor({ range: 'A1:A5', type: 'average' }).map(Boolean)).toEqual([false, false, false, true, true]);
|
|
23
|
+
expect(lookFor({ range: 'A1:A5', type: 'average', below: true, equal: true }).map(Boolean)).toEqual([true, true, true, false, false]);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('icon sets pick a level by percent of the range, reversible', () => {
|
|
27
|
+
const arrows = lookFor({ range: 'A1:A5', type: 'iconSet', set: '3Arrows' }).map((l) => l?.icon?.glyph);
|
|
28
|
+
// 10..50 sit at 0, 25, 50, 75 and 100 percent; Excel's 3-icon cuts are 33 and 67.
|
|
29
|
+
expect(arrows).toEqual(['↓', '↓', '→', '↑', '↑']);
|
|
30
|
+
const reversed = lookFor({ range: 'A1:A5', type: 'iconSet', set: '3Arrows', reverse: true }).map((l) => l?.icon?.glyph);
|
|
31
|
+
expect(reversed).toEqual(['↑', '↑', '→', '↓', '↓']);
|
|
32
|
+
expect(lookFor({ range: 'A1:A5', type: 'iconSet', set: '3TrafficLights1', thresholds: [50, 90] }).map((l) => l?.icon?.color)).toEqual([
|
|
33
|
+
'#d93025',
|
|
34
|
+
'#d93025',
|
|
35
|
+
'#f9ab00',
|
|
36
|
+
'#f9ab00',
|
|
37
|
+
'#1e8e3e',
|
|
38
|
+
]);
|
|
39
|
+
expect(iconCount('5Rating')).toBe(5);
|
|
40
|
+
expect(iconGlyph('4Arrows', 3, 4).glyph).toBe('↑');
|
|
41
|
+
});
|
|
42
|
+
});
|