@20baht/export 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -80,6 +80,38 @@ const two = await xlsx([income, expenses]); // a tab per sheet
80
80
 
81
81
  It is a writer for reports and exports, not a spreadsheet library: no formulas, merged cells, colours or charts.
82
82
 
83
+ ## A document, cell by cell
84
+
85
+ A list is rows under a header. A document (a checklist, a form to hand in) is cells put where they belong: a
86
+ `LaidSheet`. A workbook only; `csv()` does not take one.
87
+
88
+ ```ts
89
+ import { xlsx, type LaidSheet } from '@20baht/export';
90
+
91
+ const head = { bold: true, shade: true, border: true, center: true };
92
+ const page: LaidSheet = {
93
+ name: 'Checklist',
94
+ cells: [
95
+ [{ value: 'Deployment Checklist', bold: true }],
96
+ [],
97
+ [{ value: 'No.', ...head }, { value: 'Plan', ...head }, { value: null, ...head }],
98
+ [{ value: null, ...head }, { value: 'Start', ...head }, { value: 'Finish', ...head }],
99
+ [{ value: 1, border: true }, { value: new Date(Date.UTC(2026, 10, 19, 13)), format: 'dd/mm/yyyy hh:mm', border: true }],
100
+ ],
101
+ merges: [
102
+ { row: 0, column: 0, columns: 3 }, // the title across the table
103
+ { row: 2, column: 1, columns: 2 }, // "Plan" over Start and Finish
104
+ { row: 2, column: 0, rows: 2 }, // "No." down both header rows
105
+ ],
106
+ widths: [6, 18, 18], // characters; unset: what the column holds, merged cells aside
107
+ frozen: 4, // rows kept in view
108
+ };
109
+ const bytes = await xlsx([page, expenses]); // beside sheets of rows, a tab each
110
+ ```
111
+
112
+ A cell is its value (`string | number | boolean | Date | null`) or `{ value, bold, shade, border, wrap, center, format }`.
113
+ `@20baht/sheet`'s `sheetWorkbook(sheet, data)` lays a filled sheet out this way.
114
+
83
115
  ## A table's columns
84
116
 
85
117
  A table declared once with the engine's `defineTable` (the one `<baht-table>` shows) gives an export the same
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { csv, csvStream, CSV_TYPE, type CsvOptions } from './csv.js';
2
2
  export { contentDisposition, contentTypeOf, download } from './download.js';
3
- export type { Cell, Column, Sheet, SyncSheet } from './sheet.js';
3
+ export type { Cell, CellLook, CellMerge, Column, LaidCell, LaidSheet, Sheet, SyncSheet, } from './sheet.js';
4
4
  export { tableColumns, type TableColumnLike, type TableColumnsOptions, type TableLike, } from './table.js';
5
5
  export { columnName, xlsx, XLSX_TYPE, type XlsxOptions } from './xlsx.js';
package/dist/sheet.d.ts CHANGED
@@ -27,6 +27,45 @@ export interface Sheet<Row> {
27
27
  /** An array, any iterable, or an async iterable (a query read page by page). */
28
28
  rows: Iterable<Row> | AsyncIterable<Row>;
29
29
  }
30
+ /** How a laid-out cell looks in a workbook. */
31
+ export interface CellLook {
32
+ bold?: boolean;
33
+ /** A light grey fill: a header, a band. */
34
+ shade?: boolean;
35
+ /** A thin line on every side. */
36
+ border?: boolean;
37
+ /** Long text breaks onto more lines instead of running over the next cell. */
38
+ wrap?: boolean;
39
+ center?: boolean;
40
+ /** An Excel number format for a number or a date: `'#,##0.00'`, `'dd/mm/yyyy hh:mm'`. */
41
+ format?: string;
42
+ }
43
+ /** A cell of a laid-out sheet: its value alone, or with how it looks. */
44
+ export type LaidCell = Cell | ({
45
+ value: Cell;
46
+ } & CellLook);
47
+ /** Cells shown as one: from `row` and `column` (both from 0), `rows` down and `columns` across (1 when unset). */
48
+ export interface CellMerge {
49
+ row: number;
50
+ column: number;
51
+ rows?: number;
52
+ columns?: number;
53
+ }
54
+ /**
55
+ * A sheet laid out cell by cell, for a document rather than a list: a title, labelled values, a
56
+ * table with a two-row header and bands across it. A workbook only; `csv()` does not take it.
57
+ */
58
+ export interface LaidSheet {
59
+ /** The tab's name in a workbook. Unset: `Sheet1`, `Sheet2`, … */
60
+ name?: string;
61
+ /** The rows, top to bottom; a row is its cells, left to right. */
62
+ cells: readonly (readonly LaidCell[])[];
63
+ merges?: readonly CellMerge[];
64
+ /** Column widths in characters. Unset: as wide as what the column holds (8 to 60), merged cells aside. */
65
+ widths?: readonly (number | undefined)[];
66
+ /** How many rows from the top stay in view. */
67
+ frozen?: number;
68
+ }
30
69
  /** A sheet whose rows are all at hand: what `csv()` takes. */
