@mdgs/pivotjet 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.
package/src/export.js ADDED
@@ -0,0 +1,775 @@
1
+ // Pivot exporters: Excel (.xlsx) and PDF. Zero dependencies, synchronous, DOM-free (Node + browser).
2
+ //
3
+ // toXLSX(result, opts) -> Uint8Array (hand-written OOXML in a STORED zip)
4
+ // toPDF(result, opts) -> Uint8Array (hand-written PDF 1.4, Helvetica, paginated + column bands)
5
+ // downloadBlob(bytes, filename, mime) (browser helper)
6
+
7
+ import { makeFormatter, PRESETS } from './format.js';
8
+ import { compileCellRules, parseColor, styleCss, cssFamily, officeFamily } from './cellfmt.js';
9
+ import { esc } from './util.js';
10
+ import { createFontSet, winAnsi, pdfStr } from './pdffont.js';
11
+
12
+ export const XLSX_MAX_ROWS = 1048576;
13
+ export const XLSX_MAX_COLS = 16384;
14
+
15
+ // ---------------------------------------------------------------------------------------
16
+ // shared: flatten a PivotResult into a header grid + body rows
17
+ // ---------------------------------------------------------------------------------------
18
+ /**
19
+ * @returns {{D:number,C:number,M:number,H:number,dimLabels:string[],cols:{node:object,j:number,path:string[]}[],
20
+ * header:string[][],rows:{dims:string[],vals:(number|null)[],kind:'leaf'|'sub'|'grand'}[],extra:number}}
21
+ * Header grid: C rows (one per column dimension) + one values row; cell layout = [D dim cols][M data cols].
22
+ * Only the first `limit` non-grand body rows are materialised; `extra` counts the rest (grand row always kept).
23
+ */
24
+ function buildTable(result, { subtotals = false, grandTotals = true, limit = Infinity, maxCols = Infinity } = {}) {
25
+ const D = result.rowDims.length, C = result.colDims.length, nv = result.values.length;
26
+ const dimLabels = result.rowDims.map((d) => d.label);
27
+ const colNodes = C ? result.leaves('cols') : [result.colRoot];
28
+ const withGrandCols = C > 0 && grandTotals;
29
+
30
+ const cols = [];
31
+ for (const node of colNodes) for (let j = 0; j < nv; j++) cols.push({ node, j, path: C ? node.path() : [] });
32
+ if (withGrandCols) {
33
+ const gp = ['Grand Total'];
34
+ while (gp.length < C) gp.push('');
35
+ for (let j = 0; j < nv; j++) cols.push({ node: result.colRoot, j, path: gp });
36
+ }
37
+ const M = cols.length;
38
+ if (D + M > maxCols) {
39
+ throw new Error(`Excel supports at most ${XLSX_MAX_COLS.toLocaleString('en-US')} columns per sheet; this pivot needs ${(D + M).toLocaleString('en-US')}. Reduce column dimensions, add filters, or export CSV.`);
40
+ }
41
+
42
+ const H = C + 1;
43
+ const header = [];
44
+ for (let L = 0; L < C; L++) {
45
+ const row = new Array(D).fill('');
46
+ for (let k = 0; k < M; k++) row.push(cols[k].path[L] ?? '');
47
+ header.push(row);
48
+ }
49
+ const vrow = dimLabels.slice();
50
+ for (let k = 0; k < M; k++) vrow.push(result.values[cols[k].j].label);
51
+ header.push(vrow);
52
+
53
+ const rows = [];
54
+ let extra = 0;
55
+ const emit = (node, label, kind) => {
56
+ if (kind !== 'grand' && rows.length >= limit) { extra++; return; }
57
+ const path = node.path();
58
+ const dims = [];
59
+ for (let d = 0; d < D; d++) dims.push(d < path.length ? path[d] : d === path.length ? label : '');
60
+ const vals = new Array(M);
61
+ for (let k = 0; k < M; k++) vals[k] = result.get(node, cols[k].node, cols[k].j);
62
+ rows.push({ dims, vals, kind, node });
63
+ };
64
+ // recursion depth == number of row dimensions, never the number of rows
65
+ const walk = (n) => {
66
+ if (!n.children.length) { emit(n, n.label, 'leaf'); return; }
67
+ for (const ch of n.children) walk(ch);
68
+ if (subtotals) emit(n, 'Total', 'sub');
69
+ };
70
+ if (D === 0) emit(result.rowRoot, '', 'grand');
71
+ else {
72
+ for (const ch of result.rowRoot.children) walk(ch);
73
+ if (grandTotals) emit(result.rowRoot, 'Grand Total', 'grand');
74
+ }
75
+ if (D > 0 && grandTotals) rows[rows.length - 1].dims = ['Grand Total', ...new Array(D - 1).fill('')];
76
+ return { D, C, M, H, dimLabels, cols, header, rows, extra };
77
+ }
78
+
79
+ const grandRowCount = (result, grandTotals) => (result.rowDims.length === 0 || grandTotals ? 1 : 0);
80
+
81
+ // ---------------------------------------------------------------------------------------
82
+ // XLSX
83
+ // ---------------------------------------------------------------------------------------
84
+ const enc = new TextEncoder();
85
+ const BAD_XML = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
86
+ const XML_ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
87
+ const xesc = (s) => String(s).replace(BAD_XML, '').replace(/[&<>"]/g, (c) => XML_ESC[c]);
88
+
89
+ const colNameCache = [];
90
+ function colName(i) {
91
+ let s = colNameCache[i];
92
+ if (s !== undefined) return s;
93
+ s = '';
94
+ let n = i + 1;
95
+ while (n > 0) { const m = (n - 1) % 26; s = String.fromCharCode(65 + m) + s; n = ((n - 1 - m) / 26) | 0; }
96
+ return (colNameCache[i] = s);
97
+ }
98
+
99
+ // ---- tiny STORED zip ----
100
+ const CRC_TABLE = (() => {
101
+ const t = new Uint32Array(256);
102
+ for (let n = 0; n < 256; n++) {
103
+ let c = n;
104
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
105
+ t[n] = c >>> 0;
106
+ }
107
+ return t;
108
+ })();
109
+ function crc32(buf) {
110
+ let c = 0xffffffff;
111
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
112
+ return (c ^ 0xffffffff) >>> 0;
113
+ }
114
+ function concat(chunks) {
115
+ let n = 0;
116
+ for (const c of chunks) n += c.length;
117
+ const out = new Uint8Array(n);
118
+ let o = 0;
119
+ for (const c of chunks) { out.set(c, o); o += c.length; }
120
+ return out;
121
+ }
122
+ function zipStore(files, date = new Date()) {
123
+ const dosTime = ((date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1)) & 0xffff;
124
+ const dosDate = ((Math.max(0, date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()) & 0xffff;
125
+ const parts = [], central = [];
126
+ let offset = 0;
127
+ for (const f of files) {
128
+ const name = enc.encode(f.name);
129
+ const crc = crc32(f.data);
130
+ const lh = new DataView(new ArrayBuffer(30));
131
+ lh.setUint32(0, 0x04034b50, true); lh.setUint16(4, 20, true); lh.setUint16(6, 0x0800, true); lh.setUint16(8, 0, true);
132
+ lh.setUint16(10, dosTime, true); lh.setUint16(12, dosDate, true); lh.setUint32(14, crc, true);
133
+ lh.setUint32(18, f.data.length, true); lh.setUint32(22, f.data.length, true); lh.setUint16(26, name.length, true); lh.setUint16(28, 0, true);
134
+ parts.push(new Uint8Array(lh.buffer), name, f.data);
135
+ const ch = new DataView(new ArrayBuffer(46));
136
+ ch.setUint32(0, 0x02014b50, true); ch.setUint16(4, 20, true); ch.setUint16(6, 20, true); ch.setUint16(8, 0x0800, true); ch.setUint16(10, 0, true);
137
+ ch.setUint16(12, dosTime, true); ch.setUint16(14, dosDate, true); ch.setUint32(16, crc, true);
138
+ ch.setUint32(20, f.data.length, true); ch.setUint32(24, f.data.length, true); ch.setUint16(28, name.length, true);
139
+ ch.setUint32(42, offset, true);
140
+ central.push(new Uint8Array(ch.buffer), name);
141
+ offset += 30 + name.length + f.data.length;
142
+ }
143
+ const cdStart = offset;
144
+ let cdSize = 0;
145
+ for (const c of central) cdSize += c.length;
146
+ const eo = new DataView(new ArrayBuffer(22));
147
+ eo.setUint32(0, 0x06054b50, true); eo.setUint16(8, files.length, true); eo.setUint16(10, files.length, true);
148
+ eo.setUint32(12, cdSize, true); eo.setUint32(16, cdStart, true);
149
+ if (offset + cdSize > 0xfffffffe) throw new Error('Export is too large for a ZIP container (4 GB limit)');
150
+ return concat([...parts, ...central, new Uint8Array(eo.buffer)]);
151
+ }
152
+
153
+ const FORMAT_KIND = { number: 'number', integer: 'integer', currency: 'currency', percent: 'percent', compact: 'integer' };
154
+ function excelFormatKind(v) {
155
+ const f = v.format;
156
+ const pct = v.showAs && v.showAs !== 'value';
157
+ if (f == null || typeof f === 'function') return pct ? 'percent' : 'number';
158
+ if (typeof f === 'string') return FORMAT_KIND[f] || 'number';
159
+ const preset = f.preset || (f.style === 'percent' ? 'percent' : f.style === 'currency' ? 'currency' : f.notation === 'compact' ? 'compact' : null);
160
+ if (preset) return FORMAT_KIND[preset] || 'number';
161
+ return f.maximumFractionDigits === 0 ? 'integer' : 'number';
162
+ }
163
+ const NUMFMT_ID = { number: 4, integer: 3, currency: 164, percent: 165 };
164
+ const CURRENCY_SYMBOL = { USD: '$', EUR: '€', GBP: '£', INR: '₹', JPY: '¥', CNY: '¥', KRW: '₩', CHF: 'CHF ', CAD: 'CA$', AUD: 'A$' };
165
+ const q = (t) => '"' + String(t).replace(/"/g, '""') + '"';
166
+ /** Excel number-format code for a pivotjet number format (null for function formats). */
167
+ export function excelNumFmt(fmt, showAs) {
168
+ if (typeof fmt === 'function') return null;
169
+ const spec = fmt == null ? (showAs && showAs !== 'value' ? 'percent' : 'number') : fmt;
170
+ const o = typeof spec === 'string' ? { preset: spec } : spec;
171
+ const pre = { ...(PRESETS[o.preset] || {}), ...o };
172
+ const pad = (n) => (n > 0 ? '.' + '0'.repeat(Math.min(n, 10)) : '');
173
+ let code;
174
+ if (pre.notation === 'compact') code = '[>=1000000]#,##0.0,,"M";[>=1000]#,##0.0,"K";#,##0';
175
+ else if (pre.style === 'percent') code = '0' + pad(pre.maximumFractionDigits ?? pre.minimumFractionDigits ?? 1) + '%';
176
+ else if (pre.style === 'currency') {
177
+ const sym = CURRENCY_SYMBOL[pre.currency] ?? (pre.currency ? pre.currency + ' ' : '$');
178
+ code = q(sym) + (pre.useGrouping === false ? '0' : '#,##0') + pad(pre.maximumFractionDigits ?? pre.minimumFractionDigits ?? 2);
179
+ } else code = (pre.useGrouping === false ? '0' : '#,##0') + pad(pre.maximumFractionDigits ?? pre.minimumFractionDigits ?? 2);
180
+ if (o.prefix || o.suffix) code = (o.prefix ? q(o.prefix) : '') + code + (o.suffix ? q(o.suffix) : '');
181
+ return code;
182
+ }
183
+ const BUILTIN_CODE = { '0': 1, '0.00': 2, '#,##0': 3, '#,##0.00': 4, '0%': 9, '0.00%': 10 };
184
+ const argb = (rgb) => 'FF' + rgb.map((x) => x.toString(16).padStart(2, '0')).join('').toUpperCase();
185
+
186
+ // per-cell styles added on top of the fixed ones
187
+ function makeStyleRegistry(baseCount) {
188
+ const reg = { numFmts: [], fonts: [], fills: [], xfs: [], _nf: new Map(), _fo: new Map(), _fi: new Map(), _xf: new Map() };
189
+ const numFmtId = (code) => {
190
+ if (BUILTIN_CODE[code]) return BUILTIN_CODE[code];
191
+ let id = reg._nf.get(code);
192
+ if (id === undefined) { id = 170 + reg.numFmts.length; reg.numFmts.push({ id, code }); reg._nf.set(code, id); }
193
+ return id;
194
+ };
195
+ const fontId = (bold, italic, underline, rgb, name, size) => {
196
+ if (!italic && !underline && !rgb && !name && !size) return bold ? 1 : 0;
197
+ const key = `${+bold}${+italic}${+underline}${rgb || ''}|${name || ''}|${size || ''}`;
198
+ let id = reg._fo.get(key);
199
+ if (id === undefined) {
200
+ id = 2 + reg.fonts.length;
201
+ reg.fonts.push(`<font>${bold ? '<b/>' : ''}${italic ? '<i/>' : ''}${underline ? '<u/>' : ''}<sz val="${size || 11}"/>${rgb ? `<color rgb="${argb(rgb)}"/>` : ''}<name val="${xesc(name ? officeFamily(name) : 'Calibri')}"/></font>`);
202
+ reg._fo.set(key, id);
203
+ }
204
+ return id;
205
+ };
206
+ const fillId = (rgb) => {
207
+ const key = argb(rgb);
208
+ let id = reg._fi.get(key);
209
+ if (id === undefined) {
210
+ id = 5 + reg.fills.length;
211
+ reg.fills.push(`<fill><patternFill patternType="solid"><fgColor rgb="${key}"/><bgColor indexed="64"/></patternFill></fill>`);
212
+ reg._fi.set(key, id);
213
+ }
214
+ return id;
215
+ };
216
+ reg.xf = (nfId, kind, st) => {
217
+ st = st || {};
218
+ const bold = st.bold ?? kind > 0, rgbText = st.color ? parseColor(st.color) : null, rgbBg = st.background ? parseColor(st.background) : null;
219
+ const fo = fontId(bold, !!st.italic, !!st.underline, rgbText, st.font, st.size);
220
+ const fi = rgbBg ? fillId(rgbBg) : kind === 0 ? 0 : kind === 1 ? 3 : 4;
221
+ const key = `${nfId}|${fo}|${fi}|${st.align || ''}`;
222
+ let idx = reg._xf.get(key);
223
+ if (idx === undefined) {
224
+ idx = baseCount + reg.xfs.length;
225
+ reg.xfs.push(`<xf numFmtId="${nfId}" fontId="${fo}" fillId="${fi}" borderId="0" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1"${st.align ? ` applyAlignment="1"><alignment horizontal="${st.align}"/></xf>` : '/>'}`);
226
+ reg._xf.set(key, idx);
227
+ }
228
+ return idx;
229
+ };
230
+ reg.numFmtId = numFmtId;
231
+ return reg;
232
+ }
233
+ const cellRules = (rules, result, locale) => (typeof rules === 'function' ? rules : rules && rules.length ? compileCellRules(rules, result, { locale }) : null);
234
+ const NUMFMT_CODE = { currency: '"$"#,##0.00', percent: '0.0%' };
235
+
236
+ function stylesXml(fmts, reg) {
237
+ const custom = fmts.filter((f) => NUMFMT_ID[f] >= 164);
238
+ const allFmt = [...custom.map((f) => ({ id: NUMFMT_ID[f], code: NUMFMT_CODE[f] })), ...reg.numFmts];
239
+ const numFmts = allFmt.length
240
+ ? `<numFmts count="${allFmt.length}">${allFmt.map((f) => `<numFmt numFmtId="${f.id}" formatCode="${xesc(f.code)}"/>`).join('')}</numFmts>`
241
+ : '';
242
+ const xfs = [
243
+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>',
244
+ '<xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1" applyAlignment="1"><alignment horizontal="center"/></xf>',
245
+ '<xf numFmtId="0" fontId="1" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>',
246
+ '<xf numFmtId="0" fontId="1" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/>',
247
+ ];
248
+ for (const f of fmts) {
249
+ for (let kind = 0; kind < 3; kind++) {
250
+ xfs.push(`<xf numFmtId="${NUMFMT_ID[f]}" fontId="${kind ? 1 : 0}" fillId="${kind === 0 ? 0 : kind === 1 ? 3 : 4}" borderId="0" xfId="0" applyNumberFormat="1"${kind ? ' applyFont="1" applyFill="1"' : ''}/>`);
251
+ }
252
+ }
253
+ xfs.push(...reg.xfs);
254
+ const fill = (rgb) => `<fill><patternFill patternType="solid"><fgColor rgb="${rgb}"/><bgColor indexed="64"/></patternFill></fill>`;
255
+ return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
256
+ + '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
257
+ + numFmts
258
+ + `<fonts count="${2 + reg.fonts.length}"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font>${reg.fonts.join('')}</fonts>`
259
+ + `<fills count="${5 + reg.fills.length}"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>${fill('FFDDE5F3')}${fill('FFF1F4FA')}${fill('FFE3E9F4')}${reg.fills.join('')}</fills>`
260
+ + '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
261
+ + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
262
+ + `<cellXfs count="${xfs.length}">${xfs.join('')}</cellXfs>`
263
+ + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'
264
+ + '</styleSheet>';
265
+ }
266
+
267
+ function sheetName(name) {
268
+ const s = String(name ?? 'Pivot').replace(/[\[\]:*?\/\\]/g, ' ').trim().slice(0, 31);
269
+ return s || 'Pivot';
270
+ }
271
+
272
+ /**
273
+ * Build an .xlsx workbook (one sheet) from a PivotResult.
274
+ * @param {import('./engine.js').PivotResult} result
275
+ * @param {{subtotals?:boolean, grandTotals?:boolean, sheetName?:string, date?:Date}} [opts]
276
+ * @returns {Uint8Array}
277
+ */
278
+ export function toXLSX(result, opts = {}) {
279
+ const { subtotals = false, grandTotals = true, date = new Date() } = opts;
280
+ const H = result.colDims.length + 1;
281
+ const reserve = H + grandRowCount(result, grandTotals);
282
+ const T = buildTable(result, { subtotals, grandTotals, limit: XLSX_MAX_ROWS - reserve, maxCols: XLSX_MAX_COLS });
283
+ if (T.extra > 0) {
284
+ throw new Error(`Excel supports at most ${XLSX_MAX_ROWS.toLocaleString('en-US')} rows per sheet; this pivot needs ${(XLSX_MAX_ROWS - reserve + T.extra + reserve).toLocaleString('en-US')}. Reduce row dimensions, add filters, or export CSV.`);
285
+ }
286
+ const { D, C, M, dimLabels, cols, header, rows } = T;
287
+
288
+ const fmts = [...new Set(result.values.map(excelFormatKind))];
289
+ const fi = result.values.map((v) => fmts.indexOf(excelFormatKind(v)));
290
+ const numXf = (j, kind) => 4 + fi[j] * 3 + kind;
291
+ const reg = makeStyleRegistry(4 + fmts.length * 3);
292
+ const ev = cellRules(opts.rules, result, opts.locale);
293
+ const baseNf = result.values.map((v, j) => NUMFMT_ID[fmts[fi[j]]]);
294
+ const names = [];
295
+ for (let i = 0; i < D + M; i++) names.push(colName(i));
296
+
297
+ const tcell = (ref, text, s) =>
298
+ `<c r="${ref}" s="${s}" t="inlineStr"><is><t${/^\s|\s$/.test(text) ? ' xml:space="preserve"' : ''}>${xesc(text)}</t></is></c>`;
299
+
300
+ const chunks = [];
301
+ let cur = [];
302
+ const flush = () => { if (cur.length) { chunks.push(enc.encode(cur.join(''))); cur = []; } };
303
+
304
+ // header rows
305
+ const merges = [];
306
+ for (let L = 0; L < H; L++) {
307
+ const rn = L + 1;
308
+ const parts = [`<row r="${rn}">`];
309
+ for (let c = 0; c < D + M; c++) {
310
+ const text = header[L][c];
311
+ parts.push(text === '' ? `<c r="${names[c]}${rn}" s="1"/>` : tcell(names[c] + rn, text, 1));
312
+ }
313
+ parts.push('</row>');
314
+ cur.push(parts.join(''));
315
+ // merge identical adjacent parent labels across the column dimensions
316
+ if (L < C) {
317
+ let start = 0, key = '';
318
+ const keyOf = (k) => cols[k].path.slice(0, L + 1).join('\u0001');
319
+ for (let k = 0; k <= M; k++) {
320
+ const kk = k < M ? keyOf(k) : null;
321
+ if (k === 0) { key = kk; continue; }
322
+ if (kk !== key) {
323
+ if (k - start > 1) merges.push(`<mergeCell ref="${names[D + start]}${rn}:${names[D + k - 1]}${rn}"/>`);
324
+ start = k; key = kk;
325
+ }
326
+ }
327
+ }
328
+ }
329
+ flush();
330
+
331
+ // body
332
+ const dimMax = dimLabels.map((l) => l.length);
333
+ const dataMax = new Float64Array(M);
334
+ for (let i = 0; i < rows.length; i++) {
335
+ const r = rows[i];
336
+ const rn = H + 1 + i;
337
+ const kind = r.kind === 'leaf' ? 0 : r.kind === 'sub' ? 1 : 2;
338
+ const parts = [`<row r="${rn}">`];
339
+ for (let d = 0; d < D; d++) {
340
+ const s = r.dims[d];
341
+ if (s !== '') {
342
+ parts.push(tcell(names[d] + rn, s, kind === 0 ? 0 : kind === 1 ? 2 : 3));
343
+ if (s.length > dimMax[d]) dimMax[d] = s.length;
344
+ } else if (kind) parts.push(`<c r="${names[d]}${rn}" s="${kind === 1 ? 2 : 3}"/>`);
345
+ }
346
+ for (let k = 0; k < M; k++) {
347
+ const v = r.vals[k];
348
+ const ref = names[D + k] + rn;
349
+ const m = ev ? ev(r.node, cols[k].node, cols[k].j, v) : null;
350
+ if (m) {
351
+ const j = cols[k].j;
352
+ const code = m.fmt !== undefined ? excelNumFmt(m.fmt, result.values[j].showAs) : null;
353
+ const xf = reg.xf(code ? reg.numFmtId(code) : baseNf[j], kind, m.style);
354
+ if (m.text !== undefined) parts.push(m.text === '' ? `<c r="${ref}" s="${xf}"/>` : tcell(ref, m.text, xf));
355
+ else if (v === null || v !== v || v === Infinity || v === -Infinity) parts.push(`<c r="${ref}" s="${xf}"/>`);
356
+ else { parts.push(`<c r="${ref}" s="${xf}"><v>${v}</v></c>`); const a = v < 0 ? -v : v; if (a > dataMax[k]) dataMax[k] = a; }
357
+ } else if (v === null || v !== v || v === Infinity || v === -Infinity) { if (kind) parts.push(`<c r="${ref}" s="${numXf(cols[k].j, kind)}"/>`); }
358
+ else {
359
+ parts.push(`<c r="${ref}" s="${numXf(cols[k].j, kind)}"><v>${v}</v></c>`);
360
+ const a = v < 0 ? -v : v;
361
+ if (a > dataMax[k]) dataMax[k] = a;
362
+ }
363
+ }
364
+ parts.push('</row>');
365
+ cur.push(parts.join(''));
366
+ if (cur.length >= 2000) flush();
367
+ }
368
+ flush();
369
+
370
+ // sheet xml
371
+ const lastRef = `${names[D + M - 1] || 'A'}${H + rows.length}`;
372
+ let panes = '';
373
+ const ySplit = H, xSplit = D;
374
+ const tl = `${colName(xSplit)}${ySplit + 1}`;
375
+ if (xSplit > 0) {
376
+ panes = `<pane xSplit="${xSplit}" ySplit="${ySplit}" topLeftCell="${tl}" activePane="bottomRight" state="frozen"/>`
377
+ + '<selection pane="topRight"/><selection pane="bottomLeft"/><selection pane="bottomRight"/>';
378
+ } else {
379
+ panes = `<pane ySplit="${ySplit}" topLeftCell="${tl}" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft"/>`;
380
+ }
381
+ const colsXml = [];
382
+ for (let c = 0; c < D + M; c++) {
383
+ let w;
384
+ if (c < D) w = Math.min(50, Math.max(10, dimMax[c])) * 1.1 + 2;
385
+ else {
386
+ const k = c - D;
387
+ const numLen = Math.round(dataMax[k]).toString().length * 1.3 + 5;
388
+ const hl = Math.max(header[H - 1][c].length, C ? header[C - 1][c].length : 0) * 1.1 + 3;
389
+ w = Math.min(60, Math.max(12, numLen, hl));
390
+ }
391
+ colsXml.push(`<col min="${c + 1}" max="${c + 1}" width="${w.toFixed(2)}" customWidth="1"/>`);
392
+ }
393
+ const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
394
+ + '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
395
+ + `<dimension ref="A1:${lastRef}"/>`
396
+ + `<sheetViews><sheetView workbookViewId="0">${panes}</sheetView></sheetViews>`
397
+ + '<sheetFormatPr defaultRowHeight="15"/>'
398
+ + `<cols>${colsXml.join('')}</cols><sheetData>`;
399
+ const tail = '</sheetData>' + (merges.length ? `<mergeCells count="${merges.length}">${merges.join('')}</mergeCells>` : '') + '</worksheet>';
400
+ const sheet = concat([enc.encode(head), ...chunks, enc.encode(tail)]);
401
+
402
+ const xml = (s) => enc.encode(s);
403
+ const files = [
404
+ { name: '[Content_Types].xml', data: xml('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>') },
405
+ { name: '_rels/.rels', data: xml('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>') },
406
+ { name: 'xl/workbook.xml', data: xml(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><bookViews><workbookView/></bookViews><sheets><sheet name="${xesc(sheetName(opts.sheetName))}" sheetId="1" r:id="rId1"/></sheets></workbook>`) },
407
+ { name: 'xl/_rels/workbook.xml.rels', data: xml('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>') },
408
+ { name: 'xl/styles.xml', data: xml(stylesXml(fmts, reg)) },
409
+ { name: 'xl/worksheets/sheet1.xml', data: sheet },
410
+ ];
411
+ return zipStore(files, date);
412
+ }
413
+
414
+ // ---------------------------------------------------------------------------------------
415
+ // PDF
416
+ // ---------------------------------------------------------------------------------------
417
+ const num = (n) => (Math.round(n * 100) / 100).toString();
418
+
419
+ const PAGE_SIZES = { a4: [595.28, 841.89], letter: [612, 792], a3: [841.89, 1190.55], legal: [612, 1008] };
420
+
421
+ /**
422
+ * Render a PivotResult as a paginated PDF table. Cell rules keep their formatting: fills, text colour, bold, italic,
423
+ * underline, alignment, font family and size. Text is Unicode-safe when a TrueType/OpenType font is supplied.
424
+ * @param {import('./engine.js').PivotResult} result
425
+ * @param {{pageSize?:'a4'|'letter'|'a3'|'legal', orientation?:'landscape'|'portrait', fontSize?:number, margin?:number,
426
+ * title?:string, subtitle?:string, footer?:string, subtotals?:boolean, grandTotals?:boolean, maxRows?:number, locale?:string, date?:Date,
427
+ * rules?:any, font?:string, fonts?:Record<string,{regular?:Uint8Array,bold?:Uint8Array,italic?:Uint8Array,boldItalic?:Uint8Array}>}} [opts]
428
+ * font: default family ('sans' Helvetica, 'serif' Times, 'mono' Courier, or a key of `fonts`).
429
+ * fonts: embedded fonts by family name, e.g. { Inter: { regular: bytes, bold: bytes } }; a rule's style.font can use them.
430
+ * @returns {Uint8Array}
431
+ */
432
+ export function toPDF(result, opts = {}) {
433
+ const o = {
434
+ pageSize: 'a4', orientation: 'landscape', fontSize: 8, margin: 36, maxRows: 50000,
435
+ title: '', subtitle: '', footer: '', subtotals: false, grandTotals: true, locale: undefined, date: new Date(), font: 'sans', ...opts,
436
+ };
437
+ const FS = createFontSet(o.fonts || {}, o.font || 'sans');
438
+ const T = buildTable(result, { subtotals: o.subtotals, grandTotals: o.grandTotals, limit: o.maxRows });
439
+ const { D, C, M, H, dimLabels, header } = T;
440
+ const fs = o.fontSize, pad = 4, margin = o.margin;
441
+ let [pw, ph] = PAGE_SIZES[o.pageSize] || PAGE_SIZES.a4;
442
+ if (o.orientation !== 'portrait') [pw, ph] = [Math.max(pw, ph), Math.min(pw, ph)];
443
+ else [pw, ph] = [Math.min(pw, ph), Math.max(pw, ph)];
444
+ const avail = pw - 2 * margin;
445
+
446
+ const fw = (f, s, size) => f.width(f.prep(s), size);
447
+ const ff = (f, s, maxW, size) => f.fit(f.prep(s), maxW, size);
448
+ const cellFont = (bold, st) => FS.resolve(st && st.font, st && st.bold !== undefined ? st.bold : bold, st && st.italic);
449
+
450
+ // ---- text cells (formatted once; sanitised per font when drawn) ----
451
+ const fmts = result.values.map((v) => makeFormatter(v.format ?? (v.showAs && v.showAs !== 'value' ? 'percent' : 'number'), o.locale));
452
+ const ev = cellRules(o.rules, result, o.locale);
453
+ let maxSize = fs;
454
+ const body = T.rows.map((r) => {
455
+ let st = null;
456
+ const vals = r.vals.map((v, k) => {
457
+ const c = T.cols[k];
458
+ const m = ev ? ev(r.node, c.node, c.j, v) : null;
459
+ if (m) {
460
+ if (m.style) {
461
+ (st || (st = []))[k] = m.style;
462
+ if (m.style.size > maxSize) maxSize = m.style.size;
463
+ }
464
+ if (m.text !== undefined) return m.text;
465
+ if (v === null) return '';
466
+ return (m.fmtFn || fmts[c.j])(v);
467
+ }
468
+ return v === null ? '' : fmts[c.j](v);
469
+ });
470
+ return { kind: r.kind, dims: r.dims, vals, st };
471
+ });
472
+ if (T.extra > 0) {
473
+ const note = { kind: 'note', dims: [`Truncated: ${T.extra.toLocaleString('en-US')} more rows`], vals: [] };
474
+ const last = body[body.length - 1];
475
+ if (last && last.kind === 'grand') body.splice(body.length - 1, 0, note); else body.push(note);
476
+ }
477
+ const rowH = maxSize + 5;
478
+ const hdr = header;
479
+ const nCols = D + M;
480
+ const fReg = FS.resolve(null, false, false), fBold = FS.resolve(null, true, false);
481
+
482
+ // ---- column widths ----
483
+ const colW = new Array(nCols).fill(0);
484
+ for (let c = 0; c < nCols; c++) {
485
+ let mx = fw(fBold, hdr[H - 1][c], fs);
486
+ if (c >= D && C) mx = Math.max(mx, fw(fBold, hdr[C - 1][c], fs));
487
+ colW[c] = mx;
488
+ }
489
+ for (const r of body) {
490
+ if (r.kind === 'note') continue;
491
+ const bold = r.kind !== 'leaf';
492
+ const fd = bold ? fBold : fReg;
493
+ for (let d = 0; d < D; d++) { const w = fw(fd, r.dims[d], fs); if (w > colW[d]) colW[d] = w; }
494
+ for (let k = 0; k < M; k++) {
495
+ const st = r.st && r.st[k];
496
+ const w = fw(cellFont(bold, st), r.vals[k], (st && st.size) || fs);
497
+ if (w > colW[D + k]) colW[D + k] = w;
498
+ }
499
+ }
500
+ const capDim = 0.3 * avail;
501
+ for (let c = 0; c < nCols; c++) {
502
+ const cap = c < D ? capDim : Math.min(avail * 0.5, 170);
503
+ colW[c] = Math.min(cap, Math.max(36, colW[c] + 2 * pad));
504
+ }
505
+ let W0 = 0;
506
+ for (let d = 0; d < D; d++) W0 += colW[d];
507
+ if (W0 > 0.6 * avail) {
508
+ const f = (0.6 * avail) / W0;
509
+ W0 = 0;
510
+ for (let d = 0; d < D; d++) { colW[d] = Math.max(24, colW[d] * f); W0 += colW[d]; }
511
+ }
512
+ const bandAvail = Math.max(60, avail - W0);
513
+ const bands = [];
514
+ {
515
+ let cur = [], used = 0;
516
+ for (let k = 0; k < M; k++) {
517
+ const w = (colW[D + k] = Math.min(colW[D + k], bandAvail));
518
+ if (cur.length && used + w > bandAvail) { bands.push(cur); cur = []; used = 0; }
519
+ cur.push(k); used += w;
520
+ }
521
+ if (cur.length || !bands.length) bands.push(cur);
522
+ }
523
+
524
+ // ---- pagination ----
525
+ const footerH = 16;
526
+ const usable = ph - 2 * margin - footerH;
527
+ const titleH = (o.title ? fs + 8 : 0) + (o.subtitle ? fs + 4 : 0) + (o.title || o.subtitle ? 6 : 0);
528
+ const headerH = H * rowH;
529
+ const rowsFirst = Math.max(1, Math.floor((usable - titleH - headerH) / rowH));
530
+ const rowsRest = Math.max(1, Math.floor((usable - headerH) / rowH));
531
+ const pages = [];
532
+ for (const band of bands) {
533
+ let i = 0;
534
+ do {
535
+ const cap = pages.length === 0 ? rowsFirst : rowsRest;
536
+ pages.push({ band, from: i, to: Math.min(body.length, i + cap) });
537
+ i += cap;
538
+ } while (i < body.length);
539
+ }
540
+ const nPages = pages.length;
541
+
542
+ // prefix keys for header run detection (parent labels span their children within a band)
543
+ const pk = [];
544
+ for (let L = 0; L < C; L++) {
545
+ const keys = new Array(M);
546
+ for (let k = 0; k < M; k++) keys[k] = T.cols[k].path.slice(0, L + 1).join('\u0001');
547
+ pk.push(keys);
548
+ }
549
+
550
+ // ---- drawing ----
551
+ const contents = [];
552
+ for (let p = 0; p < nPages; p++) {
553
+ const pg = pages[p];
554
+ const band = pg.band;
555
+ let bw = 0;
556
+ for (const k of band) bw += colW[D + k];
557
+ const totalW = W0 + bw;
558
+ const x0 = margin;
559
+ const s = [];
560
+ const rect = (x, y, w, h, g) => s.push(`${g} g ${num(x)} ${num(y)} ${num(w)} ${num(h)} re f`);
561
+ const line = (x1, y1, x2, y2, g, lw) => s.push(`${g} G ${lw} w ${num(x1)} ${num(y1)} m ${num(x2)} ${num(y2)} l S`);
562
+ const rgbG = (c) => (c ? `${c.map((x) => num(x / 255)).join(' ')} rg` : '0 g');
563
+ // `str` must already be font.prep()'d (fit() output is)
564
+ const text = (str, x, y, font, size = fs, color = null, underline = false) => {
565
+ if (str === '') return;
566
+ s.push(`BT /${FS.nameOf(font)} ${size} Tf ${rgbG(color)} ${num(x)} ${num(y)} Td ${font.enc(str)} Tj ET`);
567
+ if (underline) {
568
+ const w = font.width(str, size);
569
+ s.push(`${color ? color.map((v) => num(v / 255)).join(' ') + ' RG' : '0 G'} ${num(size * 0.06 + 0.2)} w ${num(x)} ${num(y - size * 0.15)} m ${num(x + w)} ${num(y - size * 0.15)} l S`);
570
+ }
571
+ };
572
+ let top = ph - margin;
573
+ if (p === 0 && titleH) {
574
+ if (o.title) { top -= fs + 8; text(ff(fBold, o.title, avail, fs + 4), x0, top + 3, fBold, fs + 4); }
575
+ if (o.subtitle) { top -= fs + 4; text(ff(fReg, o.subtitle, avail, fs), x0, top + 2, fReg); }
576
+ top -= 6;
577
+ }
578
+ // header block
579
+ const hdrTop = top;
580
+ rect(x0, hdrTop - headerH, totalW, headerH, 0.88);
581
+ for (let L = 0; L < H; L++) {
582
+ const y = hdrTop - (L + 1) * rowH + (rowH - fs) / 2 + 1.5;
583
+ if (L === H - 1) {
584
+ let x = x0;
585
+ for (let d = 0; d < D; d++) { text(ff(fBold, hdr[L][d], colW[d] - 2 * pad, fs), x + pad, y, fBold); x += colW[d]; }
586
+ }
587
+ let x = x0 + W0;
588
+ if (L < C) {
589
+ let bi = 0;
590
+ while (bi < band.length) {
591
+ const k = band[bi];
592
+ let bj = bi, w = 0;
593
+ while (bj < band.length && pk[L][band[bj]] === pk[L][k]) { w += colW[D + band[bj]]; bj++; }
594
+ text(ff(fBold, hdr[L][D + k], w - 2 * pad, fs), x + pad, y, fBold);
595
+ x += w; bi = bj;
596
+ }
597
+ } else {
598
+ for (const k of band) {
599
+ const t = ff(fBold, hdr[L][D + k], colW[D + k] - 2 * pad, fs);
600
+ text(t, x + colW[D + k] - pad - fBold.width(t, fs), y, fBold);
601
+ x += colW[D + k];
602
+ }
603
+ }
604
+ }
605
+ line(x0, hdrTop - headerH, x0 + totalW, hdrTop - headerH, 0.4, 0.6);
606
+ // body rows
607
+ let y = hdrTop - headerH;
608
+ for (let i = pg.from; i < pg.to; i++) {
609
+ const r = body[i];
610
+ y -= rowH;
611
+ const ty = y + (rowH - fs) / 2 + 1.5;
612
+ if (r.kind === 'note') { text(ff(fReg, r.dims[0], totalW - 2 * pad, fs), x0 + pad, ty, fReg); continue; }
613
+ if (r.kind === 'sub') rect(x0, y, totalW, rowH, 0.955);
614
+ else if (r.kind === 'grand') rect(x0, y, totalW, rowH, 0.88);
615
+ const bold = r.kind !== 'leaf';
616
+ const fd = bold ? fBold : fReg;
617
+ const prev = i > pg.from ? body[i - 1] : null;
618
+ let x = x0, same = !bold && prev !== null && prev.kind !== 'note';
619
+ for (let d = 0; d < D; d++) {
620
+ if (same && prev.dims[d] !== r.dims[d]) same = false;
621
+ if (!same) text(ff(fd, r.dims[d], colW[d] - 2 * pad, fs), x + pad, ty, fd);
622
+ x += colW[d];
623
+ }
624
+ for (const k of band) {
625
+ const st = r.st && r.st[k];
626
+ const f = cellFont(bold, st), size = (st && st.size) || fs, cw = colW[D + k];
627
+ const t = ff(f, r.vals[k], cw - 2 * pad, size);
628
+ if (st && st.background) { const bg = parseColor(st.background); if (bg) s.push(`${bg.map((v) => num(v / 255)).join(' ')} rg ${num(x)} ${num(y)} ${num(cw)} ${num(rowH)} re f`); }
629
+ const tw = f.width(t, size);
630
+ const tx = st && st.align === 'left' ? x + pad : st && st.align === 'center' ? x + (cw - tw) / 2 : x + cw - pad - tw;
631
+ text(t, tx, y + (rowH - size) / 2 + 1.5, f, size, st && st.color ? parseColor(st.color) : null, !!(st && st.underline));
632
+ x += cw;
633
+ }
634
+ line(x0, y, x0 + totalW, y, 0.92, 0.3);
635
+ }
636
+ // footer
637
+ if (o.footer) text(ff(fReg, o.footer, avail / 2 - pad, fs), x0, margin - 2, fReg);
638
+ const foot = `Page ${p + 1} of ${nPages}`;
639
+ text(foot, x0 + (avail - fw(fReg, foot, fs)) / 2, margin - 2, fReg);
640
+ contents.push(s.join('\n'));
641
+ }
642
+
643
+ // ---- assemble ----
644
+ const objs = [null];
645
+ objs.length = 4 + 2 * nPages; // 1 catalog, 2 pages, 3 info, then (page, content) pairs
646
+ const alloc = { add: (body) => { objs.push(body); return objs.length - 1; } };
647
+ const fontRes = FS.finish(alloc);
648
+ const pageObj = (p) => 4 + 2 * p;
649
+ objs[1] = '<< /Type /Catalog /Pages 2 0 R >>';
650
+ objs[2] = `<< /Type /Pages /Count ${nPages} /Kids [${pages.map((_, p) => `${pageObj(p)} 0 R`).join(' ')}] >>`;
651
+ const dt = o.date;
652
+ const p2 = (n) => String(n).padStart(2, '0');
653
+ const stamp = `D:${dt.getUTCFullYear()}${p2(dt.getUTCMonth() + 1)}${p2(dt.getUTCDate())}${p2(dt.getUTCHours())}${p2(dt.getUTCMinutes())}${p2(dt.getUTCSeconds())}Z`;
654
+ objs[3] = `<< /Title ${pdfStr(winAnsi(o.title || 'Pivot'))} /Producer (pivotjet) /CreationDate (${stamp}) >>`;
655
+ for (let p = 0; p < nPages; p++) {
656
+ objs[pageObj(p)] = `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${num(pw)} ${num(ph)}] /Resources << /Font << ${fontRes.resources} >> >> /Contents ${pageObj(p) + 1} 0 R >>`;
657
+ objs[pageObj(p) + 1] = `<< /Length ${contents[p].length} >>\nstream\n${contents[p]}\nendstream`;
658
+ }
659
+ const n = objs.length - 1;
660
+ const offsets = new Array(n + 1);
661
+ const out = ['%PDF-1.4\n%âãÏÓ\n'];
662
+ let len = out[0].length;
663
+ for (let i = 1; i <= n; i++) {
664
+ offsets[i] = len;
665
+ const chunk = `${i} 0 obj\n${objs[i]}\nendobj\n`;
666
+ out.push(chunk);
667
+ len += chunk.length;
668
+ }
669
+ let xref = `xref\n0 ${n + 1}\n0000000000 65535 f \n`;
670
+ for (let i = 1; i <= n; i++) xref += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
671
+ xref += `trailer\n<< /Size ${n + 1} /Root 1 0 R /Info 3 0 R >>\nstartxref\n${len}\n%%EOF\n`;
672
+ out.push(xref);
673
+ len += xref.length;
674
+ const bytes = new Uint8Array(len);
675
+ let pos = 0;
676
+ for (const chunk of out) {
677
+ for (let i = 0; i < chunk.length; i++) bytes[pos++] = chunk.charCodeAt(i) & 255;
678
+ }
679
+ return bytes;
680
+ }
681
+
682
+ // ---------------------------------------------------------------------------------------
683
+ // HTML (print / email / embedding)
684
+ // ---------------------------------------------------------------------------------------
685
+ /**
686
+ * The pivot as an HTML <table> with per-cell rules applied (inline styles, no CSS needed).
687
+ * @param {object} result
688
+ * @param {{rules?:any[]|Function, locale?:string, subtotals?:boolean, grandTotals?:boolean, maxRows?:number}} [opts]
689
+ */
690
+ export function toHTMLTable(result, opts = {}) {
691
+ const { subtotals = true, grandTotals = true, locale, maxRows = 20000 } = opts;
692
+ const T = buildTable(result, { subtotals, grandTotals, limit: maxRows });
693
+ const { D, C, M, H, dimLabels, header } = T;
694
+ const ev = cellRules(opts.rules, result, locale);
695
+ const fmts = result.values.map((v) => makeFormatter(v.format ?? (v.showAs && v.showAs !== 'value' ? 'percent' : 'number'), locale));
696
+ const out = ['<table class="pj-table">'];
697
+ // header
698
+ out.push('<thead>');
699
+ for (let L = 0; L < H; L++) {
700
+ out.push('<tr>');
701
+ if (L === H - 1) for (let d = 0; d < D; d++) out.push(`<th class="pj-dim">${esc(dimLabels[d])}</th>`);
702
+ else if (L === 0 && D > 0) out.push(`<th colspan="${D}" rowspan="${H - 1}" class="pj-corner"></th>`);
703
+ if (L < C) {
704
+ let k = 0;
705
+ while (k < M) {
706
+ const key = T.cols[k].path.slice(0, L + 1).join('\u0001');
707
+ let n = 1;
708
+ while (k + n < M && T.cols[k + n].path.slice(0, L + 1).join('\u0001') === key) n++;
709
+ out.push(`<th colspan="${n}" class="pj-ch">${esc(header[L][D + k])}</th>`);
710
+ k += n;
711
+ }
712
+ } else {
713
+ for (let k = 0; k < M; k++) out.push(`<th class="pj-vh">${esc(header[L][D + k])}</th>`);
714
+ }
715
+ out.push('</tr>');
716
+ }
717
+ out.push('</thead><tbody>');
718
+ let prev = null;
719
+ for (const r of T.rows) {
720
+ out.push(`<tr class="pj-${r.kind}">`);
721
+ let same = r.kind === 'leaf' && prev && prev.kind === 'leaf';
722
+ for (let d = 0; d < D; d++) {
723
+ if (same && prev.dims[d] !== r.dims[d]) same = false;
724
+ out.push(`<td class="pj-dim">${same ? '' : esc(r.dims[d])}</td>`);
725
+ }
726
+ for (let k = 0; k < M; k++) {
727
+ const c = T.cols[k], v = r.vals[k];
728
+ const m = ev ? ev(r.node, c.node, c.j, v) : null;
729
+ let text = v === null ? '' : fmts[c.j](v);
730
+ if (m) text = m.text !== undefined ? m.text : v === null ? '' : (m.fmtFn || fmts[c.j])(v);
731
+ const css = m && m.style ? styleCss(m.style) : '';
732
+ out.push(`<td class="pj-n"${css ? ` style="${esc(css)}"` : ''}>${esc(text)}</td>`);
733
+ }
734
+ out.push('</tr>');
735
+ prev = r;
736
+ }
737
+ out.push('</tbody></table>');
738
+ if (T.extra > 0) out.push(`<p class="pj-note">Truncated: ${T.extra.toLocaleString('en-US')} more rows not shown.</p>`);
739
+ return out.join('');
740
+ }
741
+
742
+ const PAGE_CSS_SIZE = { a4: 'A4', letter: 'letter', a3: 'A3', legal: 'legal' };
743
+ /**
744
+ * A complete HTML document for printing (browser Print / Save as PDF) or emailing.
745
+ * @param {object} result
746
+ * @param {{title?:string, subtitle?:string, footer?:string, pageSize?:string, orientation?:'landscape'|'portrait', chartSVG?:string,
747
+ * rules?:any, locale?:string, subtotals?:boolean, grandTotals?:boolean, maxRows?:number, fontSize?:number}} [opts]
748
+ */
749
+ export function toPrintHTML(result, opts = {}) {
750
+ const o = { pageSize: 'a4', orientation: 'landscape', fontSize: 11, ...opts };
751
+ const size = PAGE_CSS_SIZE[o.pageSize] || 'A4';
752
+ const table = toHTMLTable(result, o);
753
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(o.title || 'Pivot')}</title><style>
754
+ @page{size:${size} ${o.orientation === 'portrait' ? 'portrait' : 'landscape'};margin:12mm}
755
+ *{box-sizing:border-box}body{font:${o.fontSize}px/1.35 ${cssFamily(o.font || 'sans')};color:#111;margin:0}
756
+ h1{font-size:${o.fontSize + 6}px;margin:0 0 2px}.sub{color:#555;margin:0 0 10px}.chart{margin:0 0 14px;page-break-inside:avoid}.chart svg{max-width:100%;height:auto}
757
+ table.pj-table{border-collapse:collapse;width:100%}.pj-table th,.pj-table td{padding:3px 7px;border-bottom:1px solid #e3e6ec;white-space:nowrap}
758
+ .pj-table th{background:#dde5f3;text-align:center;font-weight:600;border:1px solid #fff}.pj-table th.pj-dim,.pj-table th.pj-corner{text-align:left}
759
+ .pj-table thead{display:table-header-group}.pj-table tr{page-break-inside:avoid}.pj-table td.pj-n{text-align:right;font-variant-numeric:tabular-nums}
760
+ .pj-sub td{background:#f1f4fa;font-weight:600}.pj-grand td{background:#e3e9f4;font-weight:700}.pj-note{color:#a33}
761
+ .foot{margin-top:10px;color:#777;font-size:${Math.max(8, o.fontSize - 2)}px}
762
+ @media print{*{-webkit-print-color-adjust:exact;print-color-adjust:exact}}
763
+ </style></head><body>${o.title ? `<h1>${esc(o.title)}</h1>` : ''}${o.subtitle ? `<p class="sub">${esc(o.subtitle)}</p>` : ''}${o.chartSVG ? `<div class="chart">${o.chartSVG}</div>` : ''}${table}${o.footer ? `<div class="foot">${esc(o.footer)}</div>` : ''}</body></html>`;
764
+ }
765
+
766
+ /** Browser helper: offer bytes (or a string) as a file download. */
767
+ export function downloadBlob(bytes, filename, mime = 'application/octet-stream') {
768
+ const blob = new Blob([bytes], { type: mime });
769
+ const a = document.createElement('a');
770
+ a.href = URL.createObjectURL(blob);
771
+ a.download = filename;
772
+ document.body.appendChild(a);
773
+ a.click();
774
+ setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 0);
775
+ }