@salmonui/export 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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +44 -2
  3. package/dist/blob.d.ts +6 -0
  4. package/dist/blob.d.ts.map +1 -0
  5. package/dist/blob.js +10 -0
  6. package/dist/blob.js.map +1 -0
  7. package/dist/bytes.d.ts +55 -0
  8. package/dist/bytes.d.ts.map +1 -0
  9. package/dist/bytes.js +167 -0
  10. package/dist/bytes.js.map +1 -0
  11. package/dist/gantt.d.ts +111 -0
  12. package/dist/gantt.d.ts.map +1 -0
  13. package/dist/gantt.js +348 -0
  14. package/dist/gantt.js.map +1 -0
  15. package/dist/graphics.d.ts +58 -0
  16. package/dist/graphics.d.ts.map +1 -0
  17. package/dist/graphics.js +651 -0
  18. package/dist/graphics.js.map +1 -0
  19. package/dist/ics.d.ts +90 -0
  20. package/dist/ics.d.ts.map +1 -0
  21. package/dist/ics.js +528 -0
  22. package/dist/ics.js.map +1 -0
  23. package/dist/image.d.ts +10 -0
  24. package/dist/image.d.ts.map +1 -0
  25. package/dist/image.js +49 -0
  26. package/dist/image.js.map +1 -0
  27. package/dist/pdf-fonts.d.ts +22 -0
  28. package/dist/pdf-fonts.d.ts.map +1 -0
  29. package/dist/pdf-fonts.js +647 -0
  30. package/dist/pdf-fonts.js.map +1 -0
  31. package/dist/pdf-images.d.ts +17 -0
  32. package/dist/pdf-images.d.ts.map +1 -0
  33. package/dist/pdf-images.js +221 -0
  34. package/dist/pdf-images.js.map +1 -0
  35. package/dist/pdf-writer.d.ts +80 -0
  36. package/dist/pdf-writer.d.ts.map +1 -0
  37. package/dist/pdf-writer.js +677 -0
  38. package/dist/pdf-writer.js.map +1 -0
  39. package/dist/pdf.d.ts +14 -0
  40. package/dist/pdf.d.ts.map +1 -0
  41. package/dist/pdf.js +16 -0
  42. package/dist/pdf.js.map +1 -0
  43. package/dist/pivot.d.ts +194 -0
  44. package/dist/pivot.d.ts.map +1 -0
  45. package/dist/pivot.js +451 -0
  46. package/dist/pivot.js.map +1 -0
  47. package/dist/shared.d.ts +26 -0
  48. package/dist/shared.d.ts.map +1 -0
  49. package/dist/shared.js +36 -0
  50. package/dist/shared.js.map +1 -0
  51. package/dist/xlsx-writer.d.ts +61 -0
  52. package/dist/xlsx-writer.d.ts.map +1 -0
  53. package/dist/xlsx-writer.js +759 -0
  54. package/dist/xlsx-writer.js.map +1 -0
  55. package/dist/xlsx.d.ts +15 -0
  56. package/dist/xlsx.d.ts.map +1 -0
  57. package/dist/xlsx.js +18 -0
  58. package/dist/xlsx.js.map +1 -0
  59. package/dist/zip.d.ts +19 -0
  60. package/dist/zip.d.ts.map +1 -0
  61. package/dist/zip.js +106 -0
  62. package/dist/zip.js.map +1 -0
  63. package/package.json +63 -4
