@20baht/spreadsheet 0.0.0-stage → 0.2.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.
@@ -0,0 +1,902 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { html, nothing } from 'lit';
8
+ import { property, state } from 'lit/decorators.js';
9
+ import { BahtElement } from '@20baht/element';
10
+ import { addressOf, columnName, DEFAULT_COLUMNS, DEFAULT_ROWS, DEFAULT_WIDTH, emptyBook, extentOf, MAX_COLUMNS, MAX_ROWS, MAX_SHEETS, mergesOf, NUMBER_FORMATS, rangeName, } from '../book.js';
11
+ import { computeBook, displayText, inputText } from '../compute.js';
12
+ import { customElement } from '../define.js';
13
+ import { isError } from '../formula.js';
14
+ import { copied, openBook, savedBook, selectionOf, shownSheet, updateBook, } from '../session.js';
15
+ import { fromTsv, toTsv } from '../tsv.js';
16
+ export const SPREADSHEET_LABELS = {
17
+ bold: 'Bold',
18
+ italic: 'Italic',
19
+ underline: 'Underline',
20
+ textColor: 'Text colour',
21
+ fillColor: 'Fill colour',
22
+ noFill: 'No fill',
23
+ alignLeft: 'Align left',
24
+ alignCenter: 'Align centre',
25
+ alignRight: 'Align right',
26
+ borderAll: 'All borders',
27
+ borderOuter: 'Outside borders',
28
+ borderNone: 'No border',
29
+ merge: 'Merge cells',
30
+ unmerge: 'Unmerge cells',
31
+ insertRow: 'Insert row above',
32
+ insertColumn: 'Insert column left',
33
+ removeRow: 'Delete row',
34
+ removeColumn: 'Delete column',
35
+ fillHandle: 'Drag to fill',
36
+ format: 'Number format',
37
+ formatGeneral: 'General',
38
+ formatNumber: '1,234.50',
39
+ formatInteger: '1,235',
40
+ formatPercent: '12.5%',
41
+ formatDate: '2026-12-31',
42
+ formatDateTime: '2026-12-31 14:30',
43
+ undo: 'Undo',
44
+ redo: 'Redo',
45
+ cell: 'Selected cells',
46
+ formula: 'What the cell holds',
47
+ addSheet: 'Add sheet',
48
+ removeSheet: 'Remove sheet',
49
+ renameSheet: 'Sheet name',
50
+ dataSheet: 'Data',
51
+ refresh: 'Refresh data',
52
+ loading: 'Loading data…',
53
+ loadFailed: 'The data could not be loaded.',
54
+ readOnlyData: 'This sheet shows data as it is now. Use it from another sheet with a formula.',
55
+ };
56
+ const ARROWS = {
57
+ ArrowUp: 'up',
58
+ ArrowDown: 'down',
59
+ ArrowLeft: 'left',
60
+ ArrowRight: 'right',
61
+ };
62
+ const WRITES = new Set([
63
+ 'edit',
64
+ 'set',
65
+ 'clear',
66
+ 'paste',
67
+ 'style',
68
+ 'border',
69
+ 'merge',
70
+ 'unmerge',
71
+ 'width',
72
+ 'spread',
73
+ 'insert',
74
+ 'remove',
75
+ 'add-sheet',
76
+ 'rename-sheet',
77
+ 'remove-sheet',
78
+ 'undo',
79
+ 'redo',
80
+ ]);
81
+ const ROW_HEIGHT = 26;
82
+ const ROWS_SHOWN = 40;
83
+ const OVERSCAN = 8;
84
+ const textOf = (event) => event.target.value;
85
+ const cellOf = (sheet, address) => Object.hasOwn(sheet.cells, address) ? sheet.cells[address] : undefined;
86
+ const holds = (range, at) => range !== undefined &&
87
+ at.row >= range.top &&
88
+ at.row <= range.bottom &&
89
+ at.column >= range.left &&
90
+ at.column <= range.right;
91
+ function inkOn(fill) {
92
+ const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((at) => parseInt(fill.slice(at, at + 2), 16));
93
+ return red * 0.299 + green * 0.587 + blue * 0.114 > 150 ? '#1a2233' : '#ffffff';
94
+ }
95
+ const ALIGN_PATHS = {
96
+ left: 'M2 3h12M2 6.5h7M2 10h12M2 13.5h7',
97
+ center: 'M2 3h12M4.5 6.5h7M2 10h12M4.5 13.5h7',
98
+ right: 'M2 3h12M7 6.5h7M2 10h12M7 13.5h7',
99
+ };
100
+ const BORDERS = [
101
+ { sides: 'all', label: 'borderAll', path: 'M2 2h12v12H2zM8 2v12M2 8h12' },
102
+ { sides: 'outer', label: 'borderOuter', path: 'M2 2h12v12H2z' },
103
+ {
104
+ sides: 'none',
105
+ label: 'borderNone',
106
+ path: 'M2 2h1.5M6 2h1.5M10 2h1.5M14 2v1.5M14 6v1.5M14 10v1.5M14 14h-1.5M10 14H8.5M6 14H4.5M2 14v-1.5M2 10V8.5M2 6V4.5',
107
+ },
108
+ ];
109
+ const STRUCTURE = [
110
+ {
111
+ name: 'insert-row',
112
+ label: 'insertRow',
113
+ msg: { type: 'insert', axis: 'row' },
114
+ path: 'M2 3h12M2 13h12M8 5.5v5M5.5 8h5',
115
+ },
116
+ {
117
+ name: 'insert-column',
118
+ label: 'insertColumn',
119
+ msg: { type: 'insert', axis: 'column' },
120
+ path: 'M3 2v12M13 2v12M8 5.5v5M5.5 8h5',
121
+ },
122
+ {
123
+ name: 'remove-row',
124
+ label: 'removeRow',
125
+ msg: { type: 'remove', axis: 'row' },
126
+ path: 'M2 3h12M2 13h12M5.5 8h5',
127
+ },
128
+ {
129
+ name: 'remove-column',
130
+ label: 'removeColumn',
131
+ msg: { type: 'remove', axis: 'column' },
132
+ path: 'M3 2v12M13 2v12M5.5 8h5',
133
+ },
134
+ ];
135
+ const icon = (path) => html `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
136
+ <path d=${path} fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
137
+ </svg>`;
138
+ let BahtSpreadsheet = class BahtSpreadsheet extends BahtElement {
139
+ constructor() {
140
+ super(...arguments);
141
+ this.value = emptyBook();
142
+ this.readonly = false;
143
+ this.load = undefined;
144
+ this.labels = {};
145
+ this.session = openBook(this.value);
146
+ this.first = 0;
147
+ this.pending = new Set();
148
+ this.failures = new Set();
149
+ this.renaming = null;
150
+ this.resizing = null;
151
+ this.filling = null;
152
+ this.menu = null;
153
+ this.ownValue = false;
154
+ this.stale = false;
155
+ this.dragging = false;
156
+ this.computed = null;
157
+ this.scrolled = (event) => {
158
+ const first = Math.max(0, Math.floor(event.target.scrollTop / ROW_HEIGHT) - OVERSCAN);
159
+ if (Math.abs(first - this.first) >= OVERSCAN / 2 || first === 0)
160
+ this.first = first;
161
+ };
162
+ this.gridKey = (event) => {
163
+ if (this.session.editing !== null)
164
+ return;
165
+ if (this.onKey(event))
166
+ event.preventDefault();
167
+ };
168
+ this.editorKey = (event) => {
169
+ event.stopPropagation();
170
+ const moves = event.shiftKey
171
+ ? { Enter: 'up', Tab: 'left' }
172
+ : { Enter: 'down', Tab: 'right' };
173
+ const direction = moves[event.key];
174
+ if (direction) {
175
+ event.preventDefault();
176
+ this.send({ type: 'commit' });
177
+ this.send({ type: 'move', direction });
178
+ this.grid()?.focus();
179
+ }
180
+ else if (event.key === 'Escape') {
181
+ event.preventDefault();
182
+ this.send({ type: 'cancel' });
183
+ this.grid()?.focus();
184
+ }
185
+ };
186
+ this.barKey = (event) => {
187
+ if (event.key === 'Enter') {
188
+ event.preventDefault();
189
+ this.send({ type: 'commit' });
190
+ this.grid()?.focus();
191
+ }
192
+ else if (event.key === 'Escape') {
193
+ event.preventDefault();
194
+ this.send({ type: 'cancel' });
195
+ this.grid()?.focus();
196
+ }
197
+ };
198
+ this.barInput = (event) => {
199
+ if (this.session.editing === null)
200
+ this.send({ type: 'edit' });
201
+ this.send({ type: 'type', text: textOf(event) });
202
+ };
203
+ this.shownText = (cell, at) => displayText(this.values.at(this.session.sheet, at.row, at.column), cell?.style);
204
+ this.copy = (event) => {
205
+ if (this.session.editing !== null)
206
+ return;
207
+ event.preventDefault();
208
+ event.clipboardData?.setData('text/plain', toTsv(copied(this.session, this.shownText)));
209
+ if (event.type === 'cut')
210
+ this.send({ type: 'clear' });
211
+ };
212
+ this.paste = (event) => {
213
+ if (this.session.editing !== null)
214
+ return;
215
+ const text = event.clipboardData?.getData('text/plain') ?? '';
216
+ event.preventDefault();
217
+ if (text !== '')
218
+ this.send({ type: 'paste', cells: fromTsv(text) });
219
+ };
220
+ this.pointerDown = (event) => {
221
+ const cell = this.placeOf(event);
222
+ if (!cell || event.target.closest('.baht-spreadsheet-editor'))
223
+ return;
224
+ if (this.session.editing !== null)
225
+ this.send({ type: 'commit' });
226
+ this.dragging = true;
227
+ this.send({ type: 'select', cell, extend: event.shiftKey });
228
+ this.grid()?.focus();
229
+ event.preventDefault();
230
+ };
231
+ this.fillStart = (event) => {
232
+ event.preventDefault();
233
+ event.stopPropagation();
234
+ const from = selectionOf(this.session);
235
+ this.filling = { from, to: from };
236
+ const done = () => {
237
+ window.removeEventListener('pointerup', done);
238
+ const { filling } = this;
239
+ this.filling = null;
240
+ if (filling)
241
+ this.send({ type: 'spread', ...filling });
242
+ this.grid()?.focus();
243
+ };
244
+ window.addEventListener('pointerup', done);
245
+ };
246
+ this.pointerOver = (event) => {
247
+ if (this.filling) {
248
+ const over = this.placeOf(event);
249
+ if (over)
250
+ this.filling = { ...this.filling, to: this.fillTo(this.filling.from, over) };
251
+ return;
252
+ }
253
+ if (!this.dragging || event.buttons === 0) {
254
+ this.dragging = false;
255
+ return;
256
+ }
257
+ const cell = this.placeOf(event);
258
+ if (cell)
259
+ this.send({ type: 'select', cell, extend: true });
260
+ };
261
+ this.contextMenu = (event) => {
262
+ const cell = this.placeOf(event);
263
+ const sheet = shownSheet(this.session);
264
+ if (!cell || !sheet || sheet.source || this.readonly)
265
+ return;
266
+ event.preventDefault();
267
+ const selection = selectionOf(this.session);
268
+ const inside = holds(selection, cell);
269
+ if (!inside)
270
+ this.send({ type: 'select', cell });
271
+ const box = this.getBoundingClientRect();
272
+ this.menu = { x: event.clientX - box.left, y: event.clientY - box.top };
273
+ window.addEventListener('pointerdown', this.menuAway, true);
274
+ };
275
+ this.menuAway = (event) => {
276
+ const inside = event.target instanceof Element && event.target.closest('.baht-spreadsheet-menu');
277
+ if (!inside)
278
+ this.closeMenu();
279
+ };
280
+ this.doubleClick = (event) => {
281
+ if (this.placeOf(event))
282
+ this.send({ type: 'edit' });
283
+ };
284
+ }
285
+ get book() {
286
+ return this.session.book;
287
+ }
288
+ async refresh(sheet) {
289
+ const { load } = this;
290
+ if (!load)
291
+ return;
292
+ const sheets = this.session.book.sheets.filter((candidate) => candidate.source && (sheet === undefined || candidate.key === sheet));
293
+ await Promise.all(sheets.map(async (target) => {
294
+ this.pending = new Set([...this.pending, target.key]);
295
+ this.failures = new Set([...this.failures].filter((key) => key !== target.key));
296
+ try {
297
+ const data = await load(target.source, target);
298
+ this.session = updateBook(this.session, { type: 'fill', sheet: target.key, data }).state;
299
+ }
300
+ catch {
301
+ this.failures = new Set([...this.failures, target.key]);
302
+ }
303
+ this.pending = new Set([...this.pending].filter((key) => key !== target.key));
304
+ }));
305
+ }
306
+ async addDataSheet(name, source) {
307
+ if (this.readonly)
308
+ return;
309
+ this.send({ type: 'add-sheet', name, source });
310
+ await this.refresh(this.session.sheet);
311
+ }
312
+ get words() {
313
+ return { ...SPREADSHEET_LABELS, ...this.labels };
314
+ }
315
+ get values() {
316
+ if (this.computed?.book !== this.session.book)
317
+ this.computed = { book: this.session.book, values: computeBook(this.session.book) };
318
+ return this.computed.values;
319
+ }
320
+ willUpdate(changed) {
321
+ if (changed.has('value') && !this.ownValue) {
322
+ this.session = openBook(this.value, this.session.sheet);
323
+ this.first = 0;
324
+ this.stale = true;
325
+ }
326
+ this.ownValue = false;
327
+ }
328
+ updated() {
329
+ if (this.stale) {
330
+ this.stale = false;
331
+ void this.refresh();
332
+ }
333
+ const editor = this.querySelector('.baht-spreadsheet-editor, .baht-spreadsheet-rename');
334
+ if (editor && document.activeElement !== editor && !this.barFocused()) {
335
+ editor.focus();
336
+ editor.setSelectionRange(editor.value.length, editor.value.length);
337
+ }
338
+ }
339
+ barFocused() {
340
+ return document.activeElement?.classList.contains('baht-spreadsheet-bar-input') === true;
341
+ }
342
+ send(msg) {
343
+ if (this.readonly && WRITES.has(msg.type))
344
+ return;
345
+ const { state: next, changed } = updateBook(this.session, msg);
346
+ this.session = next;
347
+ this.reveal();
348
+ if (!changed)
349
+ return;
350
+ this.ownValue = true;
351
+ this.value = savedBook(next.book);
352
+ this.emit('baht-change', { value: this.value });
353
+ }
354
+ grid() {
355
+ return this.querySelector('.baht-spreadsheet-grid');
356
+ }
357
+ reveal() {
358
+ const box = this.querySelector('.baht-spreadsheet-scroll');
359
+ if (!box || box.clientHeight === 0)
360
+ return;
361
+ const top = this.session.end.row * ROW_HEIGHT;
362
+ const shown = box.clientHeight - ROW_HEIGHT * 2;
363
+ if (top < box.scrollTop)
364
+ box.scrollTop = top;
365
+ else if (top > box.scrollTop + shown)
366
+ box.scrollTop = top - shown;
367
+ }
368
+ onKey(event) {
369
+ const command = event.ctrlKey || event.metaKey;
370
+ const direction = ARROWS[event.key];
371
+ if (direction)
372
+ this.send({ type: 'move', direction, extend: event.shiftKey });
373
+ else if (event.key === 'Tab')
374
+ this.send({ type: 'move', direction: event.shiftKey ? 'left' : 'right' });
375
+ else if (event.key === 'Enter')
376
+ this.send({ type: 'move', direction: event.shiftKey ? 'up' : 'down' });
377
+ else if (event.key === 'F2')
378
+ this.send({ type: 'edit' });
379
+ else if (event.key === 'Delete' || event.key === 'Backspace')
380
+ this.send({ type: 'clear' });
381
+ else if (command)
382
+ return this.shortcut(event);
383
+ else if (event.key.length === 1 && !event.altKey)
384
+ this.send({ type: 'edit', text: event.key });
385
+ else
386
+ return false;
387
+ return true;
388
+ }
389
+ shortcut(event) {
390
+ const key = event.key.toLowerCase();
391
+ if (key === 'z')
392
+ this.send({ type: event.shiftKey ? 'redo' : 'undo' });
393
+ else if (key === 'y')
394
+ this.send({ type: 'redo' });
395
+ else if (key === 'b')
396
+ this.toggle('bold');
397
+ else if (key === 'i')
398
+ this.toggle('italic');
399
+ else if (key === 'u')
400
+ this.toggle('underline');
401
+ else if (key === 'd' || key === 'r')
402
+ this.fillFromEdge(key === 'd');
403
+ else
404
+ return false;
405
+ return true;
406
+ }
407
+ fillFromEdge(down) {
408
+ const to = selectionOf(this.session);
409
+ const from = down ? { ...to, bottom: to.top } : { ...to, right: to.left };
410
+ this.send({ type: 'spread', from, to });
411
+ }
412
+ placeOf(event) {
413
+ const cell = event.target.closest('td[data-row]');
414
+ if (!cell)
415
+ return null;
416
+ return { row: Number(cell.dataset.row), column: Number(cell.dataset.column) };
417
+ }
418
+ fillTo(from, cell) {
419
+ const rows = Math.max(from.top - cell.row, cell.row - from.bottom, 0);
420
+ const columns = Math.max(from.left - cell.column, cell.column - from.right, 0);
421
+ return rows >= columns
422
+ ? { ...from, top: Math.min(from.top, cell.row), bottom: Math.max(from.bottom, cell.row) }
423
+ : {
424
+ ...from,
425
+ left: Math.min(from.left, cell.column),
426
+ right: Math.max(from.right, cell.column),
427
+ };
428
+ }
429
+ closeMenu() {
430
+ this.menu = null;
431
+ window.removeEventListener('pointerdown', this.menuAway, true);
432
+ }
433
+ disconnectedCallback() {
434
+ super.disconnectedCallback();
435
+ this.closeMenu();
436
+ }
437
+ menuBox() {
438
+ if (!this.menu)
439
+ return nothing;
440
+ const words = this.words;
441
+ return html `<div
442
+ class="baht-spreadsheet-menu"
443
+ role="menu"
444
+ style="left:${this.menu.x}px;top:${this.menu.y}px"
445
+ @keydown=${(event) => {
446
+ if (event.key !== 'Escape')
447
+ return;
448
+ this.closeMenu();
449
+ this.grid()?.focus();
450
+ }}
451
+ >
452
+ ${STRUCTURE.map((item) => html `<button
453
+ type="button"
454
+ role="menuitem"
455
+ data-menu=${item.name}
456
+ @click=${() => {
457
+ this.closeMenu();
458
+ this.send(item.msg);
459
+ this.grid()?.focus();
460
+ }}
461
+ >
462
+ ${icon(item.path)} ${words[item.label]}
463
+ </button>`)}
464
+ </div>`;
465
+ }
466
+ resizeStart(event, column, width) {
467
+ event.preventDefault();
468
+ event.stopPropagation();
469
+ const from = event.clientX;
470
+ const move = (moved) => {
471
+ this.resizing = { column, width: Math.max(24, width + moved.clientX - from) };
472
+ };
473
+ const done = () => {
474
+ window.removeEventListener('pointermove', move);
475
+ window.removeEventListener('pointerup', done);
476
+ const { resizing } = this;
477
+ this.resizing = null;
478
+ if (resizing)
479
+ this.send({ type: 'width', column, width: resizing.width });
480
+ };
481
+ window.addEventListener('pointermove', move);
482
+ window.addEventListener('pointerup', done);
483
+ }
484
+ get activeStyle() {
485
+ const sheet = shownSheet(this.session);
486
+ return (sheet && cellOf(sheet, addressOf(this.session.active))?.style) ?? {};
487
+ }
488
+ toggle(flag) {
489
+ this.send({ type: 'style', style: { [flag]: this.activeStyle[flag] === true ? null : true } });
490
+ }
491
+ look(style) {
492
+ this.send({ type: 'style', style });
493
+ }
494
+ render() {
495
+ const sheet = shownSheet(this.session);
496
+ return html `<div class="baht-spreadsheet" ?data-readonly=${this.readonly}>
497
+ ${sheet ? [this.tools(sheet), this.bar(sheet), this.notice(sheet), this.table(sheet)] : nothing}
498
+ ${this.tabs()} ${this.menuBox()}
499
+ </div>`;
500
+ }
501
+ tool(label, content, click, options) {
502
+ return html `<button
503
+ type="button"
504
+ class="baht-spreadsheet-tool"
505
+ data-tool=${options.name}
506
+ title=${label}
507
+ aria-label=${label}
508
+ aria-pressed=${options.pressed === undefined ? nothing : String(options.pressed)}
509
+ ?disabled=${options.disabled === true}
510
+ @click=${click}
511
+ >
512
+ ${content}
513
+ </button>`;
514
+ }
515
+ tools(sheet) {
516
+ if (this.readonly)
517
+ return nothing;
518
+ const words = this.words;
519
+ const style = this.activeStyle;
520
+ const locked = sheet.source !== undefined;
521
+ const selection = selectionOf(this.session);
522
+ const isMerged = mergesOf(sheet).some((merge) => merge.top === selection.top && merge.left === selection.left);
523
+ const one = selection.top === selection.bottom && selection.left === selection.right;
524
+ const flag = (name, letter) => this.tool(words[name], html `<span data-look=${name}>${letter}</span>`, () => {
525
+ this.toggle(name);
526
+ }, { name, pressed: style[name] === true, disabled: locked });
527
+ const colour = (name, label, fallback) => html `<label class="baht-spreadsheet-colour" title=${label}>
528
+ <span data-swatch=${name} style="--swatch:${style[name] ?? fallback}">A</span>
529
+ <input
530
+ type="color"
531
+ aria-label=${label}
532
+ data-tool=${name}
533
+ .value=${style[name] ?? fallback}
534
+ ?disabled=${locked}
535
+ @input=${(event) => {
536
+ this.look({ [name]: textOf(event) });
537
+ }}
538
+ />
539
+ </label>`;
540
+ const align = (to, label) => this.tool(label, icon(ALIGN_PATHS[to]), () => {
541
+ this.look({ align: style.align === to ? null : to });
542
+ }, { name: `align-${to}`, pressed: style.align === to, disabled: locked });
543
+ return html `<div class="baht-spreadsheet-tools" role="toolbar">
544
+ ${this.tool(words.undo, icon('M6 3 2.5 6.5 6 10M3 6.5h6.5a4 4 0 0 1 0 8H7'), () => {
545
+ this.send({ type: 'undo' });
546
+ }, { name: 'undo', disabled: this.session.undo.length === 0 })}
547
+ ${this.tool(words.redo, icon('M10 3l3.5 3.5L10 10M13 6.5H6.5a4 4 0 0 0 0 8H9'), () => {
548
+ this.send({ type: 'redo' });
549
+ }, { name: 'redo', disabled: this.session.redo.length === 0 })}
550
+ <span class="baht-spreadsheet-gap"></span>
551
+ ${flag('bold', 'B')} ${flag('italic', 'I')} ${flag('underline', 'U')}
552
+ <span class="baht-spreadsheet-gap"></span>
553
+ ${colour('color', words.textColor, '#1a2233')} ${colour('fill', words.fillColor, '#ffffff')}
554
+ ${this.tool(words.noFill, icon('M3 13 13 3M3 3h10v10H3z'), () => {
555
+ this.look({ fill: null, color: null });
556
+ }, { name: 'no-fill', disabled: locked })}
557
+ <span class="baht-spreadsheet-gap"></span>
558
+ ${align('left', words.alignLeft)} ${align('center', words.alignCenter)}
559
+ ${align('right', words.alignRight)}
560
+ <span class="baht-spreadsheet-gap"></span>
561
+ ${BORDERS.map((item) => this.tool(words[item.label], icon(item.path), () => {
562
+ this.send({ type: 'border', sides: item.sides });
563
+ }, { name: `border-${item.sides}`, disabled: locked }))}
564
+ ${this.tool(isMerged ? words.unmerge : words.merge, icon('M2 3h12v10H2zM5 8h6M5 8l2-2M5 8l2 2M11 8 9 6M11 8l-2 2'), () => {
565
+ this.send({ type: isMerged ? 'unmerge' : 'merge' });
566
+ }, { name: 'merge', pressed: isMerged, disabled: locked || (one && !isMerged) })}
567
+ <span class="baht-spreadsheet-gap"></span>
568
+ ${STRUCTURE.map((item) => this.tool(words[item.label], icon(item.path), () => {
569
+ this.send(item.msg);
570
+ }, { name: item.name, disabled: locked }))}
571
+ <span class="baht-spreadsheet-gap"></span>
572
+ <select
573
+ class="baht-spreadsheet-format"
574
+ aria-label=${words.format}
575
+ title=${words.format}
576
+ ?disabled=${locked}
577
+ @change=${(event) => {
578
+ const format = NUMBER_FORMATS.find((known) => known === textOf(event));
579
+ this.look({ format: format ?? null });
580
+ }}
581
+ >
582
+ <option value="" ?selected=${style.format === undefined}>${words.formatGeneral}</option>
583
+ ${NUMBER_FORMATS.map((format) => html `<option value=${format} ?selected=${style.format === format}>
584
+ ${this.formatLabel(format)}
585
+ </option>`)}
586
+ </select>
587
+ </div>`;
588
+ }
589
+ formatLabel(format) {
590
+ const words = this.words;
591
+ const labels = {
592
+ number: words.formatNumber,
593
+ integer: words.formatInteger,
594
+ percent: words.formatPercent,
595
+ date: words.formatDate,
596
+ datetime: words.formatDateTime,
597
+ };
598
+ return labels[format];
599
+ }
600
+ bar(sheet) {
601
+ const { session, words } = this;
602
+ const held = session.editing ?? inputText(cellOf(sheet, addressOf(session.active)));
603
+ return html `<div class="baht-spreadsheet-bar">
604
+ <span class="baht-spreadsheet-name" aria-label=${words.cell}>
605
+ ${rangeName(selectionOf(session))}
606
+ </span>
607
+ <span class="baht-spreadsheet-fx" aria-hidden="true">fx</span>
608
+ <input
609
+ class="baht-spreadsheet-bar-input"
610
+ aria-label=${words.formula}
611
+ .value=${held}
612
+ ?readonly=${this.readonly || sheet.source !== undefined}
613
+ @input=${this.barInput}
614
+ @keydown=${this.barKey}
615
+ @blur=${() => {
616
+ if (this.session.editing !== null)
617
+ this.send({ type: 'commit' });
618
+ }}
619
+ />
620
+ </div>`;
621
+ }
622
+ notice(sheet) {
623
+ if (!sheet.source)
624
+ return nothing;
625
+ const words = this.words;
626
+ const failed = this.failures.has(sheet.key);
627
+ const text = this.pending.has(sheet.key)
628
+ ? words.loading
629
+ : failed
630
+ ? words.loadFailed
631
+ : words.readOnlyData;
632
+ return html `<div class="baht-spreadsheet-notice" role="status" ?data-failed=${failed}>
633
+ <span>${text}</span>
634
+ <button
635
+ type="button"
636
+ class="baht-spreadsheet-tool"
637
+ data-tool="refresh"
638
+ ?disabled=${this.pending.has(sheet.key) || !this.load}
639
+ @click=${() => {
640
+ void this.refresh(sheet.key);
641
+ }}
642
+ >
643
+ ${words.refresh}
644
+ </button>
645
+ </div>`;
646
+ }
647
+ widthOf(sheet, column) {
648
+ if (this.resizing?.column === column)
649
+ return this.resizing.width;
650
+ return sheet.widths?.[columnName(column)] ?? DEFAULT_WIDTH;
651
+ }
652
+ table(sheet) {
653
+ const { session } = this;
654
+ const extent = extentOf(sheet);
655
+ const columns = Math.min(MAX_COLUMNS, Math.max(DEFAULT_COLUMNS, extent.columns + 2, session.active.column + 2, session.end.column + 2));
656
+ const rows = Math.min(MAX_ROWS, Math.max(DEFAULT_ROWS, extent.rows + 20, session.active.row + 2, session.end.row + 2));
657
+ const box = this.querySelector('.baht-spreadsheet-scroll');
658
+ const shown = box && box.clientHeight > 0 ? Math.ceil(box.clientHeight / ROW_HEIGHT) : ROWS_SHOWN;
659
+ const first = Math.min(this.first, Math.max(0, rows - shown));
660
+ const last = Math.min(rows, first + shown + OVERSCAN * 2);
661
+ const selection = selectionOf(session);
662
+ const merges = mergesOf(sheet).filter((merge) => merge.bottom >= first && merge.top < last);
663
+ const numbers = Array.from({ length: columns }, (_, column) => column);
664
+ return html `<div class="baht-spreadsheet-scroll" @scroll=${this.scrolled}>
665
+ <table
666
+ class="baht-spreadsheet-grid"
667
+ role="grid"
668
+ tabindex="0"
669
+ aria-rowcount=${rows}
670
+ aria-colcount=${columns}
671
+ style="--baht-spreadsheet-row:${ROW_HEIGHT}px"
672
+ @keydown=${this.gridKey}
673
+ @copy=${this.copy}
674
+ @cut=${this.copy}
675
+ @paste=${this.paste}
676
+ @pointerdown=${this.pointerDown}
677
+ @pointerover=${this.pointerOver}
678
+ @dblclick=${this.doubleClick}
679
+ @contextmenu=${this.contextMenu}
680
+ >
681
+ <colgroup>
682
+ <col class="baht-spreadsheet-corner" />
683
+ ${numbers.map((column) => html `<col style="width:${this.widthOf(sheet, column)}px" />`)}
684
+ </colgroup>
685
+ <thead>
686
+ <tr>
687
+ <th class="baht-spreadsheet-corner"></th>
688
+ ${numbers.map((column) => html `<th
689
+ scope="col"
690
+ ?data-selected=${column >= selection.left && column <= selection.right}
691
+ >
692
+ ${columnName(column)}
693
+ <span
694
+ class="baht-spreadsheet-resize"
695
+ @pointerdown=${(event) => {
696
+ this.resizeStart(event, column, this.widthOf(sheet, column));
697
+ }}
698
+ ></span>
699
+ </th>`)}
700
+ </tr>
701
+ </thead>
702
+ <tbody>
703
+ ${first > 0
704
+ ? html `<tr class="baht-spreadsheet-spacer" style="height:${first * ROW_HEIGHT}px">
705
+ <td colspan=${columns + 1}></td>
706
+ </tr>`
707
+ : nothing}
708
+ ${Array.from({ length: last - first }, (_, i) => this.row(sheet, first + i, numbers, { selection, merges, first, last }))}
709
+ ${last < rows
710
+ ? html `<tr
711
+ class="baht-spreadsheet-spacer"
712
+ style="height:${(rows - last) * ROW_HEIGHT}px"
713
+ >
714
+ <td colspan=${columns + 1}></td>
715
+ </tr>`
716
+ : nothing}
717
+ </tbody>
718
+ </table>
719
+ </div>`;
720
+ }
721
+ row(sheet, row, columns, view) {
722
+ const { selection } = view;
723
+ return html `<tr aria-rowindex=${row + 1}>
724
+ <th scope="row" ?data-selected=${row >= selection.top && row <= selection.bottom}>
725
+ ${row + 1}
726
+ </th>
727
+ ${columns.map((column) => {
728
+ const merge = view.merges.find((range) => row >= range.top &&
729
+ row <= range.bottom &&
730
+ column >= range.left &&
731
+ column <= range.right);
732
+ if (!merge)
733
+ return this.cell(sheet, { row, column }, view.selection, 1, 1);
734
+ if (row !== Math.max(merge.top, view.first) || column !== merge.left)
735
+ return nothing;
736
+ return this.cell(sheet, { row: merge.top, column: merge.left }, view.selection, Math.min(merge.bottom, view.last - 1) - row + 1, Math.min(merge.right, columns.length - 1) - merge.left + 1);
737
+ })}
738
+ </tr>`;
739
+ }
740
+ lines(sheet, at, sides = []) {
741
+ const has = (row, column, side) => cellOf(sheet, addressOf({ row, column }))?.style?.border?.includes(side) === true;
742
+ return sides.map((side) => {
743
+ if (side === 'bottom' || side === 'right')
744
+ return `border-${side}-color:var(--baht-spreadsheet-line)`;
745
+ const drawn = side === 'top'
746
+ ? at.row > 0 && has(at.row - 1, at.column, 'bottom')
747
+ : at.column > 0 && has(at.row, at.column - 1, 'right');
748
+ return drawn ? '' : `--baht-spreadsheet-${side}:1px`;
749
+ });
750
+ }
751
+ handle(sheet) {
752
+ if (this.readonly || sheet.source || this.session.editing !== null)
753
+ return nothing;
754
+ return html `<span
755
+ class="baht-spreadsheet-handle"
756
+ title=${this.words.fillHandle}
757
+ @pointerdown=${this.fillStart}
758
+ ></span>`;
759
+ }
760
+ cell(sheet, at, selection, rowspan, colspan) {
761
+ const { session } = this;
762
+ const cell = cellOf(sheet, addressOf(at));
763
+ const style = cell?.style ?? {};
764
+ const value = this.values.at(sheet.key, at.row, at.column);
765
+ const active = session.active.row === at.row && session.active.column === at.column;
766
+ const selected = holds(selection, at);
767
+ const align = style.align ?? (typeof value === 'number' ? 'right' : undefined);
768
+ const filling = holds(this.filling?.to, at);
769
+ const corner = at.row + rowspan - 1 === selection.bottom && at.column + colspan - 1 === selection.right;
770
+ const handle = corner ? this.handle(sheet) : nothing;
771
+ const css = [
772
+ style.bold === true ? 'font-weight:700' : '',
773
+ style.italic === true ? 'font-style:italic' : '',
774
+ style.underline === true ? 'text-decoration:underline' : '',
775
+ `color:${style.color ?? (style.fill === undefined ? '' : inkOn(style.fill))}`,
776
+ style.fill === undefined ? '' : `background-color:${style.fill}`,
777
+ align === undefined ? '' : `text-align:${align}`,
778
+ ...this.lines(sheet, at, style.border),
779
+ ]
780
+ .filter((rule) => rule !== '' && rule !== 'color:')
781
+ .join(';');
782
+ return html `<td
783
+ role="gridcell"
784
+ data-row=${at.row}
785
+ data-column=${at.column}
786
+ rowspan=${rowspan > 1 ? rowspan : nothing}
787
+ colspan=${colspan > 1 ? colspan : nothing}
788
+ ?data-selected=${selected}
789
+ ?data-active=${active}
790
+ ?data-error=${isError(value)}
791
+ ?data-filling=${filling}
792
+ aria-selected=${String(selected)}
793
+ style=${css || nothing}
794
+ >
795
+ ${active && session.editing !== null
796
+ ? html `<input
797
+ class="baht-spreadsheet-editor"
798
+ .value=${session.editing}
799
+ @input=${(event) => {
800
+ this.send({ type: 'type', text: textOf(event) });
801
+ }}
802
+ @keydown=${this.editorKey}
803
+ @blur=${() => {
804
+ if (this.session.editing !== null && !this.barFocused())
805
+ this.send({ type: 'commit' });
806
+ }}
807
+ />`
808
+ : displayText(value, style)}${handle}
809
+ </td>`;
810
+ }
811
+ tabs() {
812
+ const { session, words } = this;
813
+ const sheets = session.book.sheets;
814
+ return html `<div class="baht-spreadsheet-tabs" role="tablist">
815
+ ${sheets.map((sheet) => this.renaming === sheet.key
816
+ ? html `<input
817
+ class="baht-spreadsheet-rename"
818
+ aria-label=${words.renameSheet}
819
+ .value=${sheet.name}
820
+ @keydown=${(event) => {
821
+ if (event.key === 'Enter')
822
+ event.target.blur();
823
+ else if (event.key === 'Escape')
824
+ this.renaming = null;
825
+ }}
826
+ @blur=${(event) => {
827
+ if (this.renaming === null)
828
+ return;
829
+ this.renaming = null;
830
+ this.send({ type: 'rename-sheet', sheet: sheet.key, name: textOf(event) });
831
+ }}
832
+ />`
833
+ : html `<button
834
+ type="button"
835
+ role="tab"
836
+ class="baht-spreadsheet-tab"
837
+ data-sheet=${sheet.key}
838
+ aria-selected=${String(sheet.key === session.sheet)}
839
+ ?data-source=${sheet.source !== undefined}
840
+ @click=${() => {
841
+ this.send({ type: 'show', sheet: sheet.key });
842
+ this.first = 0;
843
+ }}
844
+ @dblclick=${() => {
845
+ if (!this.readonly)
846
+ this.renaming = sheet.key;
847
+ }}
848
+ >
849
+ ${sheet.source ? html `<span class="baht-spreadsheet-badge">${words.dataSheet}</span>` : nothing}
850
+ ${sheet.name}
851
+ </button>`)}
852
+ ${this.readonly
853
+ ? nothing
854
+ : html `${this.tool(words.addSheet, '+', () => {
855
+ this.send({ type: 'add-sheet' });
856
+ }, { name: 'add-sheet', disabled: sheets.length >= MAX_SHEETS })}
857
+ ${this.tool(words.removeSheet, '×', () => {
858
+ this.send({ type: 'remove-sheet', sheet: session.sheet });
859
+ }, { name: 'remove-sheet', disabled: sheets.length < 2 })}`}
860
+ </div>`;
861
+ }
862
+ };
863
+ __decorate([
864
+ property({ attribute: false })
865
+ ], BahtSpreadsheet.prototype, "value", void 0);
866
+ __decorate([
867
+ property({ type: Boolean })
868
+ ], BahtSpreadsheet.prototype, "readonly", void 0);
869
+ __decorate([
870
+ property({ attribute: false })
871
+ ], BahtSpreadsheet.prototype, "load", void 0);
872
+ __decorate([
873
+ property({ attribute: false })
874
+ ], BahtSpreadsheet.prototype, "labels", void 0);
875
+ __decorate([
876
+ state()
877
+ ], BahtSpreadsheet.prototype, "session", void 0);
878
+ __decorate([
879
+ state()
880
+ ], BahtSpreadsheet.prototype, "first", void 0);
881
+ __decorate([
882
+ state()
883
+ ], BahtSpreadsheet.prototype, "pending", void 0);
884
+ __decorate([
885
+ state()
886
+ ], BahtSpreadsheet.prototype, "failures", void 0);
887
+ __decorate([
888
+ state()
889
+ ], BahtSpreadsheet.prototype, "renaming", void 0);
890
+ __decorate([
891
+ state()
892
+ ], BahtSpreadsheet.prototype, "resizing", void 0);
893
+ __decorate([
894
+ state()
895
+ ], BahtSpreadsheet.prototype, "filling", void 0);
896
+ __decorate([
897
+ state()
898
+ ], BahtSpreadsheet.prototype, "menu", void 0);
899
+ BahtSpreadsheet = __decorate([
900
+ customElement('baht-spreadsheet')
901
+ ], BahtSpreadsheet);
902
+ export { BahtSpreadsheet };