@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # @20baht/spreadsheet
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A book of free cells from one JSON document ([spec 12](../../../spec/12-spreadsheet.md)): values and
4
+ formulas, bold / italic / colours, merged ranges, several sheets, and **data sheets** a host fills
5
+ from its own records each time the book is opened. Made for the report someone builds once and sends
6
+ on as an .xlsx: a title, a few totals, the records underneath.
7
+
8
+ It is the other half of [`@20baht/sheet`](../sheet): that one is a table of fixed, typed columns
9
+ checked like a form; this one is a spreadsheet.
10
+
11
+ ```bash
12
+ bun add @20baht/spreadsheet
13
+ ```
14
+
15
+ ## The element
16
+
17
+ ```html
18
+ <link rel="stylesheet" href="@20baht/ui/tokens.css" />
19
+ <link rel="stylesheet" href="@20baht/spreadsheet/spreadsheet.css" />
20
+ <baht-spreadsheet style="height: 560px"></baht-spreadsheet>
21
+ ```
22
+
23
+ ```ts
24
+ import '@20baht/spreadsheet/element';
25
+ import { bookWorkbook, emptyBook } from '@20baht/spreadsheet';
26
+ import { xlsx } from '@20baht/export';
27
+
28
+ const el = document.querySelector('baht-spreadsheet')!;
29
+ el.value = saved ?? emptyBook();
30
+ // a data sheet's source is yours: a name and what you need to answer it
31
+ el.load = async (source) => {
32
+ const records = await api.query(source.name, source.params);
33
+ // a Date in a row becomes a date cell
34
+ return { columns: ['Number', 'Status', 'Hours'], rows: records.map((r) => [r.id, r.status, r.hours]) };
35
+ };
36
+ el.addEventListener('baht-change', (event) => save(event.detail.value)); // saved without the data
37
+ addData.onclick = () => el.addDataSheet('Changes', { name: 'change-normal', params: { status: 'open' } });
38
+ download.onclick = async () => saveFile(await xlsx(bookWorkbook(el.book)), 'report.xlsx');
39
+ ```
40
+
41
+ - `value`: the book. `baht-change { value }` carries the book **as it is saved**, its data sheets
42
+ empty: keep it, do not hand it back. `el.book` is the book with the data, for a file.
43
+ - `load(source, sheet)` is called when a book is opened, a data sheet is added and on `refresh()`.
44
+ Never on a timer.
45
+ - `readonly`, `labels` (`SPREADSHEET_LABELS` has every word).
46
+ - Give the element a height: the grid scrolls inside it and draws only the rows in view.
47
+
48
+ Worked like Excel: click or arrows to select, Shift for a rectangle, type to write, `=` for a formula,
49
+ F2 or a double click to edit, Delete to empty, Ctrl+B / I / U, Ctrl+Z / Y, copy and paste with Excel
50
+ and Google Sheets (TSV), drag a column's edge, double click a tab to rename it, right click a cell
51
+ to put rows and columns in or take them out (formulas follow), drag the square at the selection's
52
+ corner (or Ctrl+D / Ctrl+R) to copy formulas along.
53
+
54
+ ## Formulas
55
+
56
+ Excel's spelling, so the .xlsx carries the same formula: `+ - * / ^ &`, the comparisons, `%`, cells
57
+ (`B3`), ranges (`A1:B9`, `A:A`), another sheet (`Data!A:A`, `'My data'!B2`) and
58
+ `SUM` `AVERAGE` `MIN` `MAX` `COUNT` `COUNTA` `COUNTIF` `SUMIF` `IF` `IFERROR` `AND` `OR` `NOT` `ROUND` `ABS`
59
+ `VLOOKUP` `DATE` `TODAY` `NOW` `YEAR` `MONTH` `DAY`. Errors show in the cell: `#DIV/0!` `#NAME?` `#REF!` `#VALUE!` `#N/A` `#CYCLE!` `#ERROR!`.
60
+
61
+ ```ts
62
+ import { computeBook, displayText } from '@20baht/spreadsheet';
63
+ const values = computeBook(book);
64
+ displayText(values.at('summary', 2, 1)); // row 3, column B
65
+ ```
66
+
67
+ ## Headless
68
+
69
+ No DOM, no Lit, for a server, a test or an agent:
70
+
71
+ | | |
72
+ | --- | --- |
73
+ | `parseBook(json)` | the authoring gate: `{ ok, book }` or `{ issues }` |
74
+ | `computeBook(book)` · `displayText` · `parseFormula` · `evaluate` · `FUNCTIONS` | formulas |
75
+ | `openBook` · `updateBook(state, msg)` · `selectionOf` · `copied` · `savedBook` | the grid session, pure |
76
+ | `cellInput(text)` · `inputText(cell)` | typed text → a cell, and back |
77
+ | `rewriteRefs` · `movedRefs` · `shiftedRefs` · `renamedRefs` | a formula's references written again |
78
+ | `toTsv` · `fromTsv` | the clipboard's text |
79
+ | `bookWorkbook(book)` | each sheet as a `LaidSheet` for `@20baht/export`'s `xlsx()` |
80
+
81
+ ## Not yet
82
+
83
+ Wrapped text,
84
+ the other lookups, charts, reading an .xlsx in. Spec 12 §7.
package/dist/book.d.ts ADDED
@@ -0,0 +1,97 @@
1
+ /** What a cell holds when it holds no formula. */
2
+ export type CellValue = string | number | boolean;
3
+ export declare const ALIGNS: readonly ["left", "center", "right"];
4
+ export type CellAlign = (typeof ALIGNS)[number];
5
+ /**
6
+ * How a number is shown: `number` 1,234.50, `integer` 1,235, `percent` 12.5%, and as a day counted
7
+ * from 1899-12-30 (`dates.ts`): `date` 2026-12-31, `datetime` 2026-12-31 14:30.
8
+ */
9
+ export declare const NUMBER_FORMATS: readonly ["number", "integer", "percent", "date", "datetime"];
10
+ export type NumberFormat = (typeof NUMBER_FORMATS)[number];
11
+ /** A side of a cell a line is drawn on. */
12
+ export declare const BORDER_SIDES: readonly ["top", "right", "bottom", "left"];
13
+ export type BorderSide = (typeof BORDER_SIDES)[number];
14
+ export interface CellStyle {
15
+ bold?: boolean;
16
+ italic?: boolean;
17
+ underline?: boolean;
18
+ /** The text's colour, `#rrggbb`. */
19
+ color?: string;
20
+ /** The background's colour, `#rrggbb`. */
21
+ fill?: string;
22
+ align?: CellAlign;
23
+ format?: NumberFormat;
24
+ /** The sides a thin line is drawn on, in the order of BORDER_SIDES. */
25
+ border?: BorderSide[];
26
+ }
27
+ export interface BookCell {
28
+ value?: CellValue;
29
+ /** A formula, without its `=`: `SUM(A1:A9)`. The cell shows what it works out to. */
30
+ formula?: string;
31
+ style?: CellStyle;
32
+ }
33
+ /** Where a sheet's cells come from: a name the host knows and what it needs to answer it. */
34
+ export interface BookSource {
35
+ name: string;
36
+ params?: Record<string, unknown>;
37
+ }
38
+ export interface BookSheet {
39
+ key: string;
40
+ /** The tab's name, and the sheet's name in a formula (`Data!A1`). */
41
+ name: string;
42
+ /** The cells that hold something, by address (`B3`). */
43
+ cells: Record<string, BookCell>;
44
+ /** Ranges shown as one cell (`A1:C1`). The top left cell holds the value. */
45
+ merges?: string[];
46
+ /** Column widths in pixels, by column letter. */
47
+ widths?: Record<string, number>;
48
+ /** Set on a data sheet: its cells are what the source answered, never typed and never saved. */
49
+ source?: BookSource;
50
+ }
51
+ export interface Book {
52
+ title?: string;
53
+ sheets: BookSheet[];
54
+ }
55
+ /** A cell's place, both from 0. */
56
+ export interface CellPos {
57
+ row: number;
58
+ column: number;
59
+ }
60
+ /** A rectangle of cells, both ends included. */
61
+ export interface CellRange {
62
+ top: number;
63
+ left: number;
64
+ bottom: number;
65
+ right: number;
66
+ }
67
+ export declare const MAX_ROWS = 10000;
68
+ export declare const MAX_COLUMNS = 200;
69
+ export declare const MAX_SHEETS = 20;
70
+ /** The grid a sheet shows when it holds less. */
71
+ export declare const DEFAULT_ROWS = 50;
72
+ export declare const DEFAULT_COLUMNS = 12;
73
+ export declare const DEFAULT_WIDTH = 96;
74
+ /** `A`, `Z`, `AA`: the letters of a column counted from 0. */
75
+ export declare function columnName(index: number): string;
76
+ /** The column of its letters, from 0; -1 when they are no column. */
77
+ export declare function columnIndex(name: string): number;
78
+ export declare function addressOf(cell: CellPos): string;
79
+ /** `B3` as a place; `null` when it is no address. */
80
+ export declare function parseAddress(address: string): CellPos | null;
81
+ export declare function rangeOf(a: CellPos, b?: CellPos): CellRange;
82
+ export declare function rangeName(range: CellRange): string;
83
+ /** `A1:C2` (or one address) as a rectangle; `null` when it is neither. */
84
+ export declare function parseRange(name: string): CellRange | null;
85
+ export declare function overlaps(a: CellRange, b: CellRange): boolean;
86
+ /** The sheet's merged ranges as rectangles. */
87
+ export declare function mergesOf(sheet: BookSheet): CellRange[];
88
+ /** The merged range a cell is part of. */
89
+ export declare function mergeAt(sheet: BookSheet, cell: CellPos): CellRange | null;
90
+ /** How far the sheet's cells reach: the rows and columns that hold something. */
91
+ export declare function extentOf(sheet: BookSheet): {
92
+ rows: number;
93
+ columns: number;
94
+ };
95
+ export declare function sheetOf(book: Book, key: string): BookSheet | undefined;
96
+ /** A book with one empty sheet. */
97
+ export declare function emptyBook(name?: string): Book;
package/dist/book.js ADDED
@@ -0,0 +1,85 @@
1
+ export const ALIGNS = ['left', 'center', 'right'];
2
+ export const NUMBER_FORMATS = ['number', 'integer', 'percent', 'date', 'datetime'];
3
+ export const BORDER_SIDES = ['top', 'right', 'bottom', 'left'];
4
+ export const MAX_ROWS = 10_000;
5
+ export const MAX_COLUMNS = 200;
6
+ export const MAX_SHEETS = 20;
7
+ export const DEFAULT_ROWS = 50;
8
+ export const DEFAULT_COLUMNS = 12;
9
+ export const DEFAULT_WIDTH = 96;
10
+ export function columnName(index) {
11
+ let name = '';
12
+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26))
13
+ name = String.fromCharCode(65 + ((n - 1) % 26)) + name;
14
+ return name;
15
+ }
16
+ export function columnIndex(name) {
17
+ if (!/^[A-Za-z]{1,3}$/.test(name))
18
+ return -1;
19
+ let index = 0;
20
+ for (const letter of name.toUpperCase())
21
+ index = index * 26 + (letter.charCodeAt(0) - 64);
22
+ return index - 1;
23
+ }
24
+ export function addressOf(cell) {
25
+ return `${columnName(cell.column)}${String(cell.row + 1)}`;
26
+ }
27
+ const ADDRESS = /^([A-Za-z]{1,3})([1-9]\d{0,6})$/;
28
+ export function parseAddress(address) {
29
+ const match = ADDRESS.exec(address);
30
+ if (!match)
31
+ return null;
32
+ return { row: Number(match[2]) - 1, column: columnIndex(match[1] ?? '') };
33
+ }
34
+ export function rangeOf(a, b = a) {
35
+ return {
36
+ top: Math.min(a.row, b.row),
37
+ left: Math.min(a.column, b.column),
38
+ bottom: Math.max(a.row, b.row),
39
+ right: Math.max(a.column, b.column),
40
+ };
41
+ }
42
+ export function rangeName(range) {
43
+ const from = addressOf({ row: range.top, column: range.left });
44
+ const to = addressOf({ row: range.bottom, column: range.right });
45
+ return from === to ? from : `${from}:${to}`;
46
+ }
47
+ export function parseRange(name) {
48
+ const [from, to, more] = name.split(':');
49
+ const a = parseAddress(from ?? '');
50
+ const b = to === undefined ? a : parseAddress(to);
51
+ return a && b && more === undefined ? rangeOf(a, b) : null;
52
+ }
53
+ function inRange(range, cell) {
54
+ return (cell.row >= range.top &&
55
+ cell.row <= range.bottom &&
56
+ cell.column >= range.left &&
57
+ cell.column <= range.right);
58
+ }
59
+ export function overlaps(a, b) {
60
+ return a.top <= b.bottom && b.top <= a.bottom && a.left <= b.right && b.left <= a.right;
61
+ }
62
+ export function mergesOf(sheet) {
63
+ return (sheet.merges ?? []).flatMap((name) => parseRange(name) ?? []);
64
+ }
65
+ export function mergeAt(sheet, cell) {
66
+ return mergesOf(sheet).find((range) => inRange(range, cell)) ?? null;
67
+ }
68
+ export function extentOf(sheet) {
69
+ let rows = 0;
70
+ let columns = 0;
71
+ for (const address of Object.keys(sheet.cells)) {
72
+ const cell = parseAddress(address);
73
+ if (!cell)
74
+ continue;
75
+ rows = Math.max(rows, cell.row + 1);
76
+ columns = Math.max(columns, cell.column + 1);
77
+ }
78
+ return { rows, columns };
79
+ }
80
+ export function sheetOf(book, key) {
81
+ return book.sheets.find((sheet) => sheet.key === key);
82
+ }
83
+ export function emptyBook(name = 'Sheet1') {
84
+ return { sheets: [{ key: 'sheet_1', name, cells: {} }] };
85
+ }
@@ -0,0 +1,22 @@
1
+ import { type Book, type BookCell, type CellStyle } from './book.js';
2
+ import { type Scalar } from './formula.js';
3
+ /** What every cell of a book works out to. */
4
+ export interface BookValues {
5
+ /** The value of a cell of the sheet with this key; `null` when the cell is empty. */
6
+ at(sheet: string, row: number, column: number): Scalar;
7
+ }
8
+ export declare function computeBook(book: Book): BookValues;
9
+ /** A value as its cell shows it: a number in the cell's format, an error as its code. */
10
+ export declare function displayText(value: Scalar, style?: CellStyle): string;
11
+ /** What typing puts into a cell, and for a date the format that shows it as one. */
12
+ export type TypedCell = Pick<BookCell, 'value' | 'formula'> & {
13
+ format?: 'date' | 'datetime';
14
+ };
15
+ /**
16
+ * What typing `text` into a cell puts there: a formula after `=`, a number (`1,234.5`, `12%`), a
17
+ * date (`2026-12-31`, `31/12/2026`, with `14:30` after it: its serial, and the `format` to show
18
+ * it), TRUE / FALSE, otherwise the text; after `'` always the text. Nothing for an empty text.
19
+ */
20
+ export declare function cellInput(text: string): TypedCell;
21
+ /** What a cell holds as the text that typed it: `=SUM(A1:A3)`, `12.5`, `TRUE`. */
22
+ export declare function inputText(cell: BookCell | undefined): string;
@@ -0,0 +1,114 @@
1
+ import { addressOf, extentOf, } from './book.js';
2
+ import { dateText, parseDateText } from './dates.js';
3
+ import { evaluate, failed, isError, parseFormula, } from './formula.js';
4
+ export function computeBook(book) {
5
+ const sheets = new Map();
6
+ const byName = new Map();
7
+ for (const sheet of book.sheets) {
8
+ const working = { sheet, extent: extentOf(sheet), done: new Map(), open: new Set() };
9
+ sheets.set(sheet.key, working);
10
+ byName.set(sheet.name.toLowerCase(), working);
11
+ }
12
+ const trees = new Map();
13
+ const treeOf = (formula) => {
14
+ let tree = trees.get(formula);
15
+ if (!tree) {
16
+ tree = parseFormula(formula);
17
+ trees.set(formula, tree);
18
+ }
19
+ return tree;
20
+ };
21
+ const value = (working, row, column) => {
22
+ const address = addressOf({ row, column });
23
+ const cell = Object.hasOwn(working.sheet.cells, address)
24
+ ? working.sheet.cells[address]
25
+ : undefined;
26
+ if (cell?.formula === undefined)
27
+ return cell?.value ?? null;
28
+ if (working.done.has(address))
29
+ return working.done.get(address) ?? null;
30
+ if (working.open.has(address))
31
+ return failed('#CYCLE!');
32
+ working.open.add(address);
33
+ const on = (name) => name === undefined ? working : byName.get(name.toLowerCase());
34
+ const scope = {
35
+ cell: (name, r, c) => {
36
+ const other = on(name);
37
+ return other ? value(other, r, c) : failed('#REF!');
38
+ },
39
+ extent: (name) => on(name)?.extent ?? null,
40
+ };
41
+ const result = evaluate(treeOf(cell.formula), scope);
42
+ working.open.delete(address);
43
+ working.done.set(address, result);
44
+ return result;
45
+ };
46
+ return {
47
+ at: (key, row, column) => {
48
+ const working = sheets.get(key);
49
+ return working ? value(working, row, column) : null;
50
+ },
51
+ };
52
+ }
53
+ const GROUPED = new Intl.NumberFormat('en-US', {
54
+ minimumFractionDigits: 2,
55
+ maximumFractionDigits: 2,
56
+ });
57
+ const WHOLE = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });
58
+ const PERCENT = new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 2 });
59
+ export function displayText(value, style = {}) {
60
+ if (value === null)
61
+ return '';
62
+ if (isError(value))
63
+ return value.error;
64
+ if (typeof value === 'boolean')
65
+ return value ? 'TRUE' : 'FALSE';
66
+ if (typeof value === 'string')
67
+ return value;
68
+ if (style.format === 'number')
69
+ return GROUPED.format(value);
70
+ if (style.format === 'integer')
71
+ return WHOLE.format(value);
72
+ if (style.format === 'percent')
73
+ return PERCENT.format(value);
74
+ if (style.format === 'date')
75
+ return dateText(value, false);
76
+ if (style.format === 'datetime')
77
+ return dateText(value, true);
78
+ return String(Number(value.toPrecision(12)));
79
+ }
80
+ const NUMERIC = /^[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(%)?$/;
81
+ export function cellInput(text) {
82
+ if (text.startsWith('=') && text.length > 1)
83
+ return { formula: text.slice(1) };
84
+ if (text.startsWith("'"))
85
+ return text.length > 1 ? { value: text.slice(1) } : {};
86
+ const trimmed = text.trim();
87
+ if (trimmed === '')
88
+ return {};
89
+ const numeric = NUMERIC.exec(trimmed);
90
+ if (numeric) {
91
+ const number = Number(trimmed.replaceAll(',', '').replace('%', ''));
92
+ return { value: numeric[1] === undefined ? number : number / 100 };
93
+ }
94
+ const date = parseDateText(trimmed);
95
+ if (date)
96
+ return { value: date.serial, format: date.time ? 'datetime' : 'date' };
97
+ const upper = trimmed.toUpperCase();
98
+ if (upper === 'TRUE' || upper === 'FALSE')
99
+ return { value: upper === 'TRUE' };
100
+ return { value: text };
101
+ }
102
+ export function inputText(cell) {
103
+ if (cell?.formula !== undefined)
104
+ return `=${cell.formula}`;
105
+ const value = cell?.value;
106
+ if (value === undefined)
107
+ return '';
108
+ if (typeof value === 'boolean')
109
+ return value ? 'TRUE' : 'FALSE';
110
+ const format = cell?.style?.format;
111
+ if (typeof value === 'number' && (format === 'date' || format === 'datetime'))
112
+ return dateText(value, format === 'datetime');
113
+ return String(value);
114
+ }