@20baht/spreadsheet 0.0.0-stage → 0.1.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,712 @@
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
+ merge: 'Merge cells',
27
+ unmerge: 'Unmerge cells',
28
+ format: 'Number format',
29
+ formatGeneral: 'General',
30
+ formatNumber: '1,234.50',
31
+ formatInteger: '1,235',
32
+ formatPercent: '12.5%',
33
+ undo: 'Undo',
34
+ redo: 'Redo',
35
+ cell: 'Selected cells',
36
+ formula: 'What the cell holds',
37
+ addSheet: 'Add sheet',
38
+ removeSheet: 'Remove sheet',
39
+ renameSheet: 'Sheet name',
40
+ dataSheet: 'Data',
41
+ refresh: 'Refresh data',
42
+ loading: 'Loading data…',
43
+ loadFailed: 'The data could not be loaded.',
44
+ readOnlyData: 'This sheet shows data as it is now. Use it from another sheet with a formula.',
45
+ };
46
+ const ARROWS = {
47
+ ArrowUp: 'up',
48
+ ArrowDown: 'down',
49
+ ArrowLeft: 'left',
50
+ ArrowRight: 'right',
51
+ };
52
+ const WRITES = new Set([
53
+ 'edit',
54
+ 'set',
55
+ 'clear',
56
+ 'paste',
57
+ 'style',
58
+ 'merge',
59
+ 'unmerge',
60
+ 'width',
61
+ 'add-sheet',
62
+ 'rename-sheet',
63
+ 'remove-sheet',
64
+ 'undo',
65
+ 'redo',
66
+ ]);
67
+ const ROW_HEIGHT = 26;
68
+ const ROWS_SHOWN = 40;
69
+ const OVERSCAN = 8;
70
+ const textOf = (event) => event.target.value;
71
+ const cellOf = (sheet, address) => Object.hasOwn(sheet.cells, address) ? sheet.cells[address] : undefined;
72
+ function inkOn(fill) {
73
+ const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((at) => parseInt(fill.slice(at, at + 2), 16));
74
+ return red * 0.299 + green * 0.587 + blue * 0.114 > 150 ? '#1a2233' : '#ffffff';
75
+ }
76
+ const ALIGN_PATHS = {
77
+ left: 'M2 3h12M2 6.5h7M2 10h12M2 13.5h7',
78
+ center: 'M2 3h12M4.5 6.5h7M2 10h12M4.5 13.5h7',
79
+ right: 'M2 3h12M7 6.5h7M2 10h12M7 13.5h7',
80
+ };
81
+ const icon = (path) => html `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
82
+ <path d=${path} fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
83
+ </svg>`;
84
+ let BahtSpreadsheet = class BahtSpreadsheet extends BahtElement {
85
+ constructor() {
86
+ super(...arguments);
87
+ this.value = emptyBook();
88
+ this.readonly = false;
89
+ this.load = undefined;
90
+ this.labels = {};
91
+ this.session = openBook(this.value);
92
+ this.first = 0;
93
+ this.pending = new Set();
94
+ this.failures = new Set();
95
+ this.renaming = null;
96
+ this.resizing = null;
97
+ this.ownValue = false;
98
+ this.stale = false;
99
+ this.dragging = false;
100
+ this.computed = null;
101
+ this.scrolled = (event) => {
102
+ const first = Math.max(0, Math.floor(event.target.scrollTop / ROW_HEIGHT) - OVERSCAN);
103
+ if (Math.abs(first - this.first) >= OVERSCAN / 2 || first === 0)
104
+ this.first = first;
105
+ };
106
+ this.gridKey = (event) => {
107
+ if (this.session.editing !== null)
108
+ return;
109
+ if (this.onKey(event))
110
+ event.preventDefault();
111
+ };
112
+ this.editorKey = (event) => {
113
+ event.stopPropagation();
114
+ const moves = event.shiftKey
115
+ ? { Enter: 'up', Tab: 'left' }
116
+ : { Enter: 'down', Tab: 'right' };
117
+ const direction = moves[event.key];
118
+ if (direction) {
119
+ event.preventDefault();
120
+ this.send({ type: 'commit' });
121
+ this.send({ type: 'move', direction });
122
+ this.grid()?.focus();
123
+ }
124
+ else if (event.key === 'Escape') {
125
+ event.preventDefault();
126
+ this.send({ type: 'cancel' });
127
+ this.grid()?.focus();
128
+ }
129
+ };
130
+ this.barKey = (event) => {
131
+ if (event.key === 'Enter') {
132
+ event.preventDefault();
133
+ this.send({ type: 'commit' });
134
+ this.grid()?.focus();
135
+ }
136
+ else if (event.key === 'Escape') {
137
+ event.preventDefault();
138
+ this.send({ type: 'cancel' });
139
+ this.grid()?.focus();
140
+ }
141
+ };
142
+ this.barInput = (event) => {
143
+ if (this.session.editing === null)
144
+ this.send({ type: 'edit' });
145
+ this.send({ type: 'type', text: textOf(event) });
146
+ };
147
+ this.shownText = (cell, at) => displayText(this.values.at(this.session.sheet, at.row, at.column), cell?.style);
148
+ this.copy = (event) => {
149
+ if (this.session.editing !== null)
150
+ return;
151
+ event.preventDefault();
152
+ event.clipboardData?.setData('text/plain', toTsv(copied(this.session, this.shownText)));
153
+ if (event.type === 'cut')
154
+ this.send({ type: 'clear' });
155
+ };
156
+ this.paste = (event) => {
157
+ if (this.session.editing !== null)
158
+ return;
159
+ const text = event.clipboardData?.getData('text/plain') ?? '';
160
+ event.preventDefault();
161
+ if (text !== '')
162
+ this.send({ type: 'paste', cells: fromTsv(text) });
163
+ };
164
+ this.pointerDown = (event) => {
165
+ const cell = this.placeOf(event);
166
+ if (!cell || event.target.closest('.baht-spreadsheet-editor'))
167
+ return;
168
+ if (this.session.editing !== null)
169
+ this.send({ type: 'commit' });
170
+ this.dragging = true;
171
+ this.send({ type: 'select', cell, extend: event.shiftKey });
172
+ this.grid()?.focus();
173
+ event.preventDefault();
174
+ };
175
+ this.pointerOver = (event) => {
176
+ if (!this.dragging || event.buttons === 0) {
177
+ this.dragging = false;
178
+ return;
179
+ }
180
+ const cell = this.placeOf(event);
181
+ if (cell)
182
+ this.send({ type: 'select', cell, extend: true });
183
+ };
184
+ this.doubleClick = (event) => {
185
+ if (this.placeOf(event))
186
+ this.send({ type: 'edit' });
187
+ };
188
+ }
189
+ get book() {
190
+ return this.session.book;
191
+ }
192
+ async refresh(sheet) {
193
+ const { load } = this;
194
+ if (!load)
195
+ return;
196
+ const sheets = this.session.book.sheets.filter((candidate) => candidate.source && (sheet === undefined || candidate.key === sheet));
197
+ await Promise.all(sheets.map(async (target) => {
198
+ this.pending = new Set([...this.pending, target.key]);
199
+ this.failures = new Set([...this.failures].filter((key) => key !== target.key));
200
+ try {
201
+ const data = await load(target.source, target);
202
+ this.session = updateBook(this.session, { type: 'fill', sheet: target.key, data }).state;
203
+ }
204
+ catch {
205
+ this.failures = new Set([...this.failures, target.key]);
206
+ }
207
+ this.pending = new Set([...this.pending].filter((key) => key !== target.key));
208
+ }));
209
+ }
210
+ async addDataSheet(name, source) {
211
+ if (this.readonly)
212
+ return;
213
+ this.send({ type: 'add-sheet', name, source });
214
+ await this.refresh(this.session.sheet);
215
+ }
216
+ get words() {
217
+ return { ...SPREADSHEET_LABELS, ...this.labels };
218
+ }
219
+ get values() {
220
+ if (this.computed?.book !== this.session.book)
221
+ this.computed = { book: this.session.book, values: computeBook(this.session.book) };
222
+ return this.computed.values;
223
+ }
224
+ willUpdate(changed) {
225
+ if (changed.has('value') && !this.ownValue) {
226
+ this.session = openBook(this.value, this.session.sheet);
227
+ this.first = 0;
228
+ this.stale = true;
229
+ }
230
+ this.ownValue = false;
231
+ }
232
+ updated() {
233
+ if (this.stale) {
234
+ this.stale = false;
235
+ void this.refresh();
236
+ }
237
+ const editor = this.querySelector('.baht-spreadsheet-editor, .baht-spreadsheet-rename');
238
+ if (editor && document.activeElement !== editor && !this.barFocused()) {
239
+ editor.focus();
240
+ editor.setSelectionRange(editor.value.length, editor.value.length);
241
+ }
242
+ }
243
+ barFocused() {
244
+ return document.activeElement?.classList.contains('baht-spreadsheet-bar-input') === true;
245
+ }
246
+ send(msg) {
247
+ if (this.readonly && WRITES.has(msg.type))
248
+ return;
249
+ const { state: next, changed } = updateBook(this.session, msg);
250
+ this.session = next;
251
+ this.reveal();
252
+ if (!changed)
253
+ return;
254
+ this.ownValue = true;
255
+ this.value = savedBook(next.book);
256
+ this.emit('baht-change', { value: this.value });
257
+ }
258
+ grid() {
259
+ return this.querySelector('.baht-spreadsheet-grid');
260
+ }
261
+ reveal() {
262
+ const box = this.querySelector('.baht-spreadsheet-scroll');
263
+ if (!box || box.clientHeight === 0)
264
+ return;
265
+ const top = this.session.end.row * ROW_HEIGHT;
266
+ const shown = box.clientHeight - ROW_HEIGHT * 2;
267
+ if (top < box.scrollTop)
268
+ box.scrollTop = top;
269
+ else if (top > box.scrollTop + shown)
270
+ box.scrollTop = top - shown;
271
+ }
272
+ onKey(event) {
273
+ const command = event.ctrlKey || event.metaKey;
274
+ const direction = ARROWS[event.key];
275
+ if (direction)
276
+ this.send({ type: 'move', direction, extend: event.shiftKey });
277
+ else if (event.key === 'Tab')
278
+ this.send({ type: 'move', direction: event.shiftKey ? 'left' : 'right' });
279
+ else if (event.key === 'Enter')
280
+ this.send({ type: 'move', direction: event.shiftKey ? 'up' : 'down' });
281
+ else if (event.key === 'F2')
282
+ this.send({ type: 'edit' });
283
+ else if (event.key === 'Delete' || event.key === 'Backspace')
284
+ this.send({ type: 'clear' });
285
+ else if (command)
286
+ return this.shortcut(event);
287
+ else if (event.key.length === 1 && !event.altKey)
288
+ this.send({ type: 'edit', text: event.key });
289
+ else
290
+ return false;
291
+ return true;
292
+ }
293
+ shortcut(event) {
294
+ const key = event.key.toLowerCase();
295
+ if (key === 'z')
296
+ this.send({ type: event.shiftKey ? 'redo' : 'undo' });
297
+ else if (key === 'y')
298
+ this.send({ type: 'redo' });
299
+ else if (key === 'b')
300
+ this.toggle('bold');
301
+ else if (key === 'i')
302
+ this.toggle('italic');
303
+ else if (key === 'u')
304
+ this.toggle('underline');
305
+ else
306
+ return false;
307
+ return true;
308
+ }
309
+ placeOf(event) {
310
+ const cell = event.target.closest('td[data-row]');
311
+ if (!cell)
312
+ return null;
313
+ return { row: Number(cell.dataset.row), column: Number(cell.dataset.column) };
314
+ }
315
+ resizeStart(event, column, width) {
316
+ event.preventDefault();
317
+ event.stopPropagation();
318
+ const from = event.clientX;
319
+ const move = (moved) => {
320
+ this.resizing = { column, width: Math.max(24, width + moved.clientX - from) };
321
+ };
322
+ const done = () => {
323
+ window.removeEventListener('pointermove', move);
324
+ window.removeEventListener('pointerup', done);
325
+ const { resizing } = this;
326
+ this.resizing = null;
327
+ if (resizing)
328
+ this.send({ type: 'width', column, width: resizing.width });
329
+ };
330
+ window.addEventListener('pointermove', move);
331
+ window.addEventListener('pointerup', done);
332
+ }
333
+ get activeStyle() {
334
+ const sheet = shownSheet(this.session);
335
+ return (sheet && cellOf(sheet, addressOf(this.session.active))?.style) ?? {};
336
+ }
337
+ toggle(flag) {
338
+ this.send({ type: 'style', style: { [flag]: this.activeStyle[flag] === true ? null : true } });
339
+ }
340
+ look(style) {
341
+ this.send({ type: 'style', style });
342
+ }
343
+ render() {
344
+ const sheet = shownSheet(this.session);
345
+ return html `<div class="baht-spreadsheet" ?data-readonly=${this.readonly}>
346
+ ${sheet ? [this.tools(sheet), this.bar(sheet), this.notice(sheet), this.table(sheet)] : nothing}
347
+ ${this.tabs()}
348
+ </div>`;
349
+ }
350
+ tool(label, content, click, options) {
351
+ return html `<button
352
+ type="button"
353
+ class="baht-spreadsheet-tool"
354
+ data-tool=${options.name}
355
+ title=${label}
356
+ aria-label=${label}
357
+ aria-pressed=${options.pressed === undefined ? nothing : String(options.pressed)}
358
+ ?disabled=${options.disabled === true}
359
+ @click=${click}
360
+ >
361
+ ${content}
362
+ </button>`;
363
+ }
364
+ tools(sheet) {
365
+ if (this.readonly)
366
+ return nothing;
367
+ const words = this.words;
368
+ const style = this.activeStyle;
369
+ const locked = sheet.source !== undefined;
370
+ const selection = selectionOf(this.session);
371
+ const isMerged = mergesOf(sheet).some((merge) => merge.top === selection.top && merge.left === selection.left);
372
+ const one = selection.top === selection.bottom && selection.left === selection.right;
373
+ const flag = (name, letter) => this.tool(words[name], html `<span data-look=${name}>${letter}</span>`, () => {
374
+ this.toggle(name);
375
+ }, { name, pressed: style[name] === true, disabled: locked });
376
+ const colour = (name, label, fallback) => html `<label class="baht-spreadsheet-colour" title=${label}>
377
+ <span data-swatch=${name} style="--swatch:${style[name] ?? fallback}">A</span>
378
+ <input
379
+ type="color"
380
+ aria-label=${label}
381
+ data-tool=${name}
382
+ .value=${style[name] ?? fallback}
383
+ ?disabled=${locked}
384
+ @input=${(event) => {
385
+ this.look({ [name]: textOf(event) });
386
+ }}
387
+ />
388
+ </label>`;
389
+ const align = (to, label) => this.tool(label, icon(ALIGN_PATHS[to]), () => {
390
+ this.look({ align: style.align === to ? null : to });
391
+ }, { name: `align-${to}`, pressed: style.align === to, disabled: locked });
392
+ return html `<div class="baht-spreadsheet-tools" role="toolbar">
393
+ ${this.tool(words.undo, icon('M6 3 2.5 6.5 6 10M3 6.5h6.5a4 4 0 0 1 0 8H7'), () => {
394
+ this.send({ type: 'undo' });
395
+ }, { name: 'undo', disabled: this.session.undo.length === 0 })}
396
+ ${this.tool(words.redo, icon('M10 3l3.5 3.5L10 10M13 6.5H6.5a4 4 0 0 0 0 8H9'), () => {
397
+ this.send({ type: 'redo' });
398
+ }, { name: 'redo', disabled: this.session.redo.length === 0 })}
399
+ <span class="baht-spreadsheet-gap"></span>
400
+ ${flag('bold', 'B')} ${flag('italic', 'I')} ${flag('underline', 'U')}
401
+ <span class="baht-spreadsheet-gap"></span>
402
+ ${colour('color', words.textColor, '#1a2233')} ${colour('fill', words.fillColor, '#ffffff')}
403
+ ${this.tool(words.noFill, icon('M3 13 13 3M3 3h10v10H3z'), () => {
404
+ this.look({ fill: null, color: null });
405
+ }, { name: 'no-fill', disabled: locked })}
406
+ <span class="baht-spreadsheet-gap"></span>
407
+ ${align('left', words.alignLeft)} ${align('center', words.alignCenter)}
408
+ ${align('right', words.alignRight)}
409
+ <span class="baht-spreadsheet-gap"></span>
410
+ ${this.tool(isMerged ? words.unmerge : words.merge, icon('M2 3h12v10H2zM5 8h6M5 8l2-2M5 8l2 2M11 8 9 6M11 8l-2 2'), () => {
411
+ this.send({ type: isMerged ? 'unmerge' : 'merge' });
412
+ }, { name: 'merge', pressed: isMerged, disabled: locked || (one && !isMerged) })}
413
+ <select
414
+ class="baht-spreadsheet-format"
415
+ aria-label=${words.format}
416
+ title=${words.format}
417
+ ?disabled=${locked}
418
+ @change=${(event) => {
419
+ const format = NUMBER_FORMATS.find((known) => known === textOf(event));
420
+ this.look({ format: format ?? null });
421
+ }}
422
+ >
423
+ <option value="" ?selected=${style.format === undefined}>${words.formatGeneral}</option>
424
+ ${NUMBER_FORMATS.map((format) => html `<option value=${format} ?selected=${style.format === format}>
425
+ ${this.formatLabel(format)}
426
+ </option>`)}
427
+ </select>
428
+ </div>`;
429
+ }
430
+ formatLabel(format) {
431
+ const words = this.words;
432
+ const labels = {
433
+ number: words.formatNumber,
434
+ integer: words.formatInteger,
435
+ percent: words.formatPercent,
436
+ };
437
+ return labels[format];
438
+ }
439
+ bar(sheet) {
440
+ const { session, words } = this;
441
+ const held = session.editing ?? inputText(cellOf(sheet, addressOf(session.active)));
442
+ return html `<div class="baht-spreadsheet-bar">
443
+ <span class="baht-spreadsheet-name" aria-label=${words.cell}>
444
+ ${rangeName(selectionOf(session))}
445
+ </span>
446
+ <span class="baht-spreadsheet-fx" aria-hidden="true">fx</span>
447
+ <input
448
+ class="baht-spreadsheet-bar-input"
449
+ aria-label=${words.formula}
450
+ .value=${held}
451
+ ?readonly=${this.readonly || sheet.source !== undefined}
452
+ @input=${this.barInput}
453
+ @keydown=${this.barKey}
454
+ @blur=${() => {
455
+ if (this.session.editing !== null)
456
+ this.send({ type: 'commit' });
457
+ }}
458
+ />
459
+ </div>`;
460
+ }
461
+ notice(sheet) {
462
+ if (!sheet.source)
463
+ return nothing;
464
+ const words = this.words;
465
+ const failed = this.failures.has(sheet.key);
466
+ const text = this.pending.has(sheet.key)
467
+ ? words.loading
468
+ : failed
469
+ ? words.loadFailed
470
+ : words.readOnlyData;
471
+ return html `<div class="baht-spreadsheet-notice" role="status" ?data-failed=${failed}>
472
+ <span>${text}</span>
473
+ <button
474
+ type="button"
475
+ class="baht-spreadsheet-tool"
476
+ data-tool="refresh"
477
+ ?disabled=${this.pending.has(sheet.key) || !this.load}
478
+ @click=${() => {
479
+ void this.refresh(sheet.key);
480
+ }}
481
+ >
482
+ ${words.refresh}
483
+ </button>
484
+ </div>`;
485
+ }
486
+ widthOf(sheet, column) {
487
+ if (this.resizing?.column === column)
488
+ return this.resizing.width;
489
+ return sheet.widths?.[columnName(column)] ?? DEFAULT_WIDTH;
490
+ }
491
+ table(sheet) {
492
+ const { session } = this;
493
+ const extent = extentOf(sheet);
494
+ const columns = Math.min(MAX_COLUMNS, Math.max(DEFAULT_COLUMNS, extent.columns + 2, session.active.column + 2, session.end.column + 2));
495
+ const rows = Math.min(MAX_ROWS, Math.max(DEFAULT_ROWS, extent.rows + 20, session.active.row + 2, session.end.row + 2));
496
+ const box = this.querySelector('.baht-spreadsheet-scroll');
497
+ const shown = box && box.clientHeight > 0 ? Math.ceil(box.clientHeight / ROW_HEIGHT) : ROWS_SHOWN;
498
+ const first = Math.min(this.first, Math.max(0, rows - shown));
499
+ const last = Math.min(rows, first + shown + OVERSCAN * 2);
500
+ const selection = selectionOf(session);
501
+ const merges = mergesOf(sheet).filter((merge) => merge.bottom >= first && merge.top < last);
502
+ const numbers = Array.from({ length: columns }, (_, column) => column);
503
+ return html `<div class="baht-spreadsheet-scroll" @scroll=${this.scrolled}>
504
+ <table
505
+ class="baht-spreadsheet-grid"
506
+ role="grid"
507
+ tabindex="0"
508
+ aria-rowcount=${rows}
509
+ aria-colcount=${columns}
510
+ style="--baht-spreadsheet-row:${ROW_HEIGHT}px"
511
+ @keydown=${this.gridKey}
512
+ @copy=${this.copy}
513
+ @cut=${this.copy}
514
+ @paste=${this.paste}
515
+ @pointerdown=${this.pointerDown}
516
+ @pointerover=${this.pointerOver}
517
+ @dblclick=${this.doubleClick}
518
+ >
519
+ <colgroup>
520
+ <col class="baht-spreadsheet-corner" />
521
+ ${numbers.map((column) => html `<col style="width:${this.widthOf(sheet, column)}px" />`)}
522
+ </colgroup>
523
+ <thead>
524
+ <tr>
525
+ <th class="baht-spreadsheet-corner"></th>
526
+ ${numbers.map((column) => html `<th
527
+ scope="col"
528
+ ?data-selected=${column >= selection.left && column <= selection.right}
529
+ >
530
+ ${columnName(column)}
531
+ <span
532
+ class="baht-spreadsheet-resize"
533
+ @pointerdown=${(event) => {
534
+ this.resizeStart(event, column, this.widthOf(sheet, column));
535
+ }}
536
+ ></span>
537
+ </th>`)}
538
+ </tr>
539
+ </thead>
540
+ <tbody>
541
+ ${first > 0
542
+ ? html `<tr class="baht-spreadsheet-spacer" style="height:${first * ROW_HEIGHT}px">
543
+ <td colspan=${columns + 1}></td>
544
+ </tr>`
545
+ : nothing}
546
+ ${Array.from({ length: last - first }, (_, i) => this.row(sheet, first + i, numbers, { selection, merges, first, last }))}
547
+ ${last < rows
548
+ ? html `<tr
549
+ class="baht-spreadsheet-spacer"
550
+ style="height:${(rows - last) * ROW_HEIGHT}px"
551
+ >
552
+ <td colspan=${columns + 1}></td>
553
+ </tr>`
554
+ : nothing}
555
+ </tbody>
556
+ </table>
557
+ </div>`;
558
+ }
559
+ row(sheet, row, columns, view) {
560
+ const { selection } = view;
561
+ return html `<tr aria-rowindex=${row + 1}>
562
+ <th scope="row" ?data-selected=${row >= selection.top && row <= selection.bottom}>
563
+ ${row + 1}
564
+ </th>
565
+ ${columns.map((column) => {
566
+ const merge = view.merges.find((range) => row >= range.top &&
567
+ row <= range.bottom &&
568
+ column >= range.left &&
569
+ column <= range.right);
570
+ if (!merge)
571
+ return this.cell(sheet, { row, column }, view.selection, 1, 1);
572
+ if (row !== Math.max(merge.top, view.first) || column !== merge.left)
573
+ return nothing;
574
+ 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);
575
+ })}
576
+ </tr>`;
577
+ }
578
+ cell(sheet, at, selection, rowspan, colspan) {
579
+ const { session } = this;
580
+ const cell = cellOf(sheet, addressOf(at));
581
+ const style = cell?.style ?? {};
582
+ const value = this.values.at(sheet.key, at.row, at.column);
583
+ const active = session.active.row === at.row && session.active.column === at.column;
584
+ const selected = at.row >= selection.top &&
585
+ at.row <= selection.bottom &&
586
+ at.column >= selection.left &&
587
+ at.column <= selection.right;
588
+ const align = style.align ?? (typeof value === 'number' ? 'right' : undefined);
589
+ const css = [
590
+ style.bold === true ? 'font-weight:700' : '',
591
+ style.italic === true ? 'font-style:italic' : '',
592
+ style.underline === true ? 'text-decoration:underline' : '',
593
+ `color:${style.color ?? (style.fill === undefined ? '' : inkOn(style.fill))}`,
594
+ style.fill === undefined ? '' : `background-color:${style.fill}`,
595
+ align === undefined ? '' : `text-align:${align}`,
596
+ ]
597
+ .filter((rule) => rule !== '' && rule !== 'color:')
598
+ .join(';');
599
+ return html `<td
600
+ role="gridcell"
601
+ data-row=${at.row}
602
+ data-column=${at.column}
603
+ rowspan=${rowspan > 1 ? rowspan : nothing}
604
+ colspan=${colspan > 1 ? colspan : nothing}
605
+ ?data-selected=${selected}
606
+ ?data-active=${active}
607
+ ?data-error=${isError(value)}
608
+ aria-selected=${String(selected)}
609
+ style=${css || nothing}
610
+ >
611
+ ${active && session.editing !== null
612
+ ? html `<input
613
+ class="baht-spreadsheet-editor"
614
+ .value=${session.editing}
615
+ @input=${(event) => {
616
+ this.send({ type: 'type', text: textOf(event) });
617
+ }}
618
+ @keydown=${this.editorKey}
619
+ @blur=${() => {
620
+ if (this.session.editing !== null && !this.barFocused())
621
+ this.send({ type: 'commit' });
622
+ }}
623
+ />`
624
+ : displayText(value, style)}
625
+ </td>`;
626
+ }
627
+ tabs() {
628
+ const { session, words } = this;
629
+ const sheets = session.book.sheets;
630
+ return html `<div class="baht-spreadsheet-tabs" role="tablist">
631
+ ${sheets.map((sheet) => this.renaming === sheet.key
632
+ ? html `<input
633
+ class="baht-spreadsheet-rename"
634
+ aria-label=${words.renameSheet}
635
+ .value=${sheet.name}
636
+ @keydown=${(event) => {
637
+ if (event.key === 'Enter')
638
+ event.target.blur();
639
+ else if (event.key === 'Escape')
640
+ this.renaming = null;
641
+ }}
642
+ @blur=${(event) => {
643
+ if (this.renaming === null)
644
+ return;
645
+ this.renaming = null;
646
+ this.send({ type: 'rename-sheet', sheet: sheet.key, name: textOf(event) });
647
+ }}
648
+ />`
649
+ : html `<button
650
+ type="button"
651
+ role="tab"
652
+ class="baht-spreadsheet-tab"
653
+ data-sheet=${sheet.key}
654
+ aria-selected=${String(sheet.key === session.sheet)}
655
+ ?data-source=${sheet.source !== undefined}
656
+ @click=${() => {
657
+ this.send({ type: 'show', sheet: sheet.key });
658
+ this.first = 0;
659
+ }}
660
+ @dblclick=${() => {
661
+ if (!this.readonly)
662
+ this.renaming = sheet.key;
663
+ }}
664
+ >
665
+ ${sheet.source ? html `<span class="baht-spreadsheet-badge">${words.dataSheet}</span>` : nothing}
666
+ ${sheet.name}
667
+ </button>`)}
668
+ ${this.readonly
669
+ ? nothing
670
+ : html `${this.tool(words.addSheet, '+', () => {
671
+ this.send({ type: 'add-sheet' });
672
+ }, { name: 'add-sheet', disabled: sheets.length >= MAX_SHEETS })}
673
+ ${this.tool(words.removeSheet, '×', () => {
674
+ this.send({ type: 'remove-sheet', sheet: session.sheet });
675
+ }, { name: 'remove-sheet', disabled: sheets.length < 2 })}`}
676
+ </div>`;
677
+ }
678
+ };
679
+ __decorate([
680
+ property({ attribute: false })
681
+ ], BahtSpreadsheet.prototype, "value", void 0);
682
+ __decorate([
683
+ property({ type: Boolean })
684
+ ], BahtSpreadsheet.prototype, "readonly", void 0);
685
+ __decorate([
686
+ property({ attribute: false })
687
+ ], BahtSpreadsheet.prototype, "load", void 0);
688
+ __decorate([
689
+ property({ attribute: false })
690
+ ], BahtSpreadsheet.prototype, "labels", void 0);
691
+ __decorate([
692
+ state()
693
+ ], BahtSpreadsheet.prototype, "session", void 0);
694
+ __decorate([
695
+ state()
696
+ ], BahtSpreadsheet.prototype, "first", void 0);
697
+ __decorate([
698
+ state()
699
+ ], BahtSpreadsheet.prototype, "pending", void 0);
700
+ __decorate([
701
+ state()
702
+ ], BahtSpreadsheet.prototype, "failures", void 0);
703
+ __decorate([
704
+ state()
705
+ ], BahtSpreadsheet.prototype, "renaming", void 0);
706
+ __decorate([
707
+ state()
708
+ ], BahtSpreadsheet.prototype, "resizing", void 0);
709
+ BahtSpreadsheet = __decorate([
710
+ customElement('baht-spreadsheet')
711
+ ], BahtSpreadsheet);
712
+ export { BahtSpreadsheet };