31
70
  export interface SyncSheet<Row> extends Sheet<Row> {
32
71
  rows: Iterable<Row>;
package/dist/xlsx.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Sheet } from './sheet.js';
1
+ import { type LaidSheet, type Sheet } from './sheet.js';
2
2
  export interface XlsxOptions {
3
3
  /** The zone a date's wall clock is read in. Default `UTC`. */
4
4
  timeZone?: string;
@@ -10,7 +10,8 @@ export declare const XLSX_TYPE = "application/vnd.openxmlformats-officedocument.
10
10
  /** `A`, `Z`, `AA`: the letters of a column counted from 0. */
11
11
  export declare const columnName: (index: number) => string;
12
12
  /**
13
- * The sheets as the bytes of an .xlsx file. One sheet, or several (a tab each). Rows may come page by
14
- * page (an async iterable); the workbook is still built whole before it is returned.
13
+ * The sheets as the bytes of an .xlsx file. One sheet, or several (a tab each): rows under a header
14
+ * (`Sheet`), or cells laid out one by one (`LaidSheet`). Rows may come page by page (an async
15
+ * iterable); the workbook is still built whole before it is returned.
15
16
  */
16
- export declare const xlsx: (sheets: Sheet<unknown> | readonly Sheet<unknown>[], options?: XlsxOptions) => Promise<Uint8Array>;
17
+ export declare const xlsx: (sheets: Sheet<unknown> | LaidSheet | readonly (Sheet<unknown> | LaidSheet)[], options?: XlsxOptions) => Promise<Uint8Array>;
package/dist/xlsx.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { checkTimeZone, serialDate } from './dates.js';
2
- import { cellOf, rowsOf } from './sheet.js';
2
+ import { cellOf, rowsOf, } from './sheet.js';
3
3
  import { zip } from './zip.js';
4
4
  export const XLSX_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
5
5
  const MAX_ROWS = 1_048_576;
@@ -28,18 +28,66 @@ const textWidth = (text) => {
28
28
  }
29
29
  return width;
30
30
  };
