@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/style.css CHANGED
@@ -189,6 +189,160 @@ 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
+ /* Sheet · Assets · Notes */
194
+ .view-switch { display: inline-flex; margin-left: 10px; padding: 2px; border-radius: 8px; background: var(--muted); }
195
+ .view-switch button { height: 26px; padding: 0 14px; border: 0; border-radius: 6px; background: none; color: var(--muted-foreground); font: inherit; font-size: 12.5px; font-weight: 500; cursor: pointer; transition: color 120ms; }
196
+ .view-switch button:hover { color: var(--foreground); }
197
+ .view-switch button[aria-selected='true'] { background: var(--background); color: var(--foreground); box-shadow: 0 1px 2px rgb(0 0 0 / 0.12), 0 0 0 0.5px var(--border); }
198
+ .book > [hidden] { display: none !important; }
199
+
200
+ /* Assets and Notes: a library — sidebar on the left, the page on the right. */
201
+ .lib-view { flex: 1; min-height: 0; display: grid; grid-template-columns: 252px minmax(0, 1fr); background: var(--background); position: relative; }
202
+ .asset-view.dropping::after { content: ''; position: absolute; inset: 12px; border: 2px dashed var(--select); border-radius: 12px; background: color-mix(in srgb, var(--select) 6%, transparent); pointer-events: none; z-index: 5; }
203
+ .lib-side { display: flex; flex-direction: column; min-height: 0; overflow: auto; padding: 14px 10px; border-right: 1px solid var(--border); background: var(--muted); }
204
+ .lib-head { display: flex; align-items: center; gap: 2px; padding: 4px 4px 4px 8px; }
205
+ .lib-head h2 { margin: 0; font-size: 15px; font-weight: 650; }
206
+ .lib-search { display: flex; align-items: center; gap: 6px; margin: 8px 2px 6px; padding: 0 10px; height: 32px; border-radius: 8px; background: var(--background); box-shadow: 0 0 0 1px var(--border); color: var(--muted-foreground); }
207
+ .lib-search:focus-within { box-shadow: 0 0 0 1.5px var(--foreground); }
208
+ .lib-search input { flex: 1; min-width: 0; border: 0; outline: none; background: none; color: var(--foreground); font: inherit; font-size: 13px; }
209
+ .lib-search input::-webkit-search-cancel-button { cursor: pointer; }
210
+ .lib-nav { display: flex; flex-direction: column; gap: 1px; margin: 4px 0 6px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
211
+ .lib-divider { height: 1px; margin: 6px 4px; background: var(--border); }
212
+ .lib-tab { display: flex; align-items: center; gap: 9px; height: 30px; padding: 0 10px; border: 0; border-radius: 6px; background: none; color: var(--muted-foreground); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
213
+ .lib-tab:hover { background: var(--accent); color: var(--foreground); }
214
+ .lib-tab[aria-selected='true'] { background: var(--accent); color: var(--foreground); font-weight: 550; }
215
+ .lib-list { display: flex; flex-direction: column; gap: 1px; }
216
+ .lib-group h3 { margin: 14px 10px 6px; font-size: 11.5px; font-weight: 600; letter-spacing: 0.04em; color: var(--muted-foreground); }
217
+ .lib-item { display: flex; align-items: center; gap: 10px; width: 100%; padding: 7px 10px; border: 0; border-radius: 6px; background: none; color: var(--foreground); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
218
+ .lib-item:hover { background: var(--accent); }
219
+ .lib-item.on { background: var(--background); box-shadow: 0 0 0 1px var(--border); font-weight: 550; }
220
+ .lib-thumb { flex: none; width: 44px; height: 25px; object-fit: contain; border-radius: 4px; background: #fff; box-shadow: 0 0 0 1px var(--border); }
221
+ .lib-item-text { display: flex; flex-direction: column; min-width: 0; flex: 1; }
222
+ .lib-item-top { display: flex; align-items: center; gap: 6px; min-width: 0; }
223
+ .lib-item-top svg { flex: none; color: #f9ab00; }
224
+ .lib-item-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
225
+ .lib-item-meta { display: block; margin-top: 2px; font-size: 11.5px; font-weight: 400; color: var(--muted-foreground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
226
+ .lib-item-meta:empty { display: none; }
227
+ .lib-item-meta mark { background: color-mix(in srgb, #f9ab00 35%, transparent); color: inherit; border-radius: 2px; }
228
+ .lib-empty { margin: 14px 10px; font-size: 12.5px; color: var(--muted-foreground); }
229
+ .lib-star.on { color: #f9ab00; }
230
+
231
+ .lib-main { min-width: 0; min-height: 0; overflow: auto; }
232
+ .lib-page { max-width: 1180px; margin: 0 auto; padding: 22px 32px 48px; }
233
+ .lib-page-head { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
234
+ .lib-page-head h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
235
+ .lib-page-head .btn { height: 32px; }
236
+ .lib-detail-head { display: flex; align-items: center; gap: 6px; padding-bottom: 12px; }
237
+ .lib-scope { flex: none; font-size: 11.5px; padding: 2px 8px; border-radius: 99px; background: var(--muted); color: var(--muted-foreground); }
238
+ .lib-detail-head .icon-link, .asset-tools .icon-link { display: inline-grid; place-items: center; width: 28px; height: 28px; border-radius: 6px; color: var(--muted-foreground); }
239
+ .lib-detail-head .icon-link:hover { background: var(--muted); color: var(--foreground); }
240
+ .lib-empty-state { display: flex; flex-direction: column; align-items: center; gap: 12px; margin: 14vh auto 0; color: var(--muted-foreground); }
241
+ .lib-empty-state h3 { margin: 0; font-size: 15px; font-weight: 550; color: var(--foreground); }
242
+
243
+ .asset-section h3, .note-section h3 { margin: 22px 0 10px; font-size: 11.5px; font-weight: 600; letter-spacing: 0.04em; color: var(--muted-foreground); }
244
+ .asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; }
245
+ .asset-card { position: relative; margin: 0; }
246
+ .asset-frame { display: block; width: 100%; aspect-ratio: 16 / 9; padding: 0; overflow: hidden; border: 1px solid var(--border); border-radius: 10px; background: #fff; cursor: pointer; transition: box-shadow 150ms, border-color 150ms; }
247
+ .asset-frame img { display: block; width: 100%; height: 100%; object-fit: contain; }
248
+ .asset-card:hover .asset-frame { border-color: color-mix(in srgb, var(--foreground) 25%, var(--border)); box-shadow: 0 6px 18px -10px rgb(0 0 0 / 0.35); }
249
+ .asset-card.fresh .asset-frame { border-color: var(--select); box-shadow: 0 0 0 3px color-mix(in srgb, var(--select) 22%, transparent); }
250
+ .asset-tools { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 2px; border-radius: 8px; background: var(--background); box-shadow: 0 0 0 0.5px var(--border), 0 4px 12px -6px rgb(0 0 0 / 0.3); opacity: 0; transition: opacity 120ms; }
251
+ .asset-card:hover .asset-tools, .asset-card:focus-within .asset-tools { opacity: 1; }
252
+ @media (hover: none) { .asset-tools { opacity: 1; } }
253
+ .asset-card figcaption { display: flex; flex-direction: column; gap: 2px; padding: 10px 2px 0; }
254
+ .asset-title { display: flex; align-items: center; gap: 5px; font-size: 13.5px; font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
255
+ .asset-title svg { flex: none; color: #f9ab00; }
256
+ .asset-meta { margin: 0; font-size: 12px; color: var(--muted-foreground); font-variant-numeric: tabular-nums; }
257
+ .asset-detail { display: flex; flex-direction: column; min-height: 100%; padding-top: 18px; }
258
+ .asset-style-pick { width: auto; height: 30px; max-width: 200px; font-size: 12.5px; }
259
+ .asset-stage { display: block; width: 100%; padding: 0; border: 1px solid var(--border); border-radius: 12px; background: #fff; overflow: hidden; cursor: zoom-in; }
260
+ .asset-stage img { display: block; width: 100%; max-height: calc(100vh - 260px); object-fit: contain; }
261
+ .asset-detail-head { padding-bottom: 2px; }
262
+ .asset-title-input { flex: 1 1 auto; min-width: 0; max-width: 640px; margin-left: -8px; padding: 3px 8px; border: 0; border-radius: 6px; background: none; color: var(--foreground); font: 650 22px/1.3 var(--sans); letter-spacing: -0.01em; outline: none; text-overflow: ellipsis; }
263
+ .asset-title-input:hover { background: var(--muted); }
264
+ .asset-title-input:focus { background: var(--background); box-shadow: 0 0 0 1.5px var(--select); }
265
+ .asset-detail-meta { margin: 0 0 16px; }
266
+
267
+ /* Chart styles: a gallery, and one style with its settings beside a preview. */
268
+ .style-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 18px; margin-top: 18px; }
269
+ .style-card { display: flex; flex-direction: column; padding: 0; border: 1px solid var(--border); border-radius: 12px; background: var(--background); color: var(--foreground); font: inherit; text-align: left; overflow: hidden; cursor: pointer; transition: box-shadow 150ms, border-color 150ms; }
270
+ .style-card:hover { border-color: color-mix(in srgb, var(--foreground) 25%, var(--border)); box-shadow: 0 6px 18px -10px rgb(0 0 0 / 0.35); }
271
+ .style-card img { display: block; width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-bottom: 1px solid var(--border); }
272
+ .style-foot { display: flex; align-items: center; gap: 8px; padding: 10px 12px; }
273
+ .style-name { font-size: 13.5px; font-weight: 550; }
274
+ .style-tags { display: flex; gap: 4px; flex: 1; }
275
+ .style-tag { font-size: 11px; padding: 1px 7px; border-radius: 99px; background: var(--muted); color: var(--muted-foreground); }
276
+ .style-tag.on { background: color-mix(in srgb, var(--select) 14%, transparent); color: var(--select); font-weight: 550; }
277
+ .style-swatches { display: flex; flex: none; }
278
+ .style-swatches i { width: 12px; height: 12px; border-radius: 50%; box-shadow: 0 0 0 1.5px var(--background); }
279
+ .style-swatches i + i { margin-left: -3px; }
280
+ .lib-item .style-swatches i { width: 10px; height: 10px; }
281
+ .style-page .lib-page-head { gap: 6px; }
282
+ .style-split { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(260px, 1fr); gap: 28px; margin-top: 18px; align-items: start; }
283
+ @media (max-width: 980px) { .style-split { grid-template-columns: 1fr; } }
284
+ .style-previews { display: grid; gap: 14px; }
285
+ .style-previews img { display: block; width: 100%; border-radius: 10px; box-shadow: 0 0 0 1px var(--border); }
286
+ .style-form { display: flex; flex-direction: column; gap: 16px; }
287
+ .style-form.locked { opacity: 0.75; }
288
+ .style-row { display: flex; flex-direction: column; gap: 7px; font-size: 12.5px; color: var(--muted-foreground); }
289
+ .style-row > span { font-weight: 550; }
290
+ .style-row input[type='checkbox'] { align-self: flex-start; width: 16px; height: 16px; }
291
+ .style-colors { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
292
+ .style-color { width: 30px; height: 30px; padding: 0; border: 0; border-radius: 8px; background: none; cursor: pointer; }
293
+ .style-color::-webkit-color-swatch-wrapper { padding: 0; }
294
+ .style-color::-webkit-color-swatch { border: 0; border-radius: 7px; box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.12); }
295
+ .style-color:disabled { cursor: default; }
296
+ .style-pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
297
+ .style-swatch { display: flex; align-items: center; gap: 8px; color: var(--foreground); }
298
+ .style-range { width: 100%; accent-color: var(--foreground); }
299
+
300
+ /* Notes: Home shows them as cards; one opens beside the list. */
301
+ .note-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; }
302
+ .note-card { display: flex; flex-direction: column; gap: 6px; min-height: 128px; padding: 14px 16px; border: 1px solid var(--border); border-radius: 12px; background: var(--background); color: var(--foreground); font: inherit; text-align: left; cursor: pointer; transition: box-shadow 150ms, border-color 150ms; }
303
+ .note-card:hover { border-color: color-mix(in srgb, var(--foreground) 25%, var(--border)); box-shadow: 0 6px 18px -10px rgb(0 0 0 / 0.35); }
304
+ .note-card-title { display: flex; align-items: center; gap: 6px; font-size: 14.5px; font-weight: 650; }
305
+ .note-card-title svg { flex: none; color: #f9ab00; }
306
+ .note-card-text { flex: 1; font-size: 13px; line-height: 1.55; color: var(--muted-foreground); display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
307
+ .note-card-meta { font-size: 11.5px; color: var(--muted-foreground); }
308
+ .note-main { display: flex; flex-direction: column; }
309
+ .note-main > .lib-page { width: 100%; }
310
+ .note-main > .note-head, .note-main > .note-doc, .note-main > .note-text, .note-main > .lib-empty-state { width: 100%; max-width: 920px; margin-left: auto; margin-right: auto; padding-left: 32px; padding-right: 32px; }
311
+ .note-main > .note-head { padding-top: 18px; }
312
+ .note-state { font-size: 12px; color: var(--muted-foreground); margin-right: 4px; }
313
+ .note-text { flex: 1; min-height: 0; padding-top: 4px; padding-bottom: 4px; border: 0; resize: none; background: transparent; color: var(--foreground); font: 13.5px/1.7 var(--mono); outline: none; }
314
+ .note-head .on:not(.lib-star) { background: var(--muted); color: var(--foreground); }
315
+
316
+ .lightbox { position: fixed; inset: 0; z-index: 200; display: grid; place-items: center; padding: 40px; background: rgb(0 0 0 / 0.6); cursor: zoom-out; animation: fade 120ms ease-out; }
317
+ .lightbox figure { margin: 0; max-width: min(1200px, 92vw); }
318
+ .lightbox img { display: block; max-width: 100%; max-height: 80vh; border-radius: 10px; background: #fff; box-shadow: 0 20px 60px -20px rgb(0 0 0 / 0.6); }
319
+ .lightbox figcaption { margin-top: 12px; text-align: center; color: #fff; font-size: 13.5px; }
320
+ @keyframes fade { from { opacity: 0; } }
321
+
322
+ /* The note as it reads: Medium-like type, edited in place. */
323
+ .note-doc { flex: 1; min-height: 0; overflow: auto; padding: 4px 2px 40px; outline: none; color: var(--foreground); font: 16px/1.75 var(--sans); word-break: break-word; }
324
+ .note-doc:empty::before { content: attr(data-placeholder); color: var(--muted-foreground); pointer-events: none; }
325
+ .note-doc > * { margin: 0 0 0.9em; }
326
+ .note-doc h1 { font-size: 1.75em; line-height: 1.3; font-weight: 700; letter-spacing: -0.015em; margin-top: 0.4em; }
327
+ .note-doc h2 { font-size: 1.35em; line-height: 1.35; font-weight: 650; margin-top: 1.2em; }
328
+ .note-doc h3 { font-size: 1.12em; font-weight: 650; margin-top: 1em; }
329
+ .note-doc ul, .note-doc ol { padding-left: 1.5em; }
330
+ .note-doc li { margin: 0.2em 0; }
331
+ .note-doc blockquote { padding: 0.1em 0 0.1em 1em; border-left: 3px solid var(--foreground); color: var(--muted-foreground); }
332
+ .note-doc blockquote p { margin: 0; }
333
+ .note-doc code { padding: 0.12em 0.35em; border-radius: 4px; background: var(--muted); font: 0.86em var(--mono); }
334
+ .note-doc pre { padding: 12px 14px; border-radius: 8px; background: var(--muted); overflow: auto; }
335
+ .note-doc pre code { padding: 0; background: none; font-size: 13px; line-height: 1.6; white-space: pre; }
336
+ .note-doc hr { border: 0; text-align: center; margin: 1.6em 0; }
337
+ .note-doc hr::after { content: '···'; letter-spacing: 0.6em; color: var(--muted-foreground); }
338
+ .note-doc a { color: var(--link, #1a73e8); text-decoration: underline; text-underline-offset: 2px; }
339
+ .note-doc img.md-img { display: block; max-width: 100%; margin: 0.2em 0; border-radius: 10px; background: #fff; box-shadow: 0 0 0 1px var(--border); }
340
+ .note-doc img.md-img::selection { background: none; }
341
+ .note-doc p:has(> img.md-img:only-child) { margin-bottom: 1.2em; }
342
+
343
+ .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); }
344
+ .legacy-charts[hidden] { display: none; }
345
+ .legacy-charts .btn { height: 26px; padding: 0 10px; font-size: 12px; }
192
346
  .grid { position: absolute; inset: 0; overflow: hidden; background: var(--sheet); color: var(--cell-fg); --z: 1; user-select: none; -webkit-user-select: none; }
193
347
  .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
348
  .corner.picked { background: var(--head-picked); }
package/app/types.ts CHANGED
@@ -95,7 +95,9 @@ export interface WorkbookSummary {
95
95
  updatedAt: string;
96
96
  }
97
97
 
98
- export type ChartType = 'bar' | 'line' | 'pie';
98
+ /** Column, bar (horizontal), stacked column, line, area, pie, doughnut, scatter, and combo (columns + lines on a right axis). */
99
+ export type ChartType = 'bar' | 'barH' | 'stacked' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter' | 'combo';
100
+
99
101
 
100
102
  export interface ChartSpec {
101
103
  id: string;
package/assets.js ADDED
@@ -0,0 +1,232 @@
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, opts = {}) {
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
+ // A redrawn chart keeps its name; anything else new gets a number instead of replacing a file.
87
+ const free = opts.replace ? name : freeName(root, scope, name);
88
+ writeAtomic(assetPath(root, scope, free), bytes);
89
+ return { scope, name: free };
90
+ }
91
+
92
+ /** Moves an asset to the scope's .trash folder; nothing is erased. */
93
+ export function trashAsset(root, scope, name) {
94
+ const file = assetPath(root, scope, name);
95
+ if (!existsSync(file)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
96
+ const trash = path.join(path.dirname(file), '.trash');
97
+ mkdirSync(trash, { recursive: true });
98
+ const to = path.join(trash, `${Date.now()}-${name}`);
99
+ renameSync(file, to);
100
+ return { scope, name, trashedTo: path.relative(root, to) };
101
+ }
102
+
103
+ /** Renames an image or note in place, keeping its kind; a star follows it. */
104
+ export function renameAsset(root, scope, name, to) {
105
+ const from = assetPath(root, scope, name);
106
+ const dest = assetPath(root, scope, to);
107
+ if (!existsSync(from)) throw new OpsError('not_found', `No asset ${name} in ${scope}`);
108
+ const ext = (n) => n.split('.').pop().toLowerCase();
109
+ if (ext(name) !== ext(to)) throw new OpsError('bad_name', `Keep the .${ext(name)} ending.`);
110
+ // Only a change of case may land on the "same" file (macOS folders ignore case).
111
+ if (to !== name && existsSync(dest) && to.toLowerCase() !== name.toLowerCase()) throw new OpsError('exists', `${to} is taken in ${scope}`);
112
+ renameSync(from, dest);
113
+ const favs = readFavorites(root);
114
+ if (favs.some((f) => f.scope === scope && f.name === name)) {
115
+ writeAtomic(favouritesFile(root), `${JSON.stringify(favs.map((f) => (f.scope === scope && f.name === name ? { scope, name: to } : f)), null, 2)}\n`);
116
+ }
117
+ return { scope, from: name, name: to };
118
+ }
119
+
120
+ const slug = (text) =>
121
+ String(text)
122
+ .normalize('NFKC')
123
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
124
+ .replace(/^-+|-+$/g, '')
125
+ .slice(0, 60);
126
+
127
+ /**
128
+ * Draws a chart from a workbook range and saves it as an SVG in the workbook's
129
+ * assets (or the shared ones): the same picture the editor shows.
130
+ */
131
+ export async function renderChart(root, workbook, opts) {
132
+ const { data } = readWorkbook(root, workbook);
133
+ const sheet = opts.sheet ? data.sheets.find((s) => s.name.toLowerCase() === String(opts.sheet).toLowerCase()) : data.sheets[0];
134
+ if (!sheet) throw new OpsError('no_sheet', `No sheet "${opts.sheet}". Sheets: ${data.sheets.map((s) => s.name).join(', ')}`);
135
+ const type = opts.type ?? 'bar';
136
+ if (!['bar', 'barH', 'stacked', 'line', 'area', 'pie', 'doughnut', 'scatter', 'combo'].includes(type)) throw new OpsError('bad_type', 'type is one of bar, barH, stacked, line, area, pie, doughnut, scatter, combo');
137
+ const r = parseRangeText(opts.range);
138
+ if (!r) throw new OpsError('bad_range', `Not a range: ${opts.range}`);
139
+ 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.');
140
+ const wb = Workbook.fromJSON(data);
141
+ const cells = [];
142
+ for (let row = r.r0; row <= r.r1; row++) {
143
+ const line = [];
144
+ for (let col = r.c0; col <= r.c1; col++) line.push(wb.value(sheet.name, row, col));
145
+ cells.push(line);
146
+ }
147
+ const { chartData, chartFile, findStyle, BUILTIN_STYLES } = await charts();
148
+ const own = await readChartStyles(root);
149
+ if (opts.style && !own.styles.some((s) => s.id === opts.style) && !BUILTIN_STYLES.some((s) => s.id === opts.style)) {
150
+ throw new OpsError('bad_style', `No chart style "${opts.style}". Styles: ${[...BUILTIN_STYLES, ...own.styles].map((s) => s.id).join(', ')}`);
151
+ }
152
+ const spec = { id: 'asset', type, range: opts.range, title: opts.title ?? '', x: 0, y: 0, w: 720, h: 405 };
153
+ // The source rides in the file, so the editor can redraw it when the numbers change.
154
+ // No style named: it follows the workspace's default, now and when redrawn.
155
+ const source = { sheet: sheet.name, range: String(opts.range).toUpperCase(), type, ...(opts.title ? { title: String(opts.title) } : {}), ...(opts.style ? { style: String(opts.style) } : {}) };
156
+ const svg = chartFile(spec, chartData(cells), Number(opts.width) || 720, Number(opts.height) || 405, source, findStyle(opts.style ?? own.default, own.styles));
157
+ const scope = opts.scope ?? workbook;
158
+ const wanted = opts.name ? (/\.svg$/i.test(opts.name) ? opts.name : `${opts.name}.svg`) : `${slug(opts.title || `${sheet.name}-${opts.range}`) || 'chart'}.svg`;
159
+ assetPath(root, scope, wanted);
160
+ const name = opts.replace ? wanted : freeName(root, scope, wanted);
161
+ writeAtomic(assetPath(root, scope, name), svg);
162
+ return { scope, name, sheet: sheet.name, range: opts.range, type, bytes: Buffer.byteLength(svg) };
163
+ }
164
+
165
+ // ---------- chart styles ----------
166
+ // The workspace's own looks for chart files, beside the built-in ones. Shared
167
+ // (assets/chart-styles.json, in git) so teammates and agents draw alike.
168
+ const stylesFile = (root) => path.join(root, 'assets', 'chart-styles.json');
169
+
170
+ /** { default, styles }: the style new charts follow, and the workspace's own styles. */
171
+ export async function readChartStyles(root) {
172
+ const { cleanStyle, BUILTIN_STYLES } = await charts();
173
+ let raw = {};
174
+ try {
175
+ raw = JSON.parse(readFileSync(stylesFile(root), 'utf8'));
176
+ } catch {
177
+ // none yet
178
+ }
179
+ const seen = new Set(BUILTIN_STYLES.map((s) => s.id));
180
+ const styles = [];
181
+ for (const s of Array.isArray(raw?.styles) ? raw.styles : []) {
182
+ const c = cleanStyle(s);
183
+ if (c && !seen.has(c.id)) {
184
+ seen.add(c.id);
185
+ styles.push(c);
186
+ }
187
+ }
188
+ const def = typeof raw?.default === 'string' && seen.has(raw.default) ? raw.default : 'default';
189
+ return { default: def, styles };
190
+ }
191
+
192
+ /** Replaces the workspace's styles and default; bad entries are refused, not dropped. */
193
+ export async function writeChartStyles(root, next) {
194
+ const { cleanStyle, BUILTIN_STYLES } = await charts();
195
+ const builtin = new Set(BUILTIN_STYLES.map((s) => s.id));
196
+ const ids = new Set();
197
+ const styles = (Array.isArray(next?.styles) ? next.styles : []).map((s) => {
198
+ const c = cleanStyle(s);
199
+ if (!c) throw new OpsError('bad_style', 'A style needs an id of lowercase letters, numbers and dashes.');
200
+ if (builtin.has(c.id) || ids.has(c.id)) throw new OpsError('bad_style', `The style id "${c.id}" is taken.`);
201
+ ids.add(c.id);
202
+ return c;
203
+ });
204
+ const def = typeof next?.default === 'string' ? next.default : 'default';
205
+ if (!builtin.has(def) && !ids.has(def)) throw new OpsError('bad_style', `No chart style "${def}" to make the default.`);
206
+ const out = { default: def, styles };
207
+ writeAtomic(stylesFile(root), `${JSON.stringify(out, null, 2)}
208
+ `);
209
+ return out;
210
+ }
211
+
212
+ // ---------- favourite notes ----------
213
+ // A person's pick, not part of the workbook: kept in .open-spreadsheet/ (git-ignored).
214
+ const favouritesFile = (root) => path.join(root, '.open-spreadsheet', 'favorites.json');
215
+
216
+ /** The starred notes, as { scope, name }, in the order they were starred. */
217
+ export function readFavorites(root) {
218
+ try {
219
+ const list = JSON.parse(readFileSync(favouritesFile(root), 'utf8'));
220
+ return Array.isArray(list) ? list.filter((f) => f && typeof f.scope === 'string' && typeof f.name === 'string') : [];
221
+ } catch {
222
+ return [];
223
+ }
224
+ }
225
+
226
+ export function setFavorite(root, scope, name, on) {
227
+ assetPath(root, scope, name);
228
+ const rest = readFavorites(root).filter((f) => !(f.scope === scope && f.name === name));
229
+ const next = on ? [...rest, { scope, name }] : rest;
230
+ writeAtomic(favouritesFile(root), `${JSON.stringify(next, null, 2)}\n`);
231
+ return next;
232
+ }