@@ -0,0 +1,759 @@
1
+ // XLSX writer: SpreadsheetML
2
+ // parts zipped by the in-package ZIP writer, deflated with the platform
3
+ // `CompressionStream`. No third-party code. Worksheet XML is produced row by
4
+ // row from the export model and streamed into the ZIP entry in ~512 KB
5
+ // batches; the writer yields to the event loop whenever a time slice
6
+ // (default 25 ms) is used up, so the main thread is never blocked for long
7
+ // without a worker. Image cells become pictures anchored to their
8
+ // cell (`xl/media`, `xl/drawings`); the parts exist only when a `cell` hook
9
+ // returned an image.
10
+ import { isFormulaText } from '@salmonui/core/export-model';
11
+ import { createSlicer, defaultYield, utf8 } from './bytes.js';
12
+ import { ImageStore, imageType } from './image.js';
13
+ import { hexColor, mergeStyle, stylesOf } from './shared.js';
14
+ import { ZipWriter } from './zip.js';
15
+ export const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
16
+ /** Writes one or more export models (or engines with the `export` module) as an XLSX workbook. */
17
+ export async function writeXlsx(models, options = {}) {
18
+ const list = Array.isArray(models) ? models : [models];
19
+ if (list.length === 0)
20
+ throw new Error('writeXlsx: no export model.');
21
+ const book = new Workbook(options);
22
+ if (options.layout === 'stacked') {
23
+ await book.sheet(options.sheetName ?? 'Sheet1', list, options);
24
+ }
25
+ else {
26
+ for (let i = 0; i < list.length; i++) {
27
+ await book.sheet(options.sheetNames?.[i] ?? (list.length === 1 ? (options.sheetName ?? 'Sheet1') : `Sheet${i + 1}`), [list[i]], options);
28
+ }
29
+ }
30
+ return book.finish();
31
+ }
32
+ // ---------------------------------------------------------------------------
33
+ // XML helpers
34
+ // ---------------------------------------------------------------------------
35
+ const XML_SPECIAL = /[&<>"\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/;
36
+ const XML_REPLACE = /[&<>"\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
37
+ /** XML text / attribute escape; drops characters XML 1.0 cannot carry. */
38
+ export function xml(text) {
39
+ if (!XML_SPECIAL.test(text))
40
+ return text;
41
+ return text.replace(XML_REPLACE, (c) => (c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : ''));
42
+ }
43
+ /** Column letters of a 0-based index (`0` -> `A`). */
44
+ export function columnLetter(index) {
45
+ let n = index + 1;
46
+ let s = '';
47
+ while (n > 0) {
48
+ const m = (n - 1) % 26;
49
+ s = String.fromCharCode(65 + m) + s;
50
+ n = Math.floor((n - 1) / 26);
51
+ }
52
+ return s;
53
+ }
54
+ const NS = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
55
+ const REL_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
56
+ const HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
57
+ const PKG_REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
58
+ const EMU_PER_PX = 9525;
59
+ // ---------------------------------------------------------------------------
60
+ // Number formats: the grid format descriptor as an Excel code
61
+ // ---------------------------------------------------------------------------
62
+ const CURRENCY_SYMBOLS = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥', INR: '₹', KRW: '₩' };
63
+ function fractionCode(min, max, fallbackMax) {
64
+ const lo = min ?? 0;
65
+ const hi = Math.max(lo, max ?? fallbackMax);
66
+ return lo === 0 && hi === 0 ? '' : `.${'0'.repeat(lo)}${'#'.repeat(hi - lo)}`;
67
+ }
68
+ /** Excel number format code (or built-in id) of a column; null for General. */
69
+ export function excelNumberFormat(format, type) {
70
+ if (type === 'date' || type === 'datetime' || format?.kind === 'date') {
71
+ if (format?.kind === 'date' && format.pattern)
72
+ return excelDatePattern(format.pattern);
73
+ return type === 'datetime' || format?.options.type === 'datetime' ? 22 : 14;
74
+ }
75
+ if (!format || format.kind !== 'number')
76
+ return null;
77
+ if (format.pattern)
78
+ return format.pattern;
79
+ const o = format.options;
80
+ const grouping = o.useGrouping === false ? '0' : '#,##0';
81
+ if (format.style === 'percent')
82
+ return `0${fractionCode(o.minimumFractionDigits, o.maximumFractionDigits, 0)}%`;
83
+ if (format.style === 'currency') {
84
+ const code = (o.currency ?? 'USD').toUpperCase();
85
+ const symbol = CURRENCY_SYMBOLS[code];
86
+ const body = `${grouping}${fractionCode(o.minimumFractionDigits ?? 2, o.maximumFractionDigits ?? 2, 2)}`;
87
+ return symbol ? `"${symbol}"${body}` : `[$${code}] ${body}`;
88
+ }
89
+ return `${grouping}${fractionCode(o.minimumFractionDigits, o.maximumFractionDigits, 3)}`;
90
+ }
91
+ /** DataGrid date pattern (`dd/MM/yyyy HH:mm`) as an Excel code. */
92
+ export function excelDatePattern(pattern) {
93
+ let out = '';
94
+ let twelve = false;
95
+ for (const token of pattern.match(/'[^']*'|(.)\1*/g) ?? []) {
96
+ const c = token[0];
97
+ switch (c) {
98
+ case "'":
99
+ out += token.length > 2 ? `"${token.slice(1, -1)}"` : "'";
100
+ break;
101
+ case 'y':
102
+ out += token.length === 2 ? 'yy' : 'yyyy';
103
+ break;
104
+ case 'M':
105
+ case 'L':
106
+ out += token.length >= 4 ? 'mmmm' : token.length === 3 ? 'mmm' : token.length === 2 ? 'mm' : 'm';
107
+ break;
108
+ case 'd':
109
+ out += token.length >= 2 ? 'dd' : 'd';
110
+ break;
111
+ case 'E':
112
+ out += token.length >= 4 ? 'dddd' : 'ddd';
113
+ break;
114
+ case 'H':
115
+ out += token.length >= 2 ? 'hh' : 'h';
116
+ break;
117
+ case 'h':
118
+ twelve = true;
119
+ out += token.length >= 2 ? 'hh' : 'h';
120
+ break;
121
+ case 'm':
122
+ out += token.length >= 2 ? 'mm' : 'm';
123
+ break;
124
+ case 's':
125
+ out += token.length >= 2 ? 'ss' : 's';
126
+ break;
127
+ case 'f':
128
+ out += `.${'0'.repeat(Math.min(3, token.length))}`;
129
+ break;
130
+ case 'a':
131
+ twelve = true;
132
+ out += 'AM/PM';
133
+ break;
134
+ default:
135
+ out += /[A-Za-z]/.test(token) ? `"${token}"` : token.replace(/"/g, '');
136
+ }
137
+ }
138
+ if (twelve && !out.includes('AM/PM'))
139
+ out += ' AM/PM';
140
+ return out;
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Dates
144
+ // ---------------------------------------------------------------------------
145
+ const MS_PER_DAY = 86_400_000;
146
+ const EPOCH_OFFSET = 25569; // 1970-01-01 in the 1900 date system
147
+ function createSerial(timeZone) {
148
+ if (timeZone === 'UTC' || timeZone === 'Etc/UTC' || timeZone === 'GMT')
149
+ return (d) => d.getTime() / MS_PER_DAY + EPOCH_OFFSET;
150
+ if (timeZone === undefined)
151
+ return (d) => (d.getTime() - d.getTimezoneOffset() * 60_000) / MS_PER_DAY + EPOCH_OFFSET;
152
+ const fmt = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' });
153
+ const memo = new Map();
154
+ return (d) => {
155
+ const t = d.getTime();
156
+ let hit = memo.get(t);
157
+ if (hit === undefined) {
158
+ const p = {};
159
+ for (const part of fmt.formatToParts(d))
160
+ if (part.type !== 'literal')
161
+ p[part.type] = Number(part.value);
162
+ const wall = Date.UTC(p['year'] ?? 1970, (p['month'] ?? 1) - 1, p['day'] ?? 1, p['hour'] ?? 0, p['minute'] ?? 0, p['second'] ?? 0) + (t % 1000 + 1000) % 1000;
163
+ hit = wall / MS_PER_DAY + EPOCH_OFFSET;
164
+ if (memo.size > 65_536)
165
+ memo.clear();
166
+ memo.set(t, hit);
167
+ }
168
+ return hit;
169
+ };
170
+ }
171
+ class Styles {
172
+ numFmts = new Map();
173
+ fonts = ['<font><sz val="11"/><name val="Calibri"/></font>'];
174
+ fontIds = new Map([[this.fonts[0], 0]]);
175
+ fills = ['<fill><patternFill patternType="none"/></fill>', '<fill><patternFill patternType="gray125"/></fill>'];
176
+ fillIds = new Map();
177
+ xfs = ['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'];
178
+ xfIds = new Map();
179
+ quotedIds = new Map();
180
+ get({ style, numFmt, indent: base }) {
181
+ const indent = style.indent ?? base;
182
+ const fmt = style.numberFormat ?? numFmt;
183
+ const key = `${JSON.stringify(style)}|${fmt}|${indent}`;
184
+ const hit = this.xfIds.get(key);
185
+ if (hit !== undefined)
186
+ return hit;
187
+ let numFmtId = 0;
188
+ if (typeof fmt === 'number')
189
+ numFmtId = fmt;
190
+ else if (typeof fmt === 'string' && fmt !== '' && fmt !== 'General') {
191
+ numFmtId = this.numFmts.get(fmt) ?? 164 + this.numFmts.size;
192
+ this.numFmts.set(fmt, numFmtId);
193
+ }
194
+ const color = hexColor(style.color);
195
+ const font = `<font>${style.bold ? '<b/>' : ''}${style.italic ? '<i/>' : ''}<sz val="${style.fontSize ?? 11}"/>${color ? `<color rgb="FF${color}"/>` : ''}<name val="Calibri"/></font>`;
196
+ let fontId = this.fontIds.get(font);
197
+ if (fontId === undefined) {
198
+ fontId = this.fonts.length;
199
+ this.fonts.push(font);
200
+ this.fontIds.set(font, fontId);
201
+ }
202
+ let fillId = 0;
203
+ const bg = hexColor(style.backgroundColor);
204
+ if (bg) {
205
+ fillId = this.fillIds.get(bg) ?? this.fills.length;
206
+ if (fillId === this.fills.length) {
207
+ this.fills.push(`<fill><patternFill patternType="solid"><fgColor rgb="FF${bg}"/><bgColor indexed="64"/></patternFill></fill>`);
208
+ this.fillIds.set(bg, fillId);
209
+ }
210
+ }
211
+ const horizontal = style.textAlign === 'center' ? 'center' : style.textAlign === 'end' ? 'right' : indent > 0 || style.textAlign === 'start' ? 'left' : null;
212
+ const alignment = horizontal || indent > 0 ? `<alignment${horizontal ? ` horizontal="${horizontal}"` : ''}${indent > 0 ? ` indent="${indent}"` : ''}/>` : '';
213
+ const attrs = `numFmtId="${numFmtId}" fontId="${fontId}" fillId="${fillId}" borderId="0" xfId="0"${numFmtId ? ' applyNumberFormat="1"' : ''}${fontId ? ' applyFont="1"' : ''}${fillId ? ' applyFill="1"' : ''}${alignment ? ' applyAlignment="1"' : ''}`;
214
+ const id = this.xfs.length;
215
+ this.xfs.push(alignment ? `<xf ${attrs}>${alignment}</xf>` : `<xf ${attrs}/>`);
216
+ this.xfIds.set(key, id);
217
+ return id;
218
+ }
219
+ /** The same style with Excel's quote prefix: re-entering the cell keeps formula-like text as text. */
220
+ quoted(id) {
221
+ let q = this.quotedIds.get(id);
222
+ if (q === undefined) {
223
+ q = this.xfs.length;
224
+ this.xfs.push(this.xfs[id].replace('<xf ', '<xf quotePrefix="1" '));
225
+ this.quotedIds.set(id, q);
226
+ }
227
+ return q;
228
+ }
229
+ xml() {
230
+ const numFmts = [...this.numFmts].map(([code, id]) => `<numFmt numFmtId="${id}" formatCode="${xml(code)}"/>`).join('');
231
+ return (`${HEAD}<styleSheet xmlns="${NS}">` +
232
+ (numFmts ? `<numFmts count="${this.numFmts.size}">${numFmts}</numFmts>` : '') +
233
+ `<fonts count="${this.fonts.length}">${this.fonts.join('')}</fonts>` +
234
+ `<fills count="${this.fills.length}">${this.fills.join('')}</fills>` +
235
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
236
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
237
+ `<cellXfs count="${this.xfs.length}">${this.xfs.join('')}</cellXfs>` +
238
+ '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
239
+ '</styleSheet>');
240
+ }
241
+ }
242
+ // ---------------------------------------------------------------------------
243
+ // Workbook
244
+ // ---------------------------------------------------------------------------
245
+ const FLUSH_CHARS = 512 * 1024;
246
+ const MAX_OUTLINE = 7;
247
+ /**
248
+ * Deepest row outline level of a model relative to its own rows: group
249
+ * levels, and child models one level below their detail row. Only
250
+ * models with detail rows are scanned.
251
+ */
252
+ function outlineDepth(model) {
253
+ let depth = model.groupDepth ? model.groupDepth + 1 : (model.tree?.depth ?? 0);
254
+ for (let i = 0; model.detailRowCount && i < model.rowCount && depth < MAX_OUTLINE; i++) {
255
+ const row = model.getRow(i);
256
+ if (row.kind === 'detail')
257
+ depth = Math.max(depth, row.depth + (row.detail.model ? outlineDepth(row.detail.model) : 0));
258
+ }
259
+ return depth;
260
+ }
261
+ function sheetNameOf(name, used) {
262
+ let base = name.replace(/[[\]:*?/\\]/g, ' ').trim().slice(0, 31) || 'Sheet';
263
+ let candidate = base;
264
+ for (let i = 2; used.has(candidate.toLowerCase()); i++) {
265
+ const suffix = ` (${i})`;
266
+ candidate = base.slice(0, 31 - suffix.length) + suffix;
267
+ }
268
+ used.add(candidate.toLowerCase());
269
+ return candidate;
270
+ }
271
+ class Workbook {
272
+ zip;
273
+ styles = new Styles();
274
+ strings = new Map();
275
+ stringList = [];
276
+ stringRefs = 0;
277
+ sheets = [];
278
+ used = new Set();
279
+ slicer;
280
+ typed;
281
+ theme;
282
+ /** Image parts, created on the first image cell. */
283
+ media = null;
284
+ drawings = 0;
285
+ constructor(options) {
286
+ this.zip = new ZipWriter({ compress: options.compress !== false });
287
+ this.slicer = createSlicer(Math.max(1, options.sliceMs ?? 25), options.yield ?? defaultYield);
288
+ this.typed = options.values !== 'text';
289
+ this.theme = stylesOf(options.styles);
290
+ }
291
+ sharedString(text) {
292
+ this.stringRefs++;
293
+ let id = this.strings.get(text);
294
+ if (id === undefined) {
295
+ id = this.stringList.length;
296
+ this.stringList.push(text);
297
+ this.strings.set(text, id);
298
+ }
299
+ return id;
300
+ }
301
+ async sheet(name, models, options) {
302
+ const index = this.sheets.length + 1;
303
+ this.sheets.push(sheetNameOf(name, this.used));
304
+ const entry = this.zip.entry(`xl/worksheets/sheet${index}.xml`);
305
+ const writer = new SheetWriter(this, entry, this.slicer, options, this.typed, this.theme);
306
+ const pictures = await writer.write(models);
307
+ if (pictures)
308
+ await this.drawing(index, pictures);
309
+ }
310
+ /** Media part name of an image (one per distinct bytes), or null when it cannot be embedded. */
311
+ mediaOf(image) {
312
+ const type = imageType(image);
313
+ if (!type)
314
+ return null;
315
+ const media = (this.media ??= { store: new ImageStore(), files: [] });
316
+ return media.store.get(image.data, () => {
317
+ const name = `image${media.files.length + 1}.${type}`;
318
+ media.files.push([name, image.data]);
319
+ return name;
320
+ });
321
+ }
322
+ /** Drawing part, its relationships, and the sheet relationship for a sheet's pictures. */
323
+ async drawing(sheet, pictures) {
324
+ const d = ++this.drawings;
325
+ const rels = (items) => `${HEAD}<Relationships xmlns="${PKG_REL_NS}">${items}</Relationships>`;
326
+ await this.zip.add(`xl/worksheets/_rels/sheet${sheet}.xml.rels`, rels(`<Relationship Id="rId1" Type="${REL_NS}/drawing" Target="../drawings/drawing${d}.xml"/>`));
327
+ await this.zip.add(`xl/drawings/drawing${d}.xml`, `${HEAD}<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${REL_NS}">${pictures.anchors.join('')}</xdr:wsDr>`);
328
+ await this.zip.add(`xl/drawings/_rels/drawing${d}.xml.rels`, rels([...pictures.rIds].map(([name, id]) => `<Relationship Id="${id}" Type="${REL_NS}/image" Target="../media/${name}"/>`).join('')));
329
+ }
330
+ styleId(key) {
331
+ return this.styles.get(key);
332
+ }
333
+ quotedStyle(id) {
334
+ return this.styles.quoted(id);
335
+ }
336
+ async finish() {
337
+ const n = this.sheets.length;
338
+ let overrides = this.sheets.map((_, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('');
339
+ let defaults = '';
340
+ if (this.media) {
341
+ const files = this.media.files;
342
+ for (const ext of ['png', 'jpeg'])
343
+ if (files.some(([name]) => name.endsWith(ext)))
344
+ defaults += `<Default Extension="${ext}" ContentType="image/${ext}"/>`;
345
+ for (let d = 1; d <= this.drawings; d++)
346
+ overrides += `<Override PartName="/xl/drawings/drawing${d}.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>`;
347
+ for (const [name, data] of files)
348
+ await this.zip.add(`xl/media/${name}`, data);
349
+ }
350
+ await this.zip.add('[Content_Types].xml', `${HEAD}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
351
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
352
+ '<Default Extension="xml" ContentType="application/xml"/>' +
353
+ defaults +
354
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
355
+ overrides +
356
+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
357
+ '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' +
358
+ '</Types>');
359
+ await this.zip.add('_rels/.rels', `${HEAD}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${REL_NS}/officeDocument" Target="xl/workbook.xml"/></Relationships>`);
360
+ await this.zip.add('xl/workbook.xml', `${HEAD}<workbook xmlns="${NS}" xmlns:r="${REL_NS}"><bookViews><workbookView/></bookViews><sheets>` +
361
+ this.sheets.map((s, i) => `<sheet name="${xml(s)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join('') +
362
+ '</sheets></workbook>');
363
+ await this.zip.add('xl/_rels/workbook.xml.rels', `${HEAD}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
364
+ this.sheets.map((_, i) => `<Relationship Id="rId${i + 1}" Type="${REL_NS}/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`).join('') +
365
+ `<Relationship Id="rId${n + 1}" Type="${REL_NS}/styles" Target="styles.xml"/>` +
366
+ `<Relationship Id="rId${n + 2}" Type="${REL_NS}/sharedStrings" Target="sharedStrings.xml"/>` +
367
+ '</Relationships>');
368
+ await this.zip.add('xl/styles.xml', this.styles.xml());
369
+ const sst = this.zip.entry('xl/sharedStrings.xml');
370
+ await sst.write(utf8(`${HEAD}<sst xmlns="${NS}" count="${this.stringRefs}" uniqueCount="${this.stringList.length}">`));
371
+ let parts = [];
372
+ let size = 0;
373
+ for (const s of this.stringList) {
374
+ const t = xml(s);
375
+ parts.push(`<si><t xml:space="preserve">${t}</t></si>`);
376
+ size += t.length + 40;
377
+ if (size > FLUSH_CHARS) {
378
+ await sst.write(utf8(parts.join('')));
379
+ parts = [];
380
+ size = 0;
381
+ }
382
+ }
383
+ parts.push('</sst>');
384
+ await sst.write(utf8(parts.join('')));
385
+ await sst.close();
386
+ return this.zip.finish();
387
+ }
388
+ }
389
+ class SheetWriter {
390
+ row = 0;
391
+ parts = [];
392
+ size = 0;
393
+ merges = [];
394
+ letters = [];
395
+ maxOutline = 0;
396
+ pictures = null;
397
+ book;
398
+ entry;
399
+ slicer;
400
+ options;
401
+ typed;
402
+ theme;
403
+ constructor(book, entry, slicer, options, typed, theme) {
404
+ this.book = book;
405
+ this.entry = entry;
406
+ this.slicer = slicer;
407
+ this.options = options;
408
+ this.typed = typed;
409
+ this.theme = theme;
410
+ }
411
+ ref(col) {
412
+ let l = this.letters[col];
413
+ if (l === undefined) {
414
+ l = columnLetter(col);
415
+ this.letters[col] = l;
416
+ }
417
+ return l;
418
+ }
419
+ async emit(text) {
420
+ this.parts.push(text);
421
+ this.size += text.length;
422
+ if (this.size >= FLUSH_CHARS)
423
+ await this.flush();
424
+ if (this.slicer.due())
425
+ await this.slicer.pause();
426
+ }
427
+ async flush() {
428
+ if (!this.parts.length)
429
+ return;
430
+ const chunk = this.parts.join('');
431
+ this.parts = [];
432
+ this.size = 0;
433
+ await this.entry.write(utf8(chunk));
434
+ }
435
+ rowOpen(outline, extra = '') {
436
+ this.row++;
437
+ const level = Math.min(MAX_OUTLINE, outline);
438
+ if (level > this.maxOutline)
439
+ this.maxOutline = level;
440
+ return level > 0 ? `<row r="${this.row}" outlineLevel="${level}"${extra}>` : `<row r="${this.row}"${extra}>`;
441
+ }
442
+ textCell(col, text, s) {
443
+ if (text === '')
444
+ return s ? `<c r="${this.ref(col)}${this.row}" s="${s}"/>` : '';
445
+ const style = isFormulaText(text) ? this.book.quotedStyle(s) : s;
446
+ return `<c r="${this.ref(col)}${this.row}"${style ? ` s="${style}"` : ''} t="s"><v>${this.book.sharedString(text)}</v></c>`;
447
+ }
448
+ valueCell(col, value, text, s, dateS, serial, formula) {
449
+ const r = `${this.ref(col)}${this.row}`;
450
+ if (formula !== undefined) {
451
+ const f = `<f>${xml(formula.startsWith('=') ? formula.slice(1) : formula)}</f>`;
452
+ return typeof value === 'number' && Number.isFinite(value) ? `<c r="${r}"${s ? ` s="${s}"` : ''}>${f}<v>${value}</v></c>` : `<c r="${r}"${s ? ` s="${s}"` : ''}>${f}</c>`;
453
+ }
454
+ if (!this.typed)
455
+ return this.textCell(col, text, s);
456
+ if (typeof value === 'number') {
457
+ if (Number.isFinite(value))
458
+ return `<c r="${r}"${s ? ` s="${s}"` : ''}><v>${value}</v></c>`;
459
+ return this.textCell(col, text, s);
460
+ }
461
+ if (typeof value === 'boolean')
462
+ return `<c r="${r}"${s ? ` s="${s}"` : ''} t="b"><v>${value ? 1 : 0}</v></c>`;
463
+ if (value instanceof Date) {
464
+ const t = value.getTime();
465
+ if (Number.isNaN(t))
466
+ return this.textCell(col, text, s);
467
+ return `<c r="${r}" s="${dateS}"><v>${serial(value)}</v></c>`;
468
+ }
469
+ if (value === null || value === undefined)
470
+ return s ? `<c r="${r}" s="${s}"/>` : '';
471
+ return this.textCell(col, text, s);
472
+ }
473
+ /** Anchors an image at a cell (0-based column, 1-based row); returns its height in points, or 0 when it cannot be embedded. */
474
+ picture(col, row, image) {
475
+ const name = this.book.mediaOf(image);
476
+ if (!name)
477
+ return 0;
478
+ const p = (this.pictures ??= { anchors: [], rIds: new Map() });
479
+ let rId = p.rIds.get(name);
480
+ if (!rId)
481
+ p.rIds.set(name, (rId = `rId${p.rIds.size + 1}`));
482
+ const id = p.anchors.length + 1;
483
+ const cx = Math.round(image.width * EMU_PER_PX);
484
+ const cy = Math.round(image.height * EMU_PER_PX);
485
+ p.anchors.push(`<xdr:oneCellAnchor><xdr:from><xdr:col>${col}</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>${row - 1}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:ext cx="${cx}" cy="${cy}"/>` +
486
+ `<xdr:pic><xdr:nvPicPr><xdr:cNvPr id="${id + 1}" name="Picture ${id}"/><xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr></xdr:nvPicPr>` +
487
+ `<xdr:blipFill><a:blip r:embed="${rId}"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill>` +
488
+ `<xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:oneCellAnchor>`);
489
+ return image.height * 0.75;
490
+ }
491
+ /** Writes the sheet; returns its pictures, if any. */
492
+ async write(models) {
493
+ const o = this.options;
494
+ const first = models[0];
495
+ const includeHeaders = o.includeHeaders !== false;
496
+ const headerLines = o.header ? o.header.rows.length + (o.header.gap ?? 0) : 0;
497
+ const headerRows = includeHeaders ? first.headerRows.length : 0;
498
+ // Columns: widest model per position.
499
+ const widths = [];
500
+ for (const m of models)
501
+ m.columns.forEach((c, i) => (widths[i] = Math.max(widths[i] ?? 0, c.width)));
502
+ const cols = widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${Math.max(1, Math.round(((w - 5) / 7) * 100) / 100)}" customWidth="1"/>`).join('');
503
+ const xSplit = first.frozen.left;
504
+ const ySplit = o.freezeHeader ? headerLines + headerRows : 0;
505
+ let pane = '';
506
+ if (xSplit > 0 || ySplit > 0) {
507
+ const active = xSplit && ySplit ? 'bottomRight' : xSplit ? 'topRight' : 'bottomLeft';
508
+ pane = `<pane${xSplit ? ` xSplit="${xSplit}"` : ''}${ySplit ? ` ySplit="${ySplit}"` : ''} topLeftCell="${columnLetter(xSplit)}${ySplit + 1}" activePane="${active}" state="frozen"/>`;
509
+ }
510
+ const rtl = first.direction === 'rtl' ? ' rightToLeft="1"' : '';
511
+ const maxDepth = Math.min(MAX_OUTLINE, Math.max(0, ...models.map((m) => outlineDepth(m))));
512
+ await this.emit(`${HEAD}<worksheet xmlns="${NS}" xmlns:r="${REL_NS}">` +
513
+ '<sheetPr><outlinePr summaryBelow="0"/></sheetPr>' +
514
+ `<sheetViews><sheetView workbookViewId="0"${rtl}>${pane}</sheetView></sheetViews>` +
515
+ `<sheetFormatPr defaultRowHeight="15"${maxDepth > 0 ? ` outlineLevelRow="${maxDepth}"` : ''}/>` +
516
+ (cols ? `<cols>${cols}</cols>` : '') +
517
+ '<sheetData>');
518
+ if (o.header) {
519
+ await this.content(o.header.rows);
520
+ for (let b = 0; b < (o.header.gap ?? 0); b++)
521
+ await this.emit(`${this.rowOpen(0)}</row>`);
522
+ }
523
+ for (let i = 0; i < models.length; i++) {
524
+ if (i > 0)
525
+ for (let b = 0; b < (o.gap ?? 5); b++)
526
+ await this.emit(`${this.rowOpen(0)}</row>`);
527
+ await this.model(models[i], { colOffset: 0, outline: 0 }, includeHeaders);
528
+ }
529
+ if (o.footer) {
530
+ for (let b = 0; b < (o.footer.gap ?? 0); b++)
531
+ await this.emit(`${this.rowOpen(0)}</row>`);
532
+ await this.content(o.footer.rows);
533
+ }
534
+ await this.emit('</sheetData>');
535
+ if (this.merges.length)
536
+ await this.emit(`<mergeCells count="${this.merges.length}">${this.merges.map((m) => `<mergeCell ref="${m}"/>`).join('')}</mergeCells>`);
537
+ await this.emit(`<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>${this.pictures ? '<drawing r:id="rId1"/>' : ''}</worksheet>`);
538
+ await this.flush();
539
+ await this.entry.close();
540
+ return this.pictures;
541
+ }
542
+ async content(rows) {
543
+ const serial = createSerial(undefined);
544
+ for (const r of rows) {
545
+ let xmlRow = this.rowOpen(0);
546
+ let next = 0;
547
+ const cells = [...r.cells].map((c) => {
548
+ const index = c.column ?? next;
549
+ next = index + (c.colSpan ?? 1);
550
+ return { ...c, index };
551
+ });
552
+ cells.sort((a, b) => a.index - b.index);
553
+ for (const c of cells) {
554
+ const s = c.style ? this.book.styleId({ style: c.style, numFmt: null, indent: 0 }) : 0;
555
+ const ds = this.book.styleId({ style: c.style ?? {}, numFmt: 14, indent: 0 });
556
+ const value = c.value ?? null;
557
+ xmlRow += this.valueCell(c.index, value, value instanceof Date ? value.toISOString() : value === null ? '' : String(value), s, ds, serial);
558
+ if ((c.colSpan ?? 1) > 1 || (c.rowSpan ?? 1) > 1)
559
+ this.merge(c.index, this.row, c.index + (c.colSpan ?? 1) - 1, this.row + (c.rowSpan ?? 1) - 1);
560
+ }
561
+ await this.emit(`${xmlRow}</row>`);
562
+ }
563
+ }
564
+ merge(c0, r0, c1, r1) {
565
+ if (c0 === c1 && r0 === r1)
566
+ return;
567
+ this.merges.push(`${this.ref(c0)}${r0}:${this.ref(c1)}${r1}`);
568
+ }
569
+ async model(model, at, includeHeaders) {
570
+ const book = this.book;
571
+ const theme = this.theme;
572
+ const columns = model.columns;
573
+ const n = columns.length;
574
+ const off = at.colOffset;
575
+ const serial = createSerial(model.timeZone);
576
+ const numFmts = columns.map((c) => excelNumberFormat(c.format, c.type));
577
+ const align = (c) => (c.textAlign === 'start' ? {} : { textAlign: c.textAlign });
578
+ const recordStyles = columns.map((c, i) => book.styleId({ style: mergeStyle(theme.row, align(c)), numFmt: numFmts[i] ?? null, indent: 0 }));
579
+ const dateStyles = columns.map((c, i) => book.styleId({ style: mergeStyle(theme.row, align(c)), numFmt: typeof numFmts[i] === 'string' || typeof numFmts[i] === 'number' ? numFmts[i] : 14, indent: 0 }));
580
+ const aggregateFmt = (i, type) => (type === 'count' || type === 'trueCount' || type === 'falseCount' ? null : (numFmts[i] ?? null));
581
+ // --- header rows ---------------------------------------------------------
582
+ if (includeHeaders && model.headerRows.length) {
583
+ const top = this.row + 1;
584
+ const depth = model.headerRows.length;
585
+ const covered = Array.from({ length: depth }, () => new Array(n).fill(false));
586
+ const anchors = Array.from({ length: depth }, () => new Array(n).fill(null));
587
+ const aligns = Array.from({ length: depth }, () => new Array(n).fill('start'));
588
+ const styles = Array.from({ length: depth }, () => new Array(n).fill(undefined));
589
+ model.headerRows.forEach((cells, level) => {
590
+ for (const h of cells) {
591
+ anchors[level][h.colIndex] = h.text;
592
+ aligns[level][h.colIndex] = h.textAlign;
593
+ if (h.style)
594
+ for (let c = h.colIndex; c < Math.min(n, h.colIndex + h.colSpan); c++)
595
+ styles[level][c] = h.style;
596
+ for (let r = level; r < Math.min(depth, level + h.rowSpan); r++)
597
+ for (let c = h.colIndex; c < Math.min(n, h.colIndex + h.colSpan); c++)
598
+ covered[r][c] = true;
599
+ if (h.colSpan > 1 || h.rowSpan > 1)
600
+ this.merge(off + h.colIndex, top + level, off + h.colIndex + h.colSpan - 1, top + level + h.rowSpan - 1);
601
+ }
602
+ });
603
+ for (let level = 0; level < depth; level++) {
604
+ let xmlRow = this.rowOpen(at.outline);
605
+ for (let c = 0; c < n; c++) {
606
+ const text = anchors[level][c] ?? null;
607
+ const s = book.styleId({ style: mergeStyle(mergeStyle(theme.header, { textAlign: aligns[level][c] }), styles[level][c]), numFmt: null, indent: 0 });
608
+ if (text !== null)
609
+ xmlRow += this.textCell(off + c, text, s);
610
+ else if (covered[level][c])
611
+ xmlRow += `<c r="${this.ref(off + c)}${this.row}" s="${s}"/>`;
612
+ }
613
+ await this.emit(`${xmlRow}</row>`);
614
+ }
615
+ }
616
+ // --- body ------------------------------------------------------------------
617
+ const mergeRepeated = this.options.mergeRepeatedValues === true;
618
+ const keepCollapsed = this.options.outlineCollapsed === true;
619
+ const runStart = new Int32Array(n).fill(-1);
620
+ const runText = new Array(n).fill(null);
621
+ const coverUntil = new Int32Array(n);
622
+ const closeRuns = () => {
623
+ if (!mergeRepeated)
624
+ return;
625
+ for (let c = 0; c < n; c++) {
626
+ const s = runStart[c];
627
+ if (s >= 0 && this.row > s)
628
+ this.merge(off + c, s, off + c, this.row);
629
+ runStart[c] = -1;
630
+ runText[c] = null;
631
+ }
632
+ };
633
+ const captionStyleCache = new Map();
634
+ const captionStyle = (depth) => {
635
+ let s = captionStyleCache.get(depth);
636
+ if (s === undefined) {
637
+ s = book.styleId({ style: theme.groupCaption, numFmt: null, indent: depth });
638
+ captionStyleCache.set(depth, s);
639
+ }
640
+ return s;
641
+ };
642
+ const aggregateRow = async (cells, outline, first, firstStyle, style) => {
643
+ let xmlRow = this.rowOpen(outline);
644
+ for (let c = 0; c < n; c++) {
645
+ const a = cells[c] ?? null;
646
+ if (c === 0 && first !== null) {
647
+ xmlRow += this.textCell(off, a ? `${first} ${a.text}` : first, firstStyle);
648
+ continue;
649
+ }
650
+ const cellStyle = mergeStyle(mergeStyle(style, align(columns[c])), a?.style);
651
+ const s = book.styleId({ style: cellStyle, numFmt: a ? aggregateFmt(c, a.type) : null, indent: 0 });
652
+ if (!a) {
653
+ xmlRow += `<c r="${this.ref(off + c)}${this.row}" s="${s}"/>`;
654
+ continue;
655
+ }
656
+ const ds = book.styleId({ style: cellStyle, numFmt: numFmts[c] ?? 14, indent: 0 });
657
+ xmlRow += this.valueCell(off + c, a.value, a.text, s, ds, serial);
658
+ }
659
+ await this.emit(`${xmlRow}</row>`);
660
+ };
661
+ for (let i = 0; i < model.rowCount; i++) {
662
+ const row = model.getRow(i);
663
+ switch (row.kind) {
664
+ case 'data': {
665
+ let xmlRow = this.rowOpen(at.outline + row.depth, keepCollapsed && (row.hidden || row.collapsed) ? `${row.hidden ? ' hidden="1"' : ''}${row.collapsed ? ' collapsed="1"' : ''}` : '');
666
+ const r = this.row;
667
+ let skip = 0;
668
+ let imageHeight = 0;
669
+ for (let c = 0; c < n; c++) {
670
+ const column = columns[c];
671
+ if (skip > 0 || coverUntil[c] >= r) {
672
+ if (skip > 0)
673
+ skip--;
674
+ continue;
675
+ }
676
+ let cell;
677
+ let s = recordStyles[c];
678
+ let ds = dateStyles[c];
679
+ if (model.hasCellHook) {
680
+ cell = model.cell(row, column);
681
+ if (cell.style) {
682
+ s = book.styleId({ style: mergeStyle(mergeStyle(theme.row, align(column)), cell.style), numFmt: numFmts[c] ?? null, indent: 0 });
683
+ ds = book.styleId({ style: mergeStyle(mergeStyle(theme.row, align(column)), cell.style), numFmt: numFmts[c] ?? 14, indent: 0 });
684
+ }
685
+ const cs = Math.max(1, Math.min(n - c, cell.colSpan ?? 1));
686
+ const rs = Math.max(1, cell.rowSpan ?? 1);
687
+ if (cs > 1 || rs > 1) {
688
+ this.merge(off + c, r, off + c + cs - 1, r + rs - 1);
689
+ skip = cs - 1;
690
+ if (rs > 1)
691
+ for (let k = c; k < c + cs; k++)
692
+ coverUntil[k] = r + rs - 1;
693
+ }
694
+ if (cell.image)
695
+ imageHeight = Math.max(imageHeight, this.picture(off + c, r, cell.image));
696
+ }
697
+ else {
698
+ cell = { value: column.value(row.row), text: this.typed ? '' : column.text(row.row), type: column.type };
699
+ }
700
+ if (mergeRepeated) {
701
+ const text = this.typed && !model.hasCellHook ? column.text(row.row) : cell.text;
702
+ if (runStart[c] !== -1 && runText[c] === text) {
703
+ xmlRow += s ? `<c r="${this.ref(off + c)}${r}" s="${s}"/>` : '';
704
+ continue;
705
+ }
706
+ const st = runStart[c];
707
+ if (st >= 0 && r - 1 > st)
708
+ this.merge(off + c, st, off + c, r - 1);
709
+ runStart[c] = r;
710
+ runText[c] = text;
711
+ }
712
+ const value = cell.value;
713
+ // Text is only needed for strings and the text mode; avoid formatting typed values.
714
+ const text = this.typed && !model.hasCellHook && (typeof value !== 'string' && value !== null && typeof value === 'object') ? column.text(row.row) : this.typed && !model.hasCellHook && typeof value === 'string' ? value : cell.text;
715
+ xmlRow += this.valueCell(off + c, value, text, s, ds, serial, cell.formula);
716
+ }
717
+ // A row grows to its tallest image (Excel caps row heights at 409 pt).
718
+ if (imageHeight > 15)
719
+ xmlRow = xmlRow.replace(`<row r="${r}"`, `<row r="${r}" ht="${Math.min(409, Math.ceil(imageHeight * 4) / 4)}" customHeight="1"`);
720
+ await this.emit(`${xmlRow}</row>`);
721
+ break;
722
+ }
723
+ case 'group': {
724
+ closeRuns();
725
+ await aggregateRow(row.aggregates, at.outline + row.depth, row.caption, captionStyle(row.depth), theme.groupCaption);
726
+ break;
727
+ }
728
+ case 'groupFooter':
729
+ closeRuns();
730
+ await aggregateRow(row.aggregates, at.outline + row.depth + 1, null, 0, theme.aggregate);
731
+ break;
732
+ case 'aggregate':
733
+ closeRuns();
734
+ await aggregateRow(row.aggregates, at.outline, null, 0, theme.aggregate);
735
+ break;
736
+ case 'detail': {
737
+ closeRuns();
738
+ const detail = row.detail;
739
+ for (const line of detail.text ?? [])
740
+ await this.emit(`${this.rowOpen(at.outline + row.depth)}${this.textCell(off + 1, line, 0)}</row>`);
741
+ if (detail.model)
742
+ await this.model(detail.model, { colOffset: off + 1, outline: at.outline + row.depth }, true);
743
+ break;
744
+ }
745
+ }
746
+ }
747
+ // Last row of open runs.
748
+ if (mergeRepeated) {
749
+ for (let c = 0; c < n; c++) {
750
+ const s = runStart[c];
751
+ if (s >= 0 && this.row > s)
752
+ this.merge(off + c, s, off + c, this.row);
753
+ }
754
+ }
755
+ for (const f of model.footerRows)
756
+ await aggregateRow(f.aggregates, at.outline, null, 0, theme.aggregate);
757
+ }
758
+ }
759
+ //# sourceMappingURL=xlsx-writer.js.map