31
+ const SOLID = `<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/><bgColor indexed="64"/></patternFill></fill>`;
32
+ const THIN = ['left', 'right', 'top', 'bottom']
33
+ .map((side) => `<${side} style="thin"><color auto="1"/></${side}>`)
34
+ .join('');
31
35
  class Styles {
32
36
  #formats = new Map();
37
+ #looks = new Map();
38
+ #xfs = [];
39
+ #shaded = false;
40
+ #bordered = false;
33
41
  of(format) {
34
- if (format === undefined || format === '')
42
+ return this.look({ ...(format === undefined ? {} : { format }) });
43
+ }
44
+ look(look) {
45
+ const format = look.format === '' ? undefined : look.format;
46
+ const flags = [look.bold, look.shade, look.border, look.wrap, look.center]
47
+ .map((on) => (on === true ? '1' : '0'))
48
+ .join('');
49
+ const key = flags + (format ?? '');
50
+ if (key === '00000')
35
51
  return 0;
36
- let index = this.#formats.get(format);
52
+ if (key === '10000')
53
+ return 1;
54
+ let index = this.#looks.get(key);
37
55
  if (index === undefined) {
38
- index = this.#formats.size + 2;
39
- this.#formats.set(format, index);
56
+ index = this.#xfs.length + 2;
57
+ this.#looks.set(key, index);
58
+ this.#xfs.push(this.#xf(look, format));
40
59
  }
41
60
  return index;
42
61
  }
62
+ #numFmt(format) {
63
+ if (format === undefined)
64
+ return 0;
65
+ let at = this.#formats.get(format);
66
+ if (at === undefined) {
67
+ at = this.#formats.size;
68
+ this.#formats.set(format, at);
69
+ }
70
+ return 164 + at;
71
+ }
72
+ #xf(look, format) {
73
+ const on = (flag, text) => (flag === true ? text : '');
74
+ this.#shaded ||= look.shade === true;
75
+ this.#bordered ||= look.border === true;
76
+ const aligned = look.wrap === true || look.center === true;
77
+ const attrs = `numFmtId="${String(this.#numFmt(format))}" fontId="${on(look.bold, '1') || '0'}"` +
78
+ ` fillId="${on(look.shade, '2') || '0'}" borderId="${on(look.border, '1') || '0'}" xfId="0"` +
79
+ on(format !== undefined, ' applyNumberFormat="1"') +
80
+ on(look.bold, ' applyFont="1"') +
81
+ on(look.shade, ' applyFill="1"') +
82
+ on(look.border, ' applyBorder="1"') +
83
+ on(aligned, ' applyAlignment="1"');
84
+ if (!aligned)
85
+ return `<xf ${attrs}/>`;
86
+ const alignment = on(look.center, ' horizontal="center"') +
87
+ ` vertical="${on(look.center, 'center') || 'top'}"` +
88
+ on(look.wrap, ' wrapText="1"');
89
+ return `<xf ${attrs}><alignment${alignment}/></xf>`;
90
+ }
43
91
  xml() {
44
92
  const formats = [...this.#formats.keys()];
45
93
  const numFmts = formats.length
@@ -47,40 +95,53 @@ class Styles {
47
95
  .map((code, i) => `<numFmt numFmtId="${String(164 + i)}" formatCode="${escaped(code)}"/>`)
48
96
  .join('')}</numFmts>`
49
97
  : '';
50
- const xfs = formats
51
- .map((_, i) => `<xf numFmtId="${String(164 + i)}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`)
52
- .join('');
53
98
  return (`${XML}<styleSheet xmlns="${MAIN}">${numFmts}` +
54
99
  `<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>` +
55
- `<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>` +
56
- `<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>` +
100
+ `<fills count="${this.#shaded ? '3' : '2'}"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>${this.#shaded ? SOLID : ''}</fills>` +
101
+ `<borders count="${this.#bordered ? '2' : '1'}"><border><left/><right/><top/><bottom/><diagonal/></border>${this.#bordered ? `<border>${THIN}<diagonal/></border>` : ''}</borders>` +
57
102
  `<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
58
- `<cellXfs count="${String(formats.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
59
- `<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${xfs}</cellXfs>` +
103
+ `<cellXfs count="${String(this.#xfs.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
104
+ `<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${this.#xfs.join('')}</cellXfs>` +
60
105
  `<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>` +
61
106
  `</styleSheet>`);
62
107
  }
63
108
  }
64
- const cellXml = (cell, ref, plan, styles, timeZone) => {
65
- if (cell === null || cell === undefined || cell === '')
66
- return '';
109
+ const styleOf = (cell, plan, styles, look) => {
110
+ if (cell instanceof Date) {
111
+ if (Number.isNaN(cell.getTime()))
112
+ return 0;
113
+ return look
114
+ ? styles.look({ ...look, format: look.format ?? DATE_FORMAT })
115
+ : plan.numberStyle || styles.of(DATE_FORMAT);
116
+ }
67
117
  if (typeof cell === 'number') {
68
118
  if (!Number.isFinite(cell))
69
- return '';
70
- const s = plan.numberStyle ? ` s="${String(plan.numberStyle)}"` : '';
71
- return `<c r="${ref}"${s}><v>${String(cell)}</v></c>`;
119
+ return 0;
120
+ return look ? styles.look(look) : plan.numberStyle;
121
+ }
122
+ if (!look)
123
+ return 0;
124
+ const { format: _format, ...bare } = look;
125
+ return styles.look(bare);
126
+ };
127
+ const cellXml = (cell, ref, plan, styles, timeZone, look) => {
128
+ const index = styleOf(cell, plan, styles, look);
129
+ const s = index ? ` s="${String(index)}"` : '';
130
+ if (cell === null || cell === undefined || cell === '')
131
+ return s ? `<c r="${ref}"${s}/>` : '';
132
+ if (typeof cell === 'number') {
133
+ return Number.isFinite(cell) ? `<c r="${ref}"${s}><v>${String(cell)}</v></c>` : '';
72
134
  }
73
135
  if (typeof cell === 'boolean')
74
- return `<c r="${ref}" t="b"><v>${cell ? '1' : '0'}</v></c>`;
136
+ return `<c r="${ref}"${s} t="b"><v>${cell ? '1' : '0'}</v></c>`;
75
137
  if (cell instanceof Date) {
76
138
  if (Number.isNaN(cell.getTime()))
77
139
  return '';
78
- const style = plan.numberStyle || styles.of(DATE_FORMAT);
79
- return `<c r="${ref}" s="${String(style)}"><v>${String(serialDate(cell, timeZone))}</v></c>`;
140
+ return `<c r="${ref}"${s}><v>${String(serialDate(cell, timeZone))}</v></c>`;
80
141
  }
81
142
  if (cell.length > MAX_TEXT)
82
143
  throw new RangeError(`cell ${ref} holds ${String(cell.length)} characters; a workbook cell holds at most ${String(MAX_TEXT)}`);
83
- return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
144
+ return `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
84
145
  };
85
146
  const MEASURED_ROWS = 200;
86
147
  const shownWidth = (cell) => {
@@ -141,6 +202,49 @@ const sheetXml = async (sheet, styles, timeZone) => {
141
202
  (columns.length ? `<autoFilter ref="A1:${last}"/>` : '') +
142
203
  `</worksheet>`);
143
204
  };
205
+ const isLooked = (cell) => typeof cell === 'object' && cell !== null && !(cell instanceof Date);
206
+ const span = (n) => Math.max(1, Math.trunc(n ?? 1));
207
+ const laidXml = (sheet, styles, timeZone) => {
208
+ if (sheet.cells.length > MAX_ROWS)
209
+ throw new RangeError(`a sheet has at most ${String(MAX_ROWS)} rows`);
210
+ const merges = (sheet.merges ?? []).filter((m) => span(m.rows) > 1 || span(m.columns) > 1);
211
+ const across = new Set(merges.filter((m) => span(m.columns) > 1).map((m) => `${String(m.row)}:${String(m.column)}`));
212
+ const measured = [];
213
+ const rows = sheet.cells.map((row, r) => {
214
+ if (row.length > MAX_COLUMNS)
215
+ throw new RangeError(`a sheet has at most ${String(MAX_COLUMNS)} columns`);
216
+ const cells = row.map((cell, c) => {
217
+ const { value, ...look } = isLooked(cell) ? cell : { value: cell };
218
+ if (!across.has(`${String(r)}:${String(c)}`))
219
+ measured[c] = Math.max(measured[c] ?? 0, shownWidth(value));
220
+ return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look);
221
+ });
222
+ return `<row r="${String(r + 1)}">${cells.join('')}</row>`;
223
+ });
224
+ const cols = Array.from(measured, (width, i) => {
225
+ const n = String(i + 1);
226
+ const shown = sheet.widths?.[i] ?? Math.min(60, Math.max(8, width + 2));
227
+ return `<col min="${n}" max="${n}" width="${String(shown)}" customWidth="1"/>`;
228
+ }).join('');
229
+ const frozen = Math.max(0, Math.trunc(sheet.frozen ?? 0));
230
+ const pane = frozen
231
+ ? `<pane ySplit="${String(frozen)}" topLeftCell="A${String(frozen + 1)}" activePane="bottomLeft" state="frozen"/>`
232
+ : '';
233
+ const merged = merges
234
+ .map((m) => {
235
+ const from = `${columnName(m.column)}${String(m.row + 1)}`;
236
+ const to = `${columnName(m.column + span(m.columns) - 1)}${String(m.row + span(m.rows))}`;
237
+ return `<mergeCell ref="${from}:${to}"/>`;
238
+ })
239
+ .join('');
240
+ return (`${XML}<worksheet xmlns="${MAIN}">` +
241
+ `<sheetViews><sheetView workbookViewId="0">${pane}</sheetView></sheetViews>` +
242
+ `<sheetFormatPr defaultRowHeight="15"/>` +
243
+ (cols ? `<cols>${cols}</cols>` : '') +
244
+ `<sheetData>${rows.join('')}</sheetData>` +
245
+ (merged ? `<mergeCells count="${String(merges.length)}">${merged}</mergeCells>` : '') +
246
+ `</worksheet>`);
247
+ };
144
248
  const sheetNames = (sheets) => {
145
249
  const taken = new Set();
146
250
  return sheets.map((sheet, i) => {
@@ -178,8 +282,9 @@ export const xlsx = async (sheets, options = {}) => {
178
282
  const styles = new Styles();
179
283
  const names = sheetNames(list);
180
284
  const parts = [];
181
- for (const sheet of list)
182
- parts.push(await sheetXml(sheet, styles, timeZone));
285
+ for (const sheet of list) {
286
+ parts.push('cells' in sheet ? laidXml(sheet, styles, timeZone) : await sheetXml(sheet, styles, timeZone));
287
+ }
183
288
  const ids = list.map((_, i) => String(i + 1));
184
289
  const encoder = new TextEncoder();
185
290
  const file = (path, text) => ({ path, data: encoder.encode(text) });
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@20baht/export",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
7
7
  },
8
- "description": "Rows as a CSV or an .xlsx file, on a server or in a browser: Thai that opens in Excel, no formula a cell can smuggle in, dates and number formats, a table's columns as the header. No dependencies.",
8
+ "description": "Rows as a CSV or an .xlsx file, on a server or in a browser: Thai that opens in Excel, no formula a cell can smuggle in, dates and number formats, a table's columns as the header, and a sheet laid out cell by cell (merged cells, borders) for a document. No dependencies.",
9
9
  "license": "MIT",
10
10
  "author": "Nattapong Promthong",
11
11
  "repository": {