@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 ADDED
@@ -0,0 +1,1479 @@
1
+ // The Assets and Notes views beside a workbook's sheet: chart images and
2
+ // pictures (sheets/<id>/assets/*.svg|png|…) and Markdown notes
3
+ // (sheets/<id>/assets/*.md), each with the workspace's shared ones (assets/).
4
+ // Both are a library: a sidebar (Home, Recent, Favorites, All, search) and,
5
+ // on the right, the overview, one item, or — for Assets — the chart styles.
6
+ // A chart image carries where it came from, so it is redrawn from the current
7
+ // numbers (and in its style) whenever it is shown, its file kept in step for agents.
8
+ import { BUILTIN_STYLES, CHART_TYPES, type ChartSource, type ChartStyle, chartFile, chartSourceOf, findStyle } from './charts.ts';
9
+ import { locale, T } from './i18n.ts';
10
+ import { icon } from './icons.ts';
11
+ import { type ImageResolver, mdToHtml } from './markdown.ts';
12
+ import { createNoteEditor } from './note-editor.ts';
13
+ import type { ChartType } from './types.ts';
14
+ import { confirmDialog, downloadBlob, el, iconButton, pickFile, promptDialog, showMenu, toast } from './ui.ts';
15
+
16
+ export const SHARED = 'shared';
17
+
18
+ export interface AssetEntry {
19
+ name: string;
20
+ kind: 'image' | 'note';
21
+ size: number;
22
+ updatedAt: string;
23
+ title?: string;
24
+ }
25
+
26
+ const api = (path: string, params: Record<string, string>) => `/__api/assets${path}?${new URLSearchParams(params).toString()}`;
27
+
28
+ async function failure(res: Response): Promise<Error> {
29
+ try {
30
+ return new Error(((await res.json()) as { error?: string }).error ?? res.statusText);
31
+ } catch {
32
+ return new Error(res.statusText);
33
+ }
34
+ }
35
+
36
+ export async function listAssets(scope: string): Promise<AssetEntry[]> {
37
+ const res = await fetch(api('', { scope }));
38
+ if (!res.ok) return [];
39
+ return ((await res.json()) as { assets: AssetEntry[] }).assets;
40
+ }
41
+
42
+ /** Stores an image; a taken name comes back numbered unless `replace`. */
43
+ export async function uploadAsset(scope: string, name: string, body: Blob | string, type = 'image/svg+xml', replace = false): Promise<string> {
44
+ const res = await fetch(api('/upload', { scope, name, ...(replace ? { replace: '1' } : {}) }), { method: 'POST', headers: { 'content-type': type }, body });
45
+ if (!res.ok) throw await failure(res);
46
+ return ((await res.json()) as { name: string }).name;
47
+ }
48
+
49
+ async function readText(scope: string, name: string): Promise<string> {
50
+ const res = await fetch(api('/file', { scope, name, t: String(Date.now()) }));
51
+ return res.ok ? res.text() : '';
52
+ }
53
+
54
+ async function writeNote(scope: string, name: string, text: string): Promise<void> {
55
+ const res = await fetch('/__api/assets/note', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ scope, name, text }) });
56
+ if (!res.ok) throw await failure(res);
57
+ }
58
+
59
+ async function removeAsset(scope: string, name: string): Promise<void> {
60
+ const res = await fetch(api('', { scope, name }), { method: 'DELETE' });
61
+ if (!res.ok) throw await failure(res);
62
+ }
63
+
64
+ /** A file name from a title: letters of any script kept, the rest dashes. */
65
+ export const fileStem = (title: string, fallback: string) =>
66
+ title
67
+ .normalize('NFKC')
68
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
69
+ .replace(/^-+|-+$/g, '')
70
+ .slice(0, 60) || fallback;
71
+
72
+ const stem = (name: string) => name.replace(/\.[a-z]+$/i, '');
73
+
74
+ export const chartLabel = (t: ChartType) =>
75
+ ({ bar: T.chartBar, barH: T.chartBarH, stacked: T.chartStacked, line: T.chartLine, area: T.chartArea, pie: T.chartPie, doughnut: T.chartDoughnut, scatter: T.chartScatter, combo: T.chartCombo })[t];
76
+
77
+ /** An image as a PNG at twice its size, for slides and documents. */
78
+ async function toPng(src: string): Promise<Blob> {
79
+ const img = new Image();
80
+ img.src = src;
81
+ await img.decode();
82
+ const scale = 2;
83
+ const canvas = document.createElement('canvas');
84
+ canvas.width = Math.max(1, Math.round((img.naturalWidth || 720) * scale));
85
+ canvas.height = Math.max(1, Math.round((img.naturalHeight || 405) * scale));
86
+ const ctx = canvas.getContext('2d')!;
87
+ ctx.fillStyle = '#ffffff';
88
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
89
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
90
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('PNG'))), 'image/png'));
91
+ }
92
+ const svgUrl = (svg: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
93
+
94
+ function deleteButton(scope: string, name: string, after: () => void): HTMLButtonElement {
95
+ return iconButton('trash', T.delete, async () => {
96
+ if (!(await confirmDialog(T.deleteAssetTitle(stem(name)), '', T.delete, true))) return;
97
+ try {
98
+ await removeAsset(scope, name);
99
+ after();
100
+ } catch (e) {
101
+ toast((e as Error).message);
102
+ }
103
+ });
104
+ }
105
+
106
+ /** Download as PNG (2×) or the original file; an SVG offers both. */
107
+ function downloadButton(scope: string, name: string, src: () => string): HTMLButtonElement {
108
+ const dl = iconButton('download', T.download, () => {
109
+ const original = () => {
110
+ const link = el('a');
111
+ link.href = api('/file', { scope, name, download: '1' });
112
+ link.click();
113
+ };
114
+ const png = async () => {
115
+ try {
116
+ downloadBlob(await toPng(src()), `${stem(name)}.png`);
117
+ } catch (e) {
118
+ toast((e as Error).message);
119
+ }
120
+ };
121
+ if (!/\.svg$/i.test(name)) return original();
122
+ showMenu(
123
+ [
124
+ { label: 'PNG', icon: 'download', action: () => void png() },
125
+ { label: 'SVG', icon: 'download', action: original },
126
+ ],
127
+ dl,
128
+ );
129
+ });
130
+ return dl;
131
+ }
132
+
133
+ /** Large preview over the page; click or Esc closes it. */
134
+ function lightbox(src: string, caption: string) {
135
+ const back = el('div', 'lightbox');
136
+ const fig = el('figure', '');
137
+ const img = el('img');
138
+ img.src = src;
139
+ img.alt = caption;
140
+ fig.append(img, el('figcaption', '', caption));
141
+ back.append(fig);
142
+ const close = () => {
143
+ back.remove();
144
+ window.removeEventListener('keydown', onKey, true);
145
+ };
146
+ const onKey = (e: KeyboardEvent) => {
147
+ if (e.key === 'Escape') {
148
+ e.preventDefault();
149
+ e.stopPropagation();
150
+ close();
151
+ }
152
+ };
153
+ back.addEventListener('click', close);
154
+ window.addEventListener('keydown', onKey, true);
155
+ document.body.append(back);
156
+ }
157
+
158
+ // ---------- the library both views share ----------
159
+
160
+ interface Entry {
161
+ scope: string;
162
+ name: string;
163
+ title: string;
164
+ updatedAt: string;
165
+ }
166
+ const keyOf = (n: { scope: string; name: string }) => `${n.scope}/${n.name}`;
167
+
168
+ async function loadFavourites(): Promise<Set<string>> {
169
+ try {
170
+ const res = await fetch('/__api/favorites');
171
+ if (!res.ok) return new Set();
172
+ return new Set(((await res.json()) as { favorites: { scope: string; name: string }[] }).favorites.map(keyOf));
173
+ } catch {
174
+ return new Set();
175
+ }
176
+ }
177
+ /** Stars or unstars; the new set, or null when it failed (and said so). */
178
+ async function putFavourite(scope: string, name: string, on: boolean): Promise<Set<string> | null> {
179
+ const res = await fetch('/__api/favorites', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ scope, name, on }) });
180
+ if (!res.ok) {
181
+ toast((await failure(res)).message);
182
+ return null;
183
+ }
184
+ return new Set(((await res.json()) as { favorites: { scope: string; name: string }[] }).favorites.map(keyOf));
185
+ }
186
+
187
+ function starButton(on: boolean, toggle: () => void): HTMLButtonElement {
188
+ const b = iconButton(on ? 'starFill' : 'star', on ? T.unfavorite : T.favorite, toggle);
189
+ b.classList.add('lib-star');
190
+ b.classList.toggle('on', on);
191
+ return b;
192
+ }
193
+
194
+ const ago = (iso: string) => {
195
+ const s = (Date.now() - Date.parse(iso)) / 1000;
196
+ if (s < 60) return T.justNow;
197
+ if (s < 3600) return T.minutesAgo(Math.floor(s / 60));
198
+ if (s < 86400) return T.hoursAgo(Math.floor(s / 3600));
199
+ return new Date(iso).toLocaleDateString(locale(), { month: 'short', day: 'numeric' });
200
+ };
201
+
202
+ /** The piece of `text` around the first `q`, with `q` marked; null when it is not there. */
203
+ function snippet(text: string, q: string): HTMLElement | null {
204
+ const at = text.toLowerCase().indexOf(q);
205
+ if (at < 0) return null;
206
+ const from = Math.max(0, at - 18);
207
+ const piece = text.slice(from, at + q.length + 40).replace(/[#*`>\n]+/g, ' ');
208
+ const i = piece.toLowerCase().indexOf(q);
209
+ const out = el('span', 'lib-item-meta');
210
+ out.append(`${from ? '…' : ''}${piece.slice(0, Math.max(0, i))}`, el('mark', '', piece.slice(i, i + q.length)), piece.slice(i + q.length));
211
+ return out;
212
+ }
213
+
214
+ type Nav = 'home' | 'recent' | 'fav' | 'all' | 'styles';
215
+
216
+ /** Head, search and the Home / Recent / Favorites / All nav, with the list under them. */
217
+ function librarySide(o: { title: string; actions: HTMLElement[]; searchLabel: string; store: string; extra?: readonly (readonly [Nav, string, string])[]; onNav: (n: Nav) => void; onSearch: () => void }) {
218
+ const side = el('aside', 'lib-side');
219
+ const head = el('div', 'lib-head');
220
+ head.append(el('h2', '', o.title), el('div', 'grow'), ...o.actions);
221
+ const box = el('label', 'lib-search');
222
+ const search = el('input');
223
+ search.type = 'search';
224
+ search.placeholder = o.searchLabel;
225
+ search.setAttribute('aria-label', o.searchLabel);
226
+ box.append(icon('search', 14), search);
227
+ const navEl = el('nav', 'lib-nav');
228
+ const known: Nav[] = ['home', 'recent', 'fav', 'all', ...(o.extra ?? []).map(([k]) => k)];
229
+ let nav: Nav = 'home';
230
+ try {
231
+ const v = localStorage.getItem(o.store) as Nav | null;
232
+ if (v && known.includes(v)) nav = v;
233
+ } catch {
234
+ // remembered for this page only
235
+ }
236
+ const tab = ([key, ic, label]: readonly [Nav, string, string]) => {
237
+ const b = el('button', 'lib-tab', '');
238
+ b.type = 'button';
239
+ b.dataset.nav = key;
240
+ b.append(icon(ic, 15), el('span', '', label));
241
+ b.addEventListener('click', () => select(key));
242
+ return b;
243
+ };
244
+ const main: (readonly [Nav, string, string])[] = [
245
+ ['home', 'home', T.home],
246
+ ['recent', 'clock', T.notesRecent],
247
+ ['fav', 'star', T.notesFavorites],
248
+ ['all', 'list', T.notesAll],
249
+ ];
250
+ const tabs = [...main, ...(o.extra ?? [])].map(tab);
251
+ navEl.append(...tabs.slice(0, 4));
252
+ if (o.extra?.length) navEl.append(el('div', 'lib-divider'), ...tabs.slice(4));
253
+ const list = el('div', 'lib-list');
254
+ side.append(head, box, navEl, list);
255
+ const paint = () => {
256
+ for (const t of tabs) t.setAttribute('aria-selected', String(t.dataset.nav === nav));
257
+ };
258
+ function select(n: Nav, quiet = false) {
259
+ nav = n;
260
+ try {
261
+ localStorage.setItem(o.store, n);
262
+ } catch {
263
+ // remembered for this page only
264
+ }
265
+ paint();
266
+ if (!quiet) o.onNav(n);
267
+ }
268
+ let timer = 0;
269
+ search.addEventListener('input', () => {
270
+ clearTimeout(timer);
271
+ timer = window.setTimeout(o.onSearch, 120);
272
+ });
273
+ search.addEventListener('keydown', (e) => {
274
+ if (e.key === 'Escape' && search.value) {
275
+ e.stopPropagation();
276
+ search.value = '';
277
+ o.onSearch();
278
+ }
279
+ });
280
+ paint();
281
+ return {
282
+ el: side,
283
+ list,
284
+ query: () => search.value.trim().toLowerCase(),
285
+ get nav() {
286
+ return nav;
287
+ },
288
+ select,
289
+ };
290
+ }
291
+
292
+ function libItem(n: Entry, fav: boolean, meta: string | HTMLElement | null, onClick: () => void, thumb?: string): HTMLButtonElement {
293
+ const b = el('button', 'lib-item', '');
294
+ b.type = 'button';
295
+ b.dataset.key = keyOf(n);
296
+ b.dataset.name = n.name;
297
+ if (thumb) {
298
+ const img = el('img', 'lib-thumb');
299
+ img.src = thumb;
300
+ img.alt = '';
301
+ img.loading = 'lazy';
302
+ b.append(img);
303
+ }
304
+ const text = el('span', 'lib-item-text');
305
+ const top = el('span', 'lib-item-top');
306
+ top.append(el('span', 'lib-item-title', n.title));
307
+ if (fav) top.append(icon('starFill', 11));
308
+ text.append(top);
309
+ if (meta) text.append(typeof meta === 'string' ? el('span', 'lib-item-meta', meta) : meta);
310
+ b.append(text);
311
+ b.addEventListener('click', onClick);
312
+ return b;
313
+ }
314
+
315
+ function primaryButton(label: string, ic: string, onClick: () => void, primary = true): HTMLButtonElement {
316
+ const b = el('button', primary ? 'btn primary' : 'btn', '');
317
+ b.type = 'button';
318
+ b.append(icon(ic, 14), el('span', '', label));
319
+ b.addEventListener('click', onClick);
320
+ return b;
321
+ }
322
+
323
+ const where = (scope: string) => (scope === SHARED ? T.assetsShared : T.assetsThisBook);
324
+ const newestFirst = <E extends Entry>(list: E[]) => [...list].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
325
+
326
+ // ---------- chart styles ----------
327
+
328
+ interface Styles {
329
+ default: string;
330
+ styles: ChartStyle[];
331
+ }
332
+ async function loadStyles(): Promise<Styles> {
333
+ try {
334
+ const res = await fetch('/__api/chart-styles');
335
+ if (res.ok) return (await res.json()) as Styles;
336
+ } catch {
337
+ // the built-in ones still work
338
+ }
339
+ return { default: 'default', styles: [] };
340
+ }
341
+ async function saveStyles(next: Styles): Promise<Styles | null> {
342
+ const res = await fetch('/__api/chart-styles', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(next) });
343
+ if (!res.ok) {
344
+ toast((await failure(res)).message);
345
+ return null;
346
+ }
347
+ return (await res.json()) as Styles;
348
+ }
349
+ const builtin = (id: string) => BUILTIN_STYLES.some((s) => s.id === id);
350
+ export const styleName = (s: ChartStyle) => (builtin(s.id) ? T.builtinStyle(s.id) : s.name);
351
+
352
+ const SAMPLE = {
353
+ categories: ['Q1', 'Q2', 'Q3', 'Q4'],
354
+ series: [
355
+ { name: 'A', values: [42, 58, 51, 74] },
356
+ { name: 'B', values: [30, 36, 44, 49] },
357
+ { name: 'C', values: [18, 25, 21, 33] },
358
+ ],
359
+ };
360
+ /** A small chart in a style, for its swatch and preview. */
361
+ const sampleChart = (look: ChartStyle, type: ChartType = 'bar', title = '') =>
362
+ chartFile({ id: 'sample', type, range: 'A1', ...(title ? { title } : {}), x: 0, y: 0, w: 720, h: 405 }, type === 'doughnut' ? { categories: ['A', 'B', 'C', 'D'], series: [{ name: 'S', values: [44, 26, 18, 12] }] } : SAMPLE, 720, 405, undefined, look);
363
+
364
+ // ---------- Assets ----------
365
+
366
+ /** What the editor lends the Assets view to make and redraw charts. */
367
+ export interface ChartHost {
368
+ sheets(): string[];
369
+ /** The sheet and range a new chart starts from: the selection. */
370
+ selection(): { sheet: string; range: string };
371
+ /** The chart drawn from the numbers now, in a style; '' when its sheet or range is gone. */
372
+ draw(source: ChartSource, look: ChartStyle): string;
373
+ }
374
+
375
+ const RANGE = /^\$?[A-Za-z]{1,3}\$?\d+(:\$?[A-Za-z]{1,3}\$?\d+)?$/;
376
+
377
+ interface ImageEntry extends Entry {
378
+ /** Where a chart image came from; null for any other picture. */
379
+ source: ChartSource | null;
380
+ text: string;
381
+ }
382
+
383
+ export function createAssetsView(opts: { bookId: string; charts: ChartHost }) {
384
+ const page = el('section', 'lib-view asset-view');
385
+ page.dataset.view = 'assets';
386
+ const side = librarySide({
387
+ title: T.viewAssets,
388
+ actions: [iconButton('upload', T.uploadImage, () => void pickAndUpload()), iconButton('plus', T.newChart, () => void chartDialog())],
389
+ searchLabel: T.searchAssets,
390
+ store: 'open-spreadsheet:assets-nav',
391
+ extra: [['styles', 'palette', T.chartStyles]],
392
+ onNav: (n) => {
393
+ if (n === 'home') current = null;
394
+ void paint();
395
+ },
396
+ onSearch: () => void paint(),
397
+ });
398
+ const main = el('div', 'lib-main asset-main');
399
+ page.append(side.el, main);
400
+
401
+ let images: ImageEntry[] = [];
402
+ let favourites = new Set<string>();
403
+ let styles: Styles = { default: 'default', styles: [] };
404
+ let current: { scope: string; name: string } | null = null;
405
+ /** The style open in the editor; while it is, refreshes leave the right side alone. */
406
+ let editing: string | null = null;
407
+ let fresh = '';
408
+ const allStyles = () => [...BUILTIN_STYLES, ...styles.styles];
409
+ const lookFor = (source: ChartSource) => findStyle(source.style ?? styles.default, styles.styles);
410
+ const fileUrl = (e: Entry) => api('/file', { scope: e.scope, name: e.name, v: e.updatedAt });
411
+
412
+ /** What an image shows now: a chart redrawn from the numbers (its file kept in step), else the file. */
413
+ function liveSrc(e: ImageEntry): string {
414
+ if (!e.source) return fileUrl(e);
415
+ const drawn = opts.charts.draw(e.source, lookFor(e.source)) || e.text;
416
+ if (drawn !== e.text) {
417
+ e.text = drawn;
418
+ void uploadAsset(e.scope, e.name, drawn, 'image/svg+xml', true).catch(() => {});
419
+ }
420
+ return svgUrl(drawn);
421
+ }
422
+ const metaOf = (e: ImageEntry) => (e.source ? `${chartLabel(e.source.type)} · ${e.source.sheet}!${e.source.range}` : where(e.scope));
423
+
424
+ async function upload(files: File[]) {
425
+ let last = '';
426
+ for (const file of files) {
427
+ if (!/^image\/(png|jpeg|gif|webp|svg\+xml)$/.test(file.type)) continue;
428
+ try {
429
+ const dot = file.name.lastIndexOf('.');
430
+ const ext = dot > 0 ? file.name.slice(dot).toLowerCase() : '.png';
431
+ last = await uploadAsset(opts.bookId, `${fileStem(dot > 0 ? file.name.slice(0, dot) : file.name, 'image')}${ext}`, file, file.type);
432
+ } catch (e) {
433
+ toast((e as Error).message);
434
+ }
435
+ }
436
+ if (last) await refresh({ scope: opts.bookId, name: last });
437
+ }
438
+ async function pickAndUpload() {
439
+ const file = await pickFile('image/png,image/jpeg,image/gif,image/webp,image/svg+xml');
440
+ if (file) await upload([file]);
441
+ }
442
+ page.addEventListener('dragover', (e) => {
443
+ if (!e.dataTransfer?.types.includes('Files')) return;
444
+ e.preventDefault();
445
+ page.classList.add('dropping');
446
+ });
447
+ page.addEventListener('dragleave', (e) => {
448
+ if (e.target === page) page.classList.remove('dropping');
449
+ });
450
+ page.addEventListener('drop', (e) => {
451
+ e.preventDefault();
452
+ page.classList.remove('dropping');
453
+ void upload([...(e.dataTransfer?.files ?? [])]);
454
+ });
455
+
456
+ /** New chart (no `edit`) or a change to one; returns the saved name. */
457
+ async function chartDialog(edit?: { name: string; source: ChartSource }): Promise<string | null> {
458
+ if (!styles.styles.length && styles.default === 'default') styles = await loadStyles();
459
+ const start = edit?.source ?? { ...opts.charts.selection(), type: 'bar' as const };
460
+ const v = await promptDialog({
461
+ title: edit ? T.editChart : T.newChart,
462
+ fields: [
463
+ { name: 'title', label: T.title, value: start.title ?? '' },
464
+ { name: 'type', label: T.chartType, options: CHART_TYPES.map((t) => ({ value: t, label: chartLabel(t) })), value: start.type },
465
+ { name: 'sheet', label: T.sheetLabel, options: opts.charts.sheets().map((s) => ({ value: s, label: s })), value: start.sheet },
466
+ { name: 'range', label: T.rangeLabel, value: start.range, mono: true, validate: (x) => (RANGE.test(x.trim()) ? null : T.rangeLabel) },
467
+ {
468
+ name: 'style',
469
+ label: T.styleLabel,
470
+ options: [{ value: '', label: T.followDefault(styleName(findStyle(styles.default, styles.styles))) }, ...allStyles().map((s) => ({ value: s.id, label: styleName(s) }))],
471
+ value: start.style ?? '',
472
+ },
473
+ ],
474
+ ok: T.save,
475
+ });
476
+ if (!v) return null;
477
+ const source: ChartSource = {
478
+ sheet: v.sheet!,
479
+ range: v.range!.trim().toUpperCase().replaceAll('$', ''),
480
+ type: v.type as ChartSource['type'],
481
+ ...(v.title!.trim() ? { title: v.title!.trim() } : {}),
482
+ ...(v.style ? { style: v.style } : {}),
483
+ };
484
+ const svg = opts.charts.draw(source, lookFor(source));
485
+ if (!svg) {
486
+ toast(T.rangeLabel);
487
+ return null;
488
+ }
489
+ try {
490
+ const name = edit ? await uploadAsset(opts.bookId, edit.name, svg, 'image/svg+xml', true) : await uploadAsset(opts.bookId, `${fileStem(source.title ?? '', `${source.sheet}-${source.range}`)}.svg`, svg);
491
+ fresh = `${opts.bookId}/${name}`;
492
+ if (!page.hidden) await refresh({ scope: opts.bookId, name });
493
+ return name;
494
+ } catch (e) {
495
+ toast((e as Error).message);
496
+ return null;
497
+ }
498
+ }
499
+
500
+ async function toggleFavourite(e: Entry) {
501
+ const next = await putFavourite(e.scope, e.name, !favourites.has(keyOf(e)));
502
+ if (!next) return;
503
+ favourites = next;
504
+ await paint();
505
+ }
506
+
507
+ // ----- the right side -----
508
+
509
+ function card(e: ImageEntry): HTMLElement {
510
+ const c = el('figure', 'asset-card');
511
+ c.dataset.name = e.name;
512
+ if (keyOf(e) === fresh) c.classList.add('fresh');
513
+ const src = liveSrc(e);
514
+ const frame = el('button', 'asset-frame');
515
+ frame.type = 'button';
516
+ frame.title = e.title;
517
+ const img = el('img');
518
+ img.src = src;
519
+ img.alt = e.title;
520
+ img.loading = 'lazy';
521
+ frame.append(img);
522
+ frame.addEventListener('click', () => open(e));
523
+ const tools = el('div', 'asset-tools');
524
+ tools.append(
525
+ starButton(favourites.has(keyOf(e)), () => void toggleFavourite(e)),
526
+ downloadButton(e.scope, e.name, () => src),
527
+ deleteButton(e.scope, e.name, () => void refresh()),
528
+ );
529
+ const cap = el('figcaption', '');
530
+ const t = el('span', 'asset-title', e.title);
531
+ if (favourites.has(keyOf(e))) t.prepend(icon('starFill', 12));
532
+ cap.append(t, el('span', 'asset-meta', metaOf(e)));
533
+ c.append(frame, tools, cap);
534
+ return c;
535
+ }
536
+
537
+ function header(title: string, ...actions: HTMLElement[]) {
538
+ const bar = el('div', 'lib-page-head');
539
+ bar.append(el('h1', '', title), el('div', 'grow'), ...actions);
540
+ return bar;
541
+ }
542
+
543
+ function showHome() {
544
+ editing = null;
545
+ const body = el('div', 'lib-page');
546
+ body.append(header(T.viewAssets, primaryButton(T.uploadImage, 'upload', () => void pickAndUpload(), false), primaryButton(T.newChart, 'chart', () => void chartDialog())));
547
+ if (!images.length) {
548
+ const empty = el('div', 'lib-empty-state');
549
+ empty.append(icon('chart', 28), el('h3', '', T.noAssetsYet), primaryButton(T.newChart, 'chart', () => void chartDialog()));
550
+ body.append(empty);
551
+ main.replaceChildren(body);
552
+ return;
553
+ }
554
+ const section = (label: string, list: ImageEntry[], scope?: string) => {
555
+ if (!list.length) return;
556
+ const s = el('section', 'asset-section');
557
+ if (scope) s.dataset.scope = scope;
558
+ const grid = el('div', 'asset-grid');
559
+ grid.append(...list.map(card));
560
+ s.append(el('h3', '', label), grid);
561
+ body.append(s);
562
+ };
563
+ section(T.notesFavorites, images.filter((e) => favourites.has(keyOf(e))));
564
+ section(T.assetsThisBook, images.filter((e) => e.scope === opts.bookId), opts.bookId);
565
+ section(T.assetsShared, images.filter((e) => e.scope === SHARED), SHARED);
566
+ main.replaceChildren(body);
567
+ main.querySelector('.asset-card.fresh')?.scrollIntoView({ block: 'nearest' });
568
+ }
569
+
570
+ function showDetail(e: ImageEntry) {
571
+ editing = null;
572
+ let src = liveSrc(e);
573
+ const body = el('div', 'lib-page asset-detail');
574
+ // The title on top, edited in place: Enter or leaving it renames the file (and retitles a chart).
575
+ const head = el('div', 'lib-detail-head asset-detail-head');
576
+ const title = el('input', 'asset-title-input');
577
+ title.value = e.title;
578
+ title.spellcheck = false;
579
+ title.setAttribute('aria-label', T.title);
580
+ title.addEventListener('keydown', (ev) => {
581
+ if (ev.key === 'Enter') {
582
+ ev.preventDefault();
583
+ title.blur();
584
+ } else if (ev.key === 'Escape') {
585
+ ev.stopPropagation();
586
+ title.value = e.title;
587
+ title.blur();
588
+ }
589
+ });
590
+ title.addEventListener('blur', () => void retitle(e, title));
591
+ head.append(title, el('div', 'grow'));
592
+ if (e.source && e.scope === opts.bookId) {
593
+ const s = e.source;
594
+ // Its style, changed in place: redrawn and saved at once.
595
+ const pick = el('select', 'input select asset-style-pick');
596
+ pick.title = T.styleLabel;
597
+ pick.append(new Option(T.followDefault(styleName(findStyle(styles.default, styles.styles))), ''), ...allStyles().map((st) => new Option(styleName(st), st.id)));
598
+ pick.value = s.style ?? '';
599
+ pick.addEventListener('change', async () => {
600
+ const next: ChartSource = { ...s, ...(pick.value ? { style: pick.value } : {}) };
601
+ if (!pick.value) delete next.style;
602
+ const svg = opts.charts.draw(next, lookFor(next));
603
+ if (!svg) return;
604
+ try {
605
+ await uploadAsset(e.scope, e.name, svg, 'image/svg+xml', true);
606
+ e.source = next;
607
+ e.text = svg;
608
+ src = svgUrl(svg);
609
+ img.src = src;
610
+ } catch (err) {
611
+ toast((err as Error).message);
612
+ }
613
+ });
614
+ head.append(pick, iconButton('pencil', T.editChart, () => void chartDialog({ name: e.name, source: e.source ?? s })));
615
+ }
616
+ head.append(
617
+ starButton(favourites.has(keyOf(e)), () => void toggleFavourite(e)),
618
+ downloadButton(e.scope, e.name, () => src),
619
+ deleteButton(e.scope, e.name, () => {
620
+ current = null;
621
+ void refresh();
622
+ }),
623
+ );
624
+ const frame = el('button', 'asset-stage');
625
+ frame.type = 'button';
626
+ const img = el('img');
627
+ img.src = src;
628
+ img.alt = e.title;
629
+ frame.append(img);
630
+ frame.addEventListener('click', () => lightbox(src, e.title));
631
+ const meta = el('p', 'asset-meta asset-detail-meta', [where(e.scope), ...(e.source ? [`${chartLabel(e.source.type)} · ${e.source.sheet}!${e.source.range}`] : []), ago(e.updatedAt)].join(' · '));
632
+ body.append(head, meta, frame);
633
+ main.replaceChildren(body);
634
+ }
635
+
636
+ async function retitle(e: ImageEntry, input: HTMLInputElement) {
637
+ const t = input.value.trim();
638
+ if (!t || t === e.title) {
639
+ input.value = e.title;
640
+ return;
641
+ }
642
+ const dot = e.name.lastIndexOf('.');
643
+ const to = `${fileStem(t, 'image')}${e.name.slice(dot)}`;
644
+ await inflight.catch(() => {});
645
+ try {
646
+ let name = e.name;
647
+ if (to !== e.name) {
648
+ const res = await fetch(api('/rename', { scope: e.scope, name: e.name, to }), { method: 'POST' });
649
+ if (!res.ok) throw await failure(res);
650
+ name = to;
651
+ }
652
+ if (e.source) {
653
+ // The picture's own title follows.
654
+ const next: ChartSource = { ...e.source, title: t };
655
+ const svg = opts.charts.draw(next, lookFor(next));
656
+ if (svg) await uploadAsset(e.scope, name, svg, 'image/svg+xml', true);
657
+ }
658
+ current = { scope: e.scope, name };
659
+ await refresh();
660
+ } catch (err) {
661
+ input.value = e.title;
662
+ toast((err as Error).message);
663
+ }
664
+ }
665
+
666
+ // ----- styles -----
667
+
668
+ function styleCard(s: ChartStyle): HTMLElement {
669
+ const c = el('button', 'style-card');
670
+ c.type = 'button';
671
+ c.dataset.style = s.id;
672
+ const img = el('img');
673
+ img.src = svgUrl(sampleChart(s));
674
+ img.alt = '';
675
+ const swatches = el('span', 'style-swatches');
676
+ for (const col of s.colors.slice(0, 6)) {
677
+ const dot = el('i');
678
+ dot.style.background = col;
679
+ swatches.append(dot);
680
+ }
681
+ const name = el('span', 'style-name', styleName(s));
682
+ const tags = el('span', 'style-tags');
683
+ if (styles.default === s.id) tags.append(el('span', 'style-tag on', T.defaultBadge));
684
+ if (builtin(s.id)) tags.append(el('span', 'style-tag', T.builtIn));
685
+ const foot = el('span', 'style-foot');
686
+ foot.append(name, tags, swatches);
687
+ c.append(img, foot);
688
+ c.addEventListener('click', () => {
689
+ current = null;
690
+ showStyle(s.id);
691
+ paintList();
692
+ });
693
+ return c;
694
+ }
695
+
696
+ function showStyles() {
697
+ editing = null;
698
+ const body = el('div', 'lib-page');
699
+ body.append(header(T.chartStyles, primaryButton(T.newStyle, 'plus', () => void copyStyle(findStyle(styles.default, styles.styles), true))));
700
+ const grid = el('div', 'style-grid');
701
+ grid.append(...allStyles().map(styleCard));
702
+ body.append(grid);
703
+ main.replaceChildren(body);
704
+ }
705
+
706
+ async function copyStyle(from: ChartStyle, blank = false) {
707
+ const taken = new Set(allStyles().map((s) => s.id));
708
+ let n = 1;
709
+ const base = blank ? 'style' : `${from.id}`;
710
+ while (taken.has(`${base}-${n}`)) n++;
711
+ const copy: ChartStyle = { ...from, colors: [...from.colors], id: `${base}-${n}`, name: blank ? `${T.newStyle} ${n}` : `${styleName(from)} ${n + 1}` };
712
+ const saved = await saveStyles({ ...styles, styles: [...styles.styles, copy] });
713
+ if (!saved) return;
714
+ styles = saved;
715
+ showStyle(copy.id);
716
+ paintList();
717
+ }
718
+
719
+ /** One style: its preview, and — for the workspace's own — every setting, saved as it changes. */
720
+ function showStyle(id: string) {
721
+ const s = allStyles().find((x) => x.id === id);
722
+ if (!s) return showStyles();
723
+ editing = id;
724
+ const own = !builtin(id);
725
+ const draft: ChartStyle = { ...s, colors: [...s.colors] };
726
+ const body = el('div', 'lib-page style-page');
727
+ const back = iconButton('arrowLeft', T.chartStyles, () => {
728
+ showStyles();
729
+ paintList();
730
+ });
731
+ const actions: HTMLElement[] = [];
732
+ if (styles.default !== id) {
733
+ actions.push(
734
+ primaryButton(
735
+ T.makeDefault,
736
+ 'check',
737
+ async () => {
738
+ const saved = await saveStyles({ ...styles, default: id });
739
+ if (saved) {
740
+ styles = saved;
741
+ showStyle(id);
742
+ paintList();
743
+ }
744
+ },
745
+ false,
746
+ ),
747
+ );
748
+ } else actions.push(el('span', 'style-tag on', T.defaultBadge));
749
+ if (own) {
750
+ actions.push(
751
+ iconButton('trash', T.delete, async () => {
752
+ if (!(await confirmDialog(T.deleteAssetTitle(draft.name), '', T.delete, true))) return;
753
+ const saved = await saveStyles({ default: styles.default === id ? 'default' : styles.default, styles: styles.styles.filter((x) => x.id !== id) });
754
+ if (saved) {
755
+ styles = saved;
756
+ showStyles();
757
+ paintList();
758
+ }
759
+ }),
760
+ );
761
+ } else actions.push(primaryButton(T.duplicateEdit, 'copy', () => void copyStyle(s)));
762
+ const head = el('div', 'lib-page-head');
763
+ const title = el('h1', '', styleName(s));
764
+ head.append(back, title, el('div', 'grow'), ...actions);
765
+
766
+ const previews = el('div', 'style-previews');
767
+ const p1 = el('img');
768
+ const p2 = el('img');
769
+ previews.append(p1, p2);
770
+ const draw = () => {
771
+ p1.src = svgUrl(sampleChart(draft, 'bar', styleName(draft)));
772
+ p2.src = svgUrl(sampleChart(draft, 'doughnut'));
773
+ };
774
+ draw();
775
+
776
+ let timer = 0;
777
+ const changed = () => {
778
+ draw();
779
+ clearTimeout(timer);
780
+ timer = window.setTimeout(async () => {
781
+ const saved = await saveStyles({ ...styles, styles: styles.styles.map((x) => (x.id === id ? draft : x)) });
782
+ if (saved) {
783
+ styles = saved;
784
+ paintList();
785
+ }
786
+ }, 450);
787
+ };
788
+
789
+ const form = el('div', 'style-form');
790
+ const row = (label: string, control: HTMLElement) => {
791
+ const r = el('label', 'style-row');
792
+ r.append(el('span', '', label), control);
793
+ form.append(r);
794
+ };
795
+ const colour = (value: string, set: (v: string) => void) => {
796
+ const i = el('input', 'style-color');
797
+ i.type = 'color';
798
+ i.value = value;
799
+ i.disabled = !own;
800
+ i.addEventListener('input', () => {
801
+ set(i.value);
802
+ changed();
803
+ });
804
+ return i;
805
+ };
806
+ if (own) {
807
+ const name = el('input', 'input');
808
+ name.value = draft.name;
809
+ name.addEventListener('input', () => {
810
+ draft.name = name.value.trim() || draft.id;
811
+ title.textContent = draft.name;
812
+ changed();
813
+ });
814
+ row(T.title, name);
815
+ }
816
+ const series = el('div', 'style-colors');
817
+ const paintSeries = () => {
818
+ series.replaceChildren(
819
+ ...draft.colors.map((c, i) =>
820
+ colour(c, (v) => {
821
+ draft.colors[i] = v;
822
+ }),
823
+ ),
824
+ );
825
+ if (!own) return;
826
+ if (draft.colors.length < 12)
827
+ series.append(
828
+ iconButton('plus', T.addColor, () => {
829
+ draft.colors.push(draft.colors[draft.colors.length % 8] ?? '#888888');
830
+ paintSeries();
831
+ changed();
832
+ }),
833
+ );
834
+ if (draft.colors.length > 1)
835
+ series.append(
836
+ iconButton('x', T.removeColor, () => {
837
+ draft.colors.pop();
838
+ paintSeries();
839
+ changed();
840
+ }),
841
+ );
842
+ };
843
+ paintSeries();
844
+ row(T.styleColors, series);
845
+ const pair = el('div', 'style-pair');
846
+ for (const [label, key] of [
847
+ [T.styleBackground, 'background'],
848
+ [T.styleText, 'text'],
849
+ [T.styleMuted, 'muted'],
850
+ [T.styleGrid, 'grid'],
851
+ ] as const) {
852
+ const cell = el('label', 'style-swatch');
853
+ cell.append(
854
+ colour(draft[key], (v) => {
855
+ draft[key] = v;
856
+ }),
857
+ el('span', '', label),
858
+ );
859
+ pair.append(cell);
860
+ }
861
+ row(T.styleColorsMore, pair);
862
+ const font = el('select', 'input select');
863
+ for (const [v, label] of [
864
+ ['sans', T.fontSans],
865
+ ['serif', T.fontSerif],
866
+ ['mono', T.fontMono],
867
+ ['rounded', T.fontRounded],
868
+ ] as const)
869
+ font.append(new Option(label, v));
870
+ font.value = draft.font;
871
+ font.disabled = !own;
872
+ font.addEventListener('change', () => {
873
+ draft.font = font.value as ChartStyle['font'];
874
+ changed();
875
+ });
876
+ row(T.styleFont, font);
877
+ const radius = el('input', 'style-range');
878
+ radius.type = 'range';
879
+ radius.min = '0';
880
+ radius.max = '8';
881
+ radius.value = String(draft.radius);
882
+ radius.disabled = !own;
883
+ radius.addEventListener('input', () => {
884
+ draft.radius = Number(radius.value);
885
+ changed();
886
+ });
887
+ row(T.styleCorners, radius);
888
+ const grid = el('input');
889
+ grid.type = 'checkbox';
890
+ grid.checked = draft.gridLines;
891
+ grid.disabled = !own;
892
+ grid.addEventListener('change', () => {
893
+ draft.gridLines = grid.checked;
894
+ changed();
895
+ });
896
+ row(T.styleGridLines, grid);
897
+ if (!own) form.classList.add('locked');
898
+
899
+ const split = el('div', 'style-split');
900
+ split.append(previews, form);
901
+ body.append(head, split);
902
+ main.replaceChildren(body);
903
+ }
904
+
905
+ // ----- the sidebar -----
906
+
907
+ function visible(): ImageEntry[] {
908
+ if (side.nav === 'recent') return newestFirst(images);
909
+ if (side.nav === 'fav') return images.filter((e) => favourites.has(keyOf(e)));
910
+ return images;
911
+ }
912
+
913
+ function paintList() {
914
+ const q = side.query();
915
+ const mark = () => {
916
+ for (const n of side.list.querySelectorAll<HTMLElement>('.lib-item')) n.classList.toggle('on', Boolean(current) && n.dataset.key === keyOf(current!));
917
+ for (const n of side.list.querySelectorAll<HTMLElement>('.lib-item[data-style]')) n.classList.toggle('on', n.dataset.style === editing);
918
+ };
919
+ const item = (e: ImageEntry, meta: string | HTMLElement | null = e.source ? metaOf(e) : ago(e.updatedAt)) => libItem(e, favourites.has(keyOf(e)), meta, () => open(e), e.text ? svgUrl(e.text) : fileUrl(e));
920
+ if (q) {
921
+ const hits = images
922
+ .map((e) => {
923
+ const hay = [e.title, e.name, e.source ? `${chartLabel(e.source.type)} ${e.source.sheet}!${e.source.range} ${e.source.title ?? ''}` : ''].join(' ');
924
+ const s = snippet(hay, q);
925
+ return s ? { e, s } : null;
926
+ })
927
+ .filter((x) => x !== null);
928
+ side.list.replaceChildren(...(hits.length ? hits.map((h) => item(h.e, h.s)) : [el('p', 'lib-empty', T.noMatches)]));
929
+ return mark();
930
+ }
931
+ if (side.nav === 'home') return side.list.replaceChildren();
932
+ if (side.nav === 'styles') {
933
+ side.list.replaceChildren(
934
+ ...allStyles().map((s) => {
935
+ const b = el('button', 'lib-item', '');
936
+ b.type = 'button';
937
+ b.dataset.style = s.id;
938
+ const dots = el('span', 'style-swatches');
939
+ for (const col of s.colors.slice(0, 4)) {
940
+ const d = el('i');
941
+ d.style.background = col;
942
+ dots.append(d);
943
+ }
944
+ const text = el('span', 'lib-item-text');
945
+ const top = el('span', 'lib-item-top');
946
+ top.append(el('span', 'lib-item-title', styleName(s)));
947
+ text.append(top, el('span', 'lib-item-meta', styles.default === s.id ? T.defaultBadge : builtin(s.id) ? T.builtIn : ''));
948
+ b.append(dots, text);
949
+ b.addEventListener('click', () => {
950
+ showStyle(s.id);
951
+ paintList();
952
+ });
953
+ return b;
954
+ }),
955
+ );
956
+ return mark();
957
+ }
958
+ const list = visible();
959
+ if (!list.length) {
960
+ side.list.replaceChildren(el('p', 'lib-empty', side.nav === 'fav' ? T.noFavoriteAssets : T.noAssetsYet));
961
+ return;
962
+ }
963
+ if (side.nav === 'all') {
964
+ const groups: HTMLElement[] = [];
965
+ for (const scope of [opts.bookId, SHARED]) {
966
+ const mine = list.filter((e) => e.scope === scope);
967
+ if (!mine.length) continue;
968
+ const g = el('section', 'lib-group');
969
+ g.dataset.scope = scope;
970
+ g.append(el('h3', '', where(scope)), ...mine.map((e) => item(e)));
971
+ groups.push(g);
972
+ }
973
+ side.list.replaceChildren(...groups);
974
+ } else side.list.replaceChildren(...list.map((e) => item(e, `${where(e.scope)} · ${ago(e.updatedAt)}`)));
975
+ mark();
976
+ }
977
+
978
+ function open(e: ImageEntry) {
979
+ if (side.nav === 'home' || side.nav === 'styles') side.select('all', true);
980
+ current = { scope: e.scope, name: e.name };
981
+ showDetail(e);
982
+ paintList();
983
+ }
984
+
985
+ /** Lists, then fills the right side for where the sidebar is — except a style being edited. */
986
+ async function paint() {
987
+ paintList();
988
+ if (side.nav === 'styles') {
989
+ if (editing && allStyles().some((s) => s.id === editing)) return;
990
+ return showStyles();
991
+ }
992
+ const open = current && images.find((e) => keyOf(e) === keyOf(current!));
993
+ if (open) return showDetail(open);
994
+ current = null;
995
+ if (side.nav === 'home') return showHome();
996
+ const first = visible()[0];
997
+ if (first) {
998
+ current = { scope: first.scope, name: first.name };
999
+ showDetail(first);
1000
+ paintList();
1001
+ } else showHome();
1002
+ }
1003
+
1004
+ const texts = new Map<string, { at: string; text: string }>();
1005
+ /** Each refresh bumps this; one that finishes after a newer one started is dropped (its list may be stale). */
1006
+ let loading = 0;
1007
+ /** The refresh under way; a rename waits for it, so it never reads a name that is gone. */
1008
+ let inflight: Promise<void> = Promise.resolve();
1009
+ function refresh(prefer?: { scope: string; name: string }): Promise<void> {
1010
+ inflight = load(prefer);
1011
+ return inflight;
1012
+ }
1013
+ async function load(prefer?: { scope: string; name: string }) {
1014
+ const ticket = ++loading;
1015
+ const [mine, shared, favs, st] = await Promise.all([listAssets(opts.bookId), listAssets(SHARED), loadFavourites(), loadStyles()]);
1016
+ if (ticket !== loading) return;
1017
+ favourites = favs;
1018
+ styles = st;
1019
+ const entries = await Promise.all(
1020
+ [...mine.map((a) => ({ a, scope: opts.bookId })), ...shared.map((a) => ({ a, scope: SHARED }))]
1021
+ .filter(({ a }) => a.kind === 'image')
1022
+ .map(async ({ a, scope }): Promise<ImageEntry> => {
1023
+ const e = { scope, name: a.name, title: stem(a.name), updatedAt: a.updatedAt };
1024
+ if (!/\.svg$/i.test(a.name)) return { ...e, source: null, text: '' };
1025
+ const k = keyOf(e);
1026
+ let cached = texts.get(k);
1027
+ if (cached?.at !== a.updatedAt) {
1028
+ cached = { at: a.updatedAt, text: await readText(scope, a.name) };
1029
+ texts.set(k, cached);
1030
+ }
1031
+ const source = chartSourceOf(cached.text);
1032
+ // A chart reads by the title it shows, not its file name.
1033
+ return { ...e, title: source?.title || e.title, source, text: cached.text };
1034
+ }),
1035
+ );
1036
+ if (ticket !== loading) return;
1037
+ images = entries;
1038
+ if (prefer) {
1039
+ current = prefer;
1040
+ if (side.nav === 'home' || side.nav === 'styles') side.select('all', true);
1041
+ }
1042
+ // A style being edited keeps its page; the list still follows.
1043
+ if (side.nav === 'styles' && editing) return paintList();
1044
+ await paint();
1045
+ }
1046
+
1047
+ return { el: page, refresh: () => refresh(), newChart: () => chartDialog() };
1048
+ }
1049
+
1050
+ // ---------- Notes: Markdown, edited in place ----------
1051
+
1052
+ /**
1053
+ * Images in a note are files beside it, by path relative to the note — so the
1054
+ * Markdown reads the same on GitHub or in an editor: `chart.svg` (same folder),
1055
+ * `../../../assets/x.svg` (shared, from a workbook's note), `../sheets/<id>/assets/x.svg`
1056
+ * (a workbook's, from a shared note). Nothing else is shown.
1057
+ */
1058
+ function noteImages(noteScope: string, absolute = false): ImageResolver {
1059
+ return (src) => {
1060
+ let s = src.trim();
1061
+ try {
1062
+ s = decodeURIComponent(s);
1063
+ } catch {
1064
+ return null;
1065
+ }
1066
+ s = s.replace(/^\.\//, '');
1067
+ let scope = noteScope;
1068
+ let name = s;
1069
+ const toShared = /^\.\.\/\.\.\/\.\.\/assets\/([^/]+)$/.exec(s);
1070
+ const toBook = /^\.\.\/sheets\/([a-z0-9][a-z0-9-]*)\/assets\/([^/]+)$/.exec(s);
1071
+ if (toShared && noteScope !== SHARED) [scope, name] = [SHARED, toShared[1]!];
1072
+ else if (toBook && noteScope === SHARED) [scope, name] = [toBook[1]!, toBook[2]!];
1073
+ else if (s.includes('/')) return null;
1074
+ if (!/\.(svg|png|jpe?g|gif|webp)$/i.test(name) || name.startsWith('.')) return null;
1075
+ return `${absolute ? location.origin : ''}${api('/file', { scope, name })}`;
1076
+ };
1077
+ }
1078
+ /** The path a note at `noteScope` uses for an image; spaces and brackets escaped so the Markdown holds. */
1079
+ function imageRef(noteScope: string, scope: string, name: string): string {
1080
+ const n = name.replace(/[ ()]/g, (c) => ({ ' ': '%20', '(': '%28', ')': '%29' })[c]!);
1081
+ if (scope === noteScope) return n;
1082
+ return scope === SHARED ? `../../../assets/${n}` : `../sheets/${scope}/assets/${n}`;
1083
+ }
1084
+
1085
+ /** A note as a printed page — the print dialog saves it as a PDF. */
1086
+ function printNote(markdown: string, title: string, scope: string) {
1087
+ const esc = (t: string) => t.replaceAll('&', '&amp;').replaceAll('<', '&lt;');
1088
+ const html = `<!doctype html><html lang="${document.documentElement.lang || 'en'}"><head><meta charset="utf-8"><title>${esc(title)}</title><style>
1089
+ @page { size: A4; margin: 20mm 18mm; }
1090
+ body { margin: 0; color: #1f1f1f; font: 11.5pt/1.7 -apple-system, BlinkMacSystemFont, "PingFang TC", "Noto Sans TC", "Segoe UI", sans-serif; word-break: break-word; }
1091
+ h1 { font-size: 22pt; line-height: 1.3; margin: 0 0 0.6em; letter-spacing: -0.01em; }
1092
+ h2 { font-size: 15pt; margin: 1.4em 0 0.5em; } h3 { font-size: 12.5pt; margin: 1.2em 0 0.4em; }
1093
+ p, ul, ol, blockquote, pre { margin: 0 0 0.8em; } ul, ol { padding-left: 1.4em; }
1094
+ h1, h2, h3 { break-after: avoid; } pre, blockquote, li { break-inside: avoid; }
1095
+ blockquote { padding-left: 1em; border-left: 3px solid #1f1f1f; color: #5f6368; }
1096
+ code { font: 0.9em "SF Mono", Menlo, monospace; background: #f1f3f4; padding: 0.1em 0.3em; border-radius: 3px; }
1097
+ pre { background: #f1f3f4; padding: 10px 12px; border-radius: 6px; white-space: pre-wrap; } pre code { background: none; padding: 0; }
1098
+ hr { border: 0; text-align: center; margin: 1.4em 0; } hr::after { content: '···'; letter-spacing: 0.6em; color: #9aa0a6; }
1099
+ a { color: #1a73e8; }
1100
+ img { display: block; max-width: 100%; margin: 0.4em 0 0.9em; break-inside: avoid; }
1101
+ </style></head><body>${mdToHtml(markdown, noteImages(scope, true))}</body></html>`;
1102
+ (window as unknown as { __lastNotePrint?: string }).__lastNotePrint = html;
1103
+ const frame = el('iframe', 'print-frame');
1104
+ frame.setAttribute('aria-hidden', 'true');
1105
+ document.body.append(frame);
1106
+ const doc = frame.contentDocument!;
1107
+ doc.open();
1108
+ doc.write(html);
1109
+ doc.close();
1110
+ const done = () => setTimeout(() => frame.remove(), 1000);
1111
+ frame.contentWindow!.addEventListener('afterprint', done);
1112
+ // Pictures first: the page is printed once they have loaded (or failed).
1113
+ const pictures = [...doc.images].map((img) =>
1114
+ img.complete
1115
+ ? Promise.resolve()
1116
+ : new Promise<void>((ok) => {
1117
+ img.addEventListener('load', () => ok(), { once: true });
1118
+ img.addEventListener('error', () => ok(), { once: true });
1119
+ }),
1120
+ );
1121
+ void Promise.all(pictures).then(() =>
1122
+ setTimeout(() => {
1123
+ frame.contentWindow!.focus();
1124
+ frame.contentWindow!.print();
1125
+ done();
1126
+ }, 50),
1127
+ );
1128
+ }
1129
+
1130
+ export function createNotesView(opts: { bookId: string }) {
1131
+ const page = el('section', 'lib-view note-view');
1132
+ page.dataset.view = 'notes';
1133
+ const side = librarySide({
1134
+ title: T.viewNotes,
1135
+ actions: [iconButton('plus', T.newNote, () => void newNote())],
1136
+ searchLabel: T.searchNotes,
1137
+ store: 'open-spreadsheet:notes-nav',
1138
+ onNav: (n) => void navigate(n),
1139
+ onSearch: () => void renderList(),
1140
+ });
1141
+ const main = el('div', 'lib-main note-main');
1142
+ page.append(side.el, main);
1143
+
1144
+ let current: { scope: string; name: string } | null = null;
1145
+ let dirty = false;
1146
+ let timer = 0;
1147
+ let saving: Promise<void> = Promise.resolve();
1148
+ /** Each open bumps this; a load that finishes after a newer one started is dropped. */
1149
+ let opening = 0;
1150
+ // Written as it reads; the </> toggle shows the Markdown source.
1151
+ const textarea = el('textarea', 'note-text');
1152
+ textarea.spellcheck = false;
1153
+ const editor = createNoteEditor({ onChange: () => changed(), placeholder: T.notePlaceholder, image: () => noteImages(current?.scope ?? opts.bookId) });
1154
+ let source = false;
1155
+ const state = el('span', 'note-state');
1156
+ const sourceBtn = iconButton('code', T.markdownSource, () => {
1157
+ if (source) editor.setMarkdown(textarea.value);
1158
+ else textarea.value = editor.getMarkdown();
1159
+ source = !source;
1160
+ sourceBtn.classList.toggle('on', source);
1161
+ (source ? editor.el : textarea).replaceWith(source ? textarea : editor.el);
1162
+ (source ? textarea : editor.el).focus();
1163
+ });
1164
+
1165
+ // Insert an asset: a picture from this workbook or the shared ones, by its path from the note.
1166
+ const insertBtn = iconButton('image', T.insertAsset, async () => {
1167
+ const [mine, shared] = await Promise.all([listAssets(opts.bookId), listAssets(SHARED)]);
1168
+ const pics = [...mine.map((a) => ({ a, scope: opts.bookId })), ...shared.map((a) => ({ a, scope: SHARED }))].filter(({ a }) => a.kind === 'image');
1169
+ if (!current) return;
1170
+ if (!pics.length) return toast(T.noAssetsYet);
1171
+ const here = current.scope;
1172
+ showMenu(
1173
+ pics.map(({ a, scope }) => ({
1174
+ label: scope === here ? stem(a.name) : `${stem(a.name)} · ${where(scope)}`,
1175
+ icon: 'image',
1176
+ action: () => {
1177
+ const md = `![${stem(a.name)}](${imageRef(here, scope, a.name)})`;
1178
+ if (source) {
1179
+ const at = textarea.selectionEnd;
1180
+ const before = textarea.value.slice(0, at);
1181
+ textarea.value = `${before}${before && !before.endsWith('\n') ? '\n\n' : ''}${md}\n${textarea.value.slice(at)}`;
1182
+ changed();
1183
+ } else editor.insertBlock(md);
1184
+ },
1185
+ })),
1186
+ insertBtn,
1187
+ );
1188
+ });
1189
+
1190
+ async function save() {
1191
+ if (!current || !dirty) return;
1192
+ const { scope, name } = current;
1193
+ const text = source ? textarea.value : editor.getMarkdown();
1194
+ dirty = false;
1195
+ state.textContent = T.saving;
1196
+ saving = writeNote(scope, name, text).then(
1197
+ () => {
1198
+ if (!dirty) state.textContent = T.saved;
1199
+ },
1200
+ (e: Error) => {
1201
+ dirty = true;
1202
+ state.textContent = e.message;
1203
+ },
1204
+ );
1205
+ await saving;
1206
+ }
1207
+ function changed() {
1208
+ dirty = true;
1209
+ state.textContent = T.unsaved;
1210
+ clearTimeout(timer);
1211
+ timer = window.setTimeout(() => void save(), 700);
1212
+ }
1213
+ textarea.addEventListener('input', changed);
1214
+ for (const target of [textarea, editor.el]) {
1215
+ target.addEventListener('keydown', (e) => {
1216
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
1217
+ e.preventDefault();
1218
+ clearTimeout(timer);
1219
+ void save();
1220
+ }
1221
+ });
1222
+ }
1223
+
1224
+ let notes: Entry[] = [];
1225
+ let favourites = new Set<string>();
1226
+ /** Note bodies for search and the overview, fetched once per change. */
1227
+ const bodies = new Map<string, { at: string; text: string }>();
1228
+ async function loadBodies() {
1229
+ await Promise.all(
1230
+ notes.map(async (n) => {
1231
+ const b = bodies.get(keyOf(n));
1232
+ if (b?.at === n.updatedAt) return;
1233
+ bodies.set(keyOf(n), { at: n.updatedAt, text: await readText(n.scope, n.name) });
1234
+ }),
1235
+ );
1236
+ }
1237
+
1238
+ function mark() {
1239
+ for (const n of side.list.querySelectorAll<HTMLElement>('.lib-item')) n.classList.toggle('on', Boolean(current) && n.dataset.key === keyOf(current!));
1240
+ }
1241
+
1242
+ async function open(scope: string, name: string) {
1243
+ const ticket = ++opening;
1244
+ clearTimeout(timer);
1245
+ await save();
1246
+ const text = await readText(scope, name);
1247
+ if (ticket !== opening) return;
1248
+ if (side.nav === 'home') {
1249
+ side.select('all', true);
1250
+ void renderList();
1251
+ }
1252
+ current = { scope, name };
1253
+ textarea.value = text;
1254
+ editor.setMarkdown(text);
1255
+ dirty = false;
1256
+ state.textContent = T.saved;
1257
+ const head = el('div', 'lib-detail-head note-head');
1258
+ // Download as the Markdown file, or as a PDF through the print dialog.
1259
+ const dl = iconButton('download', T.download, () =>
1260
+ showMenu(
1261
+ [
1262
+ {
1263
+ label: 'Markdown (.md)',
1264
+ icon: 'file',
1265
+ action: () => {
1266
+ const link = el('a');
1267
+ link.href = api('/file', { scope, name, download: '1' });
1268
+ link.click();
1269
+ },
1270
+ },
1271
+ { label: 'PDF', icon: 'download', action: () => printNote(source ? textarea.value : editor.getMarkdown(), stem(name), scope) },
1272
+ ],
1273
+ dl,
1274
+ ),
1275
+ );
1276
+ // The note's own first heading is its title; the bar only says where it lives.
1277
+ head.append(
1278
+ el('span', 'lib-scope', where(scope)),
1279
+ el('div', 'grow'),
1280
+ state,
1281
+ starButton(favourites.has(keyOf({ scope, name })), () => void toggleFavourite(scope, name)),
1282
+ insertBtn,
1283
+ sourceBtn,
1284
+ dl,
1285
+ deleteButton(scope, name, () => {
1286
+ current = null;
1287
+ void refresh();
1288
+ }),
1289
+ );
1290
+ main.replaceChildren(head, source ? textarea : editor.el);
1291
+ mark();
1292
+ if (source) textarea.focus();
1293
+ else editor.focus();
1294
+ }
1295
+
1296
+ /** The overview: favourites, then every note, newest first, each with its opening lines. */
1297
+ async function showHome() {
1298
+ const ticket = ++opening;
1299
+ clearTimeout(timer);
1300
+ await save();
1301
+ current = null;
1302
+ await loadBodies();
1303
+ if (ticket !== opening) return;
1304
+ const body = el('div', 'lib-page');
1305
+ const head = el('div', 'lib-page-head');
1306
+ head.append(el('h1', '', T.viewNotes), el('div', 'grow'));
1307
+ if (notes.length) head.append(primaryButton(T.newNote, 'plus', () => void newNote()));
1308
+ body.append(head);
1309
+ if (!notes.length) {
1310
+ const empty = el('div', 'lib-empty-state');
1311
+ empty.append(icon('file', 28), el('h3', '', T.noNotesYet), primaryButton(T.newNote, 'plus', () => void newNote()));
1312
+ body.append(empty);
1313
+ main.replaceChildren(body);
1314
+ mark();
1315
+ return;
1316
+ }
1317
+ const noteCard = (n: Entry) => {
1318
+ const c = el('button', 'note-card');
1319
+ c.type = 'button';
1320
+ c.dataset.key = keyOf(n);
1321
+ const text = bodies.get(keyOf(n))?.text ?? '';
1322
+ const lines = text
1323
+ .split('\n')
1324
+ .filter((l) => l.trim())
1325
+ .slice(1)
1326
+ .map((l) => l.replace(/!\[[^\]]*\]\([^)]*\)/g, '').replace(/^\s*(#+|[-*+]|\d+\.|>)\s+/, '').replace(/[*`_]+/g, ''))
1327
+ .join(' ')
1328
+ .replace(/\s+/g, ' ')
1329
+ .trim()
1330
+ .slice(0, 160);
1331
+ const top = el('span', 'note-card-title', n.title);
1332
+ if (favourites.has(keyOf(n))) top.prepend(icon('starFill', 12));
1333
+ c.append(top, el('span', 'note-card-text', lines), el('span', 'note-card-meta', `${where(n.scope)} · ${ago(n.updatedAt)}`));
1334
+ c.addEventListener('click', () => void open(n.scope, n.name));
1335
+ return c;
1336
+ };
1337
+ const section = (label: string, list: Entry[]) => {
1338
+ if (!list.length) return;
1339
+ const s = el('section', 'note-section');
1340
+ const grid = el('div', 'note-grid');
1341
+ grid.append(...list.map(noteCard));
1342
+ s.append(el('h3', '', label), grid);
1343
+ body.append(s);
1344
+ };
1345
+ section(T.notesFavorites, notes.filter((n) => favourites.has(keyOf(n))));
1346
+ section(T.notesRecent, newestFirst(notes));
1347
+ main.replaceChildren(body);
1348
+ mark();
1349
+ }
1350
+
1351
+ function showEmpty() {
1352
+ current = null;
1353
+ const empty = el('div', 'lib-empty-state');
1354
+ empty.append(icon('file', 28), el('h3', '', T.noNotesYet), primaryButton(T.newNote, 'plus', () => void newNote()));
1355
+ main.replaceChildren(empty);
1356
+ }
1357
+
1358
+ /** What the sidebar lists for Recent, Favorites or All. */
1359
+ function visible(): Entry[] {
1360
+ if (side.nav === 'recent') return newestFirst(notes);
1361
+ if (side.nav === 'fav') return notes.filter((n) => favourites.has(keyOf(n)));
1362
+ return notes;
1363
+ }
1364
+
1365
+ let searching = 0;
1366
+ async function renderList() {
1367
+ const q = side.query();
1368
+ const item = (n: Entry, meta: string | HTMLElement | null = null) => libItem(n, favourites.has(keyOf(n)), meta, () => void open(n.scope, n.name));
1369
+ if (q) {
1370
+ const ticket = ++searching;
1371
+ await loadBodies();
1372
+ if (ticket !== searching) return;
1373
+ const hits = notes
1374
+ .map((n) => {
1375
+ const inTitle = n.title.toLowerCase().includes(q);
1376
+ const s = snippet(bodies.get(keyOf(n))?.text ?? '', q);
1377
+ if (!inTitle && !s) return null;
1378
+ return { n, s: s ?? where(n.scope), rank: inTitle ? 0 : 1 };
1379
+ })
1380
+ .filter((x) => x !== null)
1381
+ .sort((a, b) => a.rank - b.rank || b.n.updatedAt.localeCompare(a.n.updatedAt));
1382
+ side.list.replaceChildren(...(hits.length ? hits.map((h) => item(h.n, h.s)) : [el('p', 'lib-empty', T.noMatches)]));
1383
+ return mark();
1384
+ }
1385
+ if (side.nav === 'home') return side.list.replaceChildren();
1386
+ const list = visible();
1387
+ if (!list.length) {
1388
+ side.list.replaceChildren(el('p', 'lib-empty', side.nav === 'fav' ? T.noFavorites : T.noNotesYet));
1389
+ return;
1390
+ }
1391
+ if (side.nav === 'all') {
1392
+ const groups: HTMLElement[] = [];
1393
+ for (const scope of [opts.bookId, SHARED]) {
1394
+ const mine = list.filter((n) => n.scope === scope);
1395
+ if (!mine.length) continue;
1396
+ const g = el('section', 'lib-group');
1397
+ g.dataset.scope = scope;
1398
+ g.append(el('h3', '', where(scope)), ...mine.map((n) => item(n)));
1399
+ groups.push(g);
1400
+ }
1401
+ side.list.replaceChildren(...groups);
1402
+ } else side.list.replaceChildren(...list.map((n) => item(n, `${where(n.scope)} · ${ago(n.updatedAt)}`)));
1403
+ mark();
1404
+ }
1405
+
1406
+ async function navigate(n: Nav) {
1407
+ await renderList();
1408
+ if (n === 'home') return showHome();
1409
+ if (current && notes.some((x) => keyOf(x) === keyOf(current!))) return;
1410
+ const first = visible()[0];
1411
+ if (first) await open(first.scope, first.name);
1412
+ else showEmpty();
1413
+ }
1414
+
1415
+ async function toggleFavourite(scope: string, name: string) {
1416
+ const on = !favourites.has(keyOf({ scope, name }));
1417
+ const next = await putFavourite(scope, name, on);
1418
+ if (!next) return;
1419
+ favourites = next;
1420
+ const star = main.querySelector<HTMLButtonElement>('.lib-star');
1421
+ if (star) {
1422
+ star.replaceChildren(icon(on ? 'starFill' : 'star'));
1423
+ star.classList.toggle('on', on);
1424
+ star.title = on ? T.unfavorite : T.favorite;
1425
+ }
1426
+ await renderList();
1427
+ }
1428
+
1429
+ /** Lists the notes; opens `prefer`, else keeps the open one, else Home or the first one listed. */
1430
+ async function refresh(prefer?: { scope: string; name: string }) {
1431
+ const [mine, shared, favs] = await Promise.all([listAssets(opts.bookId), listAssets(SHARED), loadFavourites()]);
1432
+ const toEntry = (scope: string) => (a: AssetEntry) => ({ scope, name: a.name, title: a.title || stem(a.name), updatedAt: a.updatedAt });
1433
+ notes = [...mine.filter((a) => a.kind === 'note').map(toEntry(opts.bookId)), ...shared.filter((a) => a.kind === 'note').map(toEntry(SHARED))];
1434
+ favourites = favs;
1435
+ const has = (t: { scope: string; name: string } | null | undefined) => Boolean(t && notes.some((x) => x.scope === t.scope && x.name === t.name));
1436
+ if (prefer && has(prefer)) {
1437
+ if (side.nav === 'home') side.select('all', true);
1438
+ await renderList();
1439
+ return open(prefer.scope, prefer.name);
1440
+ }
1441
+ await renderList();
1442
+ if (has(current)) return mark();
1443
+ if (side.nav === 'home') return showHome();
1444
+ const first = visible()[0] ?? notes[0];
1445
+ if (first) await open(first.scope, first.name);
1446
+ else showEmpty();
1447
+ }
1448
+
1449
+ async function newNote() {
1450
+ const v = await promptDialog({
1451
+ title: T.newNote,
1452
+ fields: [
1453
+ { name: 'title', label: T.title, value: '', validate: (x) => (x.trim() ? null : T.title) },
1454
+ { name: 'scope', label: T.saveIn, options: [{ value: opts.bookId, label: T.assetsThisBook }, { value: SHARED, label: T.assetsShared }], value: opts.bookId },
1455
+ ],
1456
+ ok: T.create,
1457
+ });
1458
+ if (!v) return;
1459
+ const t = v.title!.trim();
1460
+ const name = `${fileStem(t, 'note')}.md`;
1461
+ try {
1462
+ await save();
1463
+ await writeNote(v.scope!, name, `# ${t}\n\n`);
1464
+ await refresh({ scope: v.scope!, name });
1465
+ } catch (e) {
1466
+ toast((e as Error).message);
1467
+ }
1468
+ }
1469
+
1470
+ return {
1471
+ el: page,
1472
+ refresh: () => refresh(),
1473
+ async flush() {
1474
+ clearTimeout(timer);
1475
+ await save();
1476
+ await saving;
1477
+ },
1478
+ };
1479
+ }