@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/LICENSE +21 -0
- package/README.md +628 -3
- package/bin/pivotjet.mjs +122 -0
- package/dist/core.cjs +4926 -0
- package/dist/core.cjs.map +7 -0
- package/dist/index.cjs +7277 -0
- package/dist/index.cjs.map +7 -0
- package/dist/pivotjet.min.js +334 -0
- package/dist/pivotjet.min.js.map +7 -0
- package/docs/images/cell-formats.png +0 -0
- package/docs/images/chart.png +0 -0
- package/docs/images/configure-fields.png +0 -0
- package/docs/images/designer.png +0 -0
- package/docs/images/large-dataset.png +0 -0
- package/package.json +108 -4
- package/src/cellfmt.js +218 -0
- package/src/chart.js +595 -0
- package/src/core.d.ts +424 -0
- package/src/core.js +18 -0
- package/src/csv.js +198 -0
- package/src/dataset.js +404 -0
- package/src/designer.js +995 -0
- package/src/elements.js +50 -0
- package/src/engine.js +778 -0
- package/src/errors.js +2 -0
- package/src/export.js +775 -0
- package/src/expr.js +180 -0
- package/src/format.js +42 -0
- package/src/holistic.js +237 -0
- package/src/index.d.ts +155 -0
- package/src/index.js +6 -0
- package/src/layouts.js +105 -0
- package/src/node.d.ts +10 -0
- package/src/node.js +29 -0
- package/src/pdffont.js +361 -0
- package/src/remote.js +164 -0
- package/src/report-render.js +31 -0
- package/src/report.js +103 -0
- package/src/reportstore.js +135 -0
- package/src/server.d.ts +20 -0
- package/src/server.js +272 -0
- package/src/stream.js +285 -0
- package/src/styles.js +162 -0
- package/src/util.js +73 -0
- package/src/viewer.js +632 -0
package/src/viewer.js
ADDED
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
// PivotViewer: a virtualized pivot grid. Only the visible window of cells is ever in the DOM, so a
|
|
2
|
+
// result with millions of rows/columns scrolls as smoothly as one with ten. Framework-agnostic.
|
|
3
|
+
|
|
4
|
+
import { PivotError } from './engine.js';
|
|
5
|
+
import { toXLSX, toPDF, toPrintHTML, downloadBlob } from './export.js';
|
|
6
|
+
import { compileCellRules, cleanRules, styleCss } from './cellfmt.js';
|
|
7
|
+
import { PivotChart } from './chart.js';
|
|
8
|
+
import { makeFormatter } from './format.js';
|
|
9
|
+
import { createReport, reportToHTML } from './report.js';
|
|
10
|
+
import { Emitter, esc } from './util.js';
|
|
11
|
+
import { injectStyles } from './styles.js';
|
|
12
|
+
|
|
13
|
+
const MAX_PX = 8_000_000; // browsers cap element size (~16-33M px); scale scrolling beyond this
|
|
14
|
+
const SEP = '\u0001';
|
|
15
|
+
|
|
16
|
+
const DEFAULTS = {
|
|
17
|
+
rowHeight: 28,
|
|
18
|
+
colWidth: 112,
|
|
19
|
+
rowHeaderWidth: 260,
|
|
20
|
+
headerExtraRows: 0, // blank header rows reserved under the column headers (the designer puts the Rows zone there)
|
|
21
|
+
cornerLabels: true, // show the row-dimension names in the top-left corner
|
|
22
|
+
theme: 'auto', // 'light' | 'dark' | 'auto'
|
|
23
|
+
locale: undefined,
|
|
24
|
+
grandTotals: true,
|
|
25
|
+
colSubtotals: true,
|
|
26
|
+
expandRows: 'auto', // true | false | number of levels | 'auto'
|
|
27
|
+
expandCols: 'auto',
|
|
28
|
+
statusBar: true,
|
|
29
|
+
actions: true, // Expand / Collapse / CSV buttons in the status bar
|
|
30
|
+
drill: true, // double-click a cell to see the underlying records
|
|
31
|
+
drillLimit: 200,
|
|
32
|
+
emptyText: 'No data to display',
|
|
33
|
+
maxCells: undefined,
|
|
34
|
+
view: 'table', // 'table' | 'chart'
|
|
35
|
+
chart: { type: 'column' },
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export class PivotViewer extends Emitter {
|
|
39
|
+
/**
|
|
40
|
+
* @param {HTMLElement|string} container
|
|
41
|
+
* @param {object} [options]
|
|
42
|
+
*/
|
|
43
|
+
constructor(container, options = {}) {
|
|
44
|
+
super();
|
|
45
|
+
injectStyles();
|
|
46
|
+
this.el = typeof container === 'string' ? document.querySelector(container) : container;
|
|
47
|
+
if (!this.el) throw new Error('PivotViewer: container not found');
|
|
48
|
+
this.opts = { ...DEFAULTS, ...options };
|
|
49
|
+
this.dataset = options.dataset || null;
|
|
50
|
+
this.spec = options.spec || { rows: [], cols: [], values: [] };
|
|
51
|
+
this.result = null;
|
|
52
|
+
this.rowOpen = new Map();
|
|
53
|
+
this.colOpen = new Map();
|
|
54
|
+
this.sortState = null;
|
|
55
|
+
this.selected = null;
|
|
56
|
+
this._abort = null;
|
|
57
|
+
this._seq = 0;
|
|
58
|
+
this._fmts = [];
|
|
59
|
+
this._view = 'table';
|
|
60
|
+
this._rules = null;
|
|
61
|
+
this._pendingState = options.state || null;
|
|
62
|
+
this._build();
|
|
63
|
+
if (this.opts.view === 'chart') this.setView('chart', this.opts.chart);
|
|
64
|
+
if (this.dataset) this.refresh();
|
|
65
|
+
else this._message(this.opts.emptyText);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ------------------------------------------------------------------ DOM
|
|
69
|
+
_build() {
|
|
70
|
+
const root = (this.root = document.createElement('div'));
|
|
71
|
+
root.className = 'mp-root';
|
|
72
|
+
root.setAttribute('data-theme', this.opts.theme);
|
|
73
|
+
root.innerHTML = `
|
|
74
|
+
<div class="mp-prog"><i></i></div>
|
|
75
|
+
<div class="mp-busy"><span class="mp-bt">Calculating…</span><button class="mp-btn" data-act="cancel">Cancel</button></div>
|
|
76
|
+
<div class="mp-msg" style="display:none"></div>
|
|
77
|
+
<div class="mp-scroller" tabindex="0" role="grid" aria-label="Pivot table">
|
|
78
|
+
<div class="mp-sizer"><div class="mp-view">
|
|
79
|
+
<div class="mp-layer mp-corner"></div>
|
|
80
|
+
<div class="mp-layer mp-colhead"></div>
|
|
81
|
+
<div class="mp-layer mp-rowhead"></div>
|
|
82
|
+
<div class="mp-layer mp-body"></div>
|
|
83
|
+
</div></div>
|
|
84
|
+
</div>
|
|
85
|
+
<div class="mp-chartwrap" style="display:none"></div>
|
|
86
|
+
<div class="mp-bar"><span class="mp-stat"></span><span class="mp-sp"></span><span class="mp-act"></span></div>
|
|
87
|
+
<div class="mp-modal" style="display:none"></div>`;
|
|
88
|
+
this.el.appendChild(root);
|
|
89
|
+
const q = (s) => root.querySelector(s);
|
|
90
|
+
this.$ = {
|
|
91
|
+
prog: q('.mp-prog i'), busy: q('.mp-busy'), bt: q('.mp-bt'), msg: q('.mp-msg'), sc: q('.mp-scroller'),
|
|
92
|
+
sizer: q('.mp-sizer'), view: q('.mp-view'), corner: q('.mp-corner'), colhead: q('.mp-colhead'),
|
|
93
|
+
rowhead: q('.mp-rowhead'), body: q('.mp-body'), chartwrap: q('.mp-chartwrap'), bar: q('.mp-bar'), stat: q('.mp-stat'), act: q('.mp-act'), modal: q('.mp-modal'),
|
|
94
|
+
};
|
|
95
|
+
if (!this.opts.statusBar) this.$.bar.style.display = 'none';
|
|
96
|
+
if (this.opts.actions) {
|
|
97
|
+
this.$.act.innerHTML = '<button data-act="expand">Expand all</button> <button data-act="collapse">Collapse all</button> <button data-act="csv">CSV</button> <button data-act="xlsx">Excel</button> <button data-act="pdf">PDF</button>';
|
|
98
|
+
}
|
|
99
|
+
this._onScroll = () => { if (!this._raf) this._raf = requestAnimationFrame(() => { this._raf = 0; this._render(); }); };
|
|
100
|
+
this.$.sc.addEventListener('scroll', this._onScroll, { passive: true });
|
|
101
|
+
this._ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => { this._layout(); this._render(); }) : null;
|
|
102
|
+
if (this._ro) this._ro.observe(this.$.sc);
|
|
103
|
+
root.addEventListener('click', (e) => this._click(e));
|
|
104
|
+
root.addEventListener('dblclick', (e) => this._dblclick(e));
|
|
105
|
+
root.addEventListener('contextmenu', (e) => this._context(e));
|
|
106
|
+
this.$.sc.addEventListener('keydown', (e) => this._key(e));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
destroy() {
|
|
110
|
+
if (this._abort) this._abort.abort();
|
|
111
|
+
if (this._ro) this._ro.disconnect();
|
|
112
|
+
if (this._chart) this._chart.destroy();
|
|
113
|
+
if (this._raf) cancelAnimationFrame(this._raf);
|
|
114
|
+
this.root.remove();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
_message(text, isError) {
|
|
118
|
+
const m = this.$.msg;
|
|
119
|
+
m.style.display = text ? 'flex' : 'none';
|
|
120
|
+
m.textContent = text || '';
|
|
121
|
+
m.classList.toggle('mp-err', !!isError);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ------------------------------------------------------------------ data / compute
|
|
125
|
+
setOptions(o) {
|
|
126
|
+
Object.assign(this.opts, o);
|
|
127
|
+
if (o.theme) this.root.setAttribute('data-theme', o.theme);
|
|
128
|
+
this._rebuildLayout();
|
|
129
|
+
}
|
|
130
|
+
async setData(ds) { this.dataset = ds; this.result = null; return this.refresh(); }
|
|
131
|
+
async setSpec(spec) { this.spec = spec; return this.refresh(); }
|
|
132
|
+
getSpec() { return this.spec; }
|
|
133
|
+
getResult() { return this.result; }
|
|
134
|
+
|
|
135
|
+
/** Recompute the pivot (cancelling any computation in flight). */
|
|
136
|
+
async refresh() {
|
|
137
|
+
if (!this.dataset) return null;
|
|
138
|
+
if (this._abort) this._abort.abort();
|
|
139
|
+
const ac = (this._abort = new AbortController());
|
|
140
|
+
const seq = ++this._seq;
|
|
141
|
+
this.$.busy.classList.add('mp-on');
|
|
142
|
+
this.$.bt.textContent = 'Calculating…';
|
|
143
|
+
this.$.prog.style.width = '0';
|
|
144
|
+
this.emit('compute-start', { spec: this.spec });
|
|
145
|
+
try {
|
|
146
|
+
const res = await this.dataset.compute(this.spec, {
|
|
147
|
+
signal: ac.signal,
|
|
148
|
+
maxCells: this.opts.maxCells,
|
|
149
|
+
onProgress: (p) => {
|
|
150
|
+
if (seq !== this._seq) return;
|
|
151
|
+
this.$.prog.style.width = Math.round(p * 100) + '%';
|
|
152
|
+
this.$.bt.textContent = `Calculating… ${Math.round(p * 100)}%`;
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
if (seq !== this._seq) return null;
|
|
156
|
+
this.setResult(res);
|
|
157
|
+
this.emit('compute-end', res);
|
|
158
|
+
return res;
|
|
159
|
+
} catch (err) {
|
|
160
|
+
if (err && err.name === 'AbortError') { if (seq === this._seq) this.emit('cancel'); return null; }
|
|
161
|
+
if (seq === this._seq) {
|
|
162
|
+
this._message(err.message || String(err), true);
|
|
163
|
+
this.emit('error', err);
|
|
164
|
+
if (!(err instanceof PivotError)) console.error(err);
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
} finally {
|
|
168
|
+
if (seq === this._seq) { this.$.busy.classList.remove('mp-on'); this.$.prog.style.width = '0'; }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
setResult(res) {
|
|
173
|
+
this.result = res;
|
|
174
|
+
this._message('');
|
|
175
|
+
this._fmts = res.values.map((v) => makeFormatter(v.format ?? (v.showAs && v.showAs !== 'value' ? 'percent' : 'number'), this.opts.locale));
|
|
176
|
+
this._compileRules();
|
|
177
|
+
this._applySort();
|
|
178
|
+
this._autoExpand();
|
|
179
|
+
this._applyPending();
|
|
180
|
+
this._rebuildLayout();
|
|
181
|
+
const s = res.stats;
|
|
182
|
+
this.$.stat.textContent = `${s.rows.toLocaleString()} records · ${s.matchedRows.toLocaleString()} matched · ${s.cells.toLocaleString()} cells · ${(s.ms / 1000).toFixed(2)}s`;
|
|
183
|
+
this.$.sc.scrollTop = 0; this.$.sc.scrollLeft = 0;
|
|
184
|
+
this._render();
|
|
185
|
+
if (this._view === 'chart') this._chartUpdate();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ------------------------------------------------------------------ expand / collapse
|
|
189
|
+
_autoExpand() {
|
|
190
|
+
const r = this.result;
|
|
191
|
+
const lvl = (opt, nodes, limit) => (opt === 'auto' ? (nodes.length <= limit ? Infinity : 1) : opt === true ? Infinity : opt === false ? 0 : Number(opt));
|
|
192
|
+
const o = r.spec.options || {};
|
|
193
|
+
this._expRows = lvl(o.expandRows ?? this.opts.expandRows, r.rowAxis.nodes, 20000);
|
|
194
|
+
this._expCols = lvl(o.expandCols ?? this.opts.expandCols, r.colAxis.nodes, 300);
|
|
195
|
+
this.rowOpen.clear(); this.colOpen.clear();
|
|
196
|
+
}
|
|
197
|
+
_isOpen(node, map, def) {
|
|
198
|
+
if (!node.children.length) return false;
|
|
199
|
+
if (map.size) { const v = map.get(node.key); if (v !== undefined) return v; }
|
|
200
|
+
return node.level < def;
|
|
201
|
+
}
|
|
202
|
+
expandToLevel(n, axis) {
|
|
203
|
+
if (!this.result) return;
|
|
204
|
+
if (!axis || axis === 'rows') { this._expRows = n; this.rowOpen.clear(); }
|
|
205
|
+
if (!axis || axis === 'cols') { this._expCols = n; this.colOpen.clear(); }
|
|
206
|
+
this._rebuildLayout(); this._render();
|
|
207
|
+
}
|
|
208
|
+
expandAll(axis) { this.expandToLevel(Infinity, axis); }
|
|
209
|
+
collapseAll(axis) { this.expandToLevel(0, axis); }
|
|
210
|
+
toggleRow(node) { this.rowOpen.set(node.key, !this._isOpen(node, this.rowOpen, this._expRows)); this._rebuildLayout(); this._render(); this.emit('toggle', { axis: 'rows', node }); }
|
|
211
|
+
toggleCol(node) { this.colOpen.set(node.key, !this._isOpen(node, this.colOpen, this._expCols)); this._rebuildLayout(); this._render(); this.emit('toggle', { axis: 'cols', node }); }
|
|
212
|
+
|
|
213
|
+
// ------------------------------------------------------------------ sorting
|
|
214
|
+
sortByColumn(colIndex, dir) {
|
|
215
|
+
const e = this._entries[Math.floor(colIndex / this._nv)];
|
|
216
|
+
const j = colIndex % this._nv;
|
|
217
|
+
const cur = this.sortState;
|
|
218
|
+
const same = cur && cur.key === e.node.key && cur.kind === e.kind && cur.j === j;
|
|
219
|
+
if (dir === undefined) dir = same ? (cur.dir === 'desc' ? 'asc' : null) : 'desc';
|
|
220
|
+
if (!dir) { this.sortState = null; this.result.resetSort('rows'); }
|
|
221
|
+
else { this.sortState = { key: e.node.key, kind: e.kind, j, dir }; this.result.sortBy('rows', e.node, j, dir); }
|
|
222
|
+
this._rebuildLayout(); this._render();
|
|
223
|
+
if (this._view === 'chart') this._chartUpdate();
|
|
224
|
+
this.emit('sort', this.sortState);
|
|
225
|
+
}
|
|
226
|
+
_applySort() {
|
|
227
|
+
const s = this.sortState, r = this.result;
|
|
228
|
+
if (!s) return;
|
|
229
|
+
let node = null;
|
|
230
|
+
if (s.kind === 'grand' || s.kind === 'only') node = r.colRoot;
|
|
231
|
+
else node = r.colAxis.nodes.find((n) => n.level >= 0 && n.key === s.key) || null;
|
|
232
|
+
if (node) r.sortBy('rows', node, Math.min(s.j, r.values.length - 1), s.dir); else this.sortState = null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ------------------------------------------------------------------ layout model
|
|
236
|
+
_rebuildLayout() {
|
|
237
|
+
const r = this.result;
|
|
238
|
+
if (!r) return;
|
|
239
|
+
const o = this.opts, nv = (this._nv = r.values.length);
|
|
240
|
+
const D = r.rowDims.length, C = r.colDims.length;
|
|
241
|
+
const optsSpec = r.spec.options || {};
|
|
242
|
+
const grand = optsSpec.grandTotals ?? o.grandTotals;
|
|
243
|
+
const subtotals = optsSpec.colSubtotals ?? o.colSubtotals;
|
|
244
|
+
|
|
245
|
+
// rows (pre-order; parents show their own subtotal values)
|
|
246
|
+
const rows = [];
|
|
247
|
+
const walk = (n) => { rows.push(n); if (this._isOpen(n, this.rowOpen, this._expRows)) for (const c of n.children) walk(c); };
|
|
248
|
+
for (const c of r.rowRoot.children) walk(c);
|
|
249
|
+
this._rows = rows;
|
|
250
|
+
this._hasGrandRow = D === 0 || grand;
|
|
251
|
+
this._nRows = rows.length + (this._hasGrandRow ? 1 : 0);
|
|
252
|
+
|
|
253
|
+
// columns
|
|
254
|
+
const entries = [], headers = [];
|
|
255
|
+
const visit = (n, level) => {
|
|
256
|
+
const open = this._isOpen(n, this.colOpen, this._expCols);
|
|
257
|
+
const col0 = entries.length * nv;
|
|
258
|
+
if (!open) {
|
|
259
|
+
entries.push({ node: n, kind: 'leaf' });
|
|
260
|
+
headers.push({ level, label: n.label, col0, span: nv, levelSpan: C - level, node: n, toggle: n.children.length > 0, open: false });
|
|
261
|
+
} else {
|
|
262
|
+
for (const ch of n.children) visit(ch, level + 1);
|
|
263
|
+
if (subtotals) {
|
|
264
|
+
entries.push({ node: n, kind: 'sub' });
|
|
265
|
+
headers.push({ level: level + 1, label: 'Total', col0: (entries.length - 1) * nv, span: nv, levelSpan: C - level - 1, sub: true });
|
|
266
|
+
}
|
|
267
|
+
headers.push({ level, label: n.label, col0, span: entries.length * nv - col0, levelSpan: 1, node: n, toggle: true, open: true });
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
if (C === 0) entries.push({ node: r.colRoot, kind: 'only' });
|
|
271
|
+
else {
|
|
272
|
+
for (const c of r.colRoot.children) visit(c, 0);
|
|
273
|
+
if (grand) {
|
|
274
|
+
entries.push({ node: r.colRoot, kind: 'grand' });
|
|
275
|
+
headers.push({ level: 0, label: 'Grand Total', col0: (entries.length - 1) * nv, span: nv, levelSpan: C, grand: true });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
this._entries = entries;
|
|
279
|
+
this._headers = headers;
|
|
280
|
+
this._valLevel = nv > 1 || C === 0;
|
|
281
|
+
this._hdrLevels = Math.max(1, C + (this._valLevel ? 1 : 0));
|
|
282
|
+
this._nCols = entries.length * nv;
|
|
283
|
+
this._layout();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
_layout() {
|
|
287
|
+
const r = this.result;
|
|
288
|
+
if (!r) return;
|
|
289
|
+
const o = this.opts, sc = this.$.sc;
|
|
290
|
+
const cw = sc.clientWidth, ch = sc.clientHeight;
|
|
291
|
+
this._cw = cw; this._ch = ch;
|
|
292
|
+
this._hdrH = (this._hdrLevels + (o.headerExtraRows || 0)) * o.rowHeight;
|
|
293
|
+
const bodyW = this._nCols * o.colWidth, bodyH = this._nRows * o.rowHeight;
|
|
294
|
+
const vw = Math.max(0, cw - o.rowHeaderWidth), vh = Math.max(0, ch - this._hdrH);
|
|
295
|
+
const maxX = Math.max(0, bodyW - vw), maxY = Math.max(0, bodyH - vh);
|
|
296
|
+
this._sx = Math.max(1, maxX / MAX_PX);
|
|
297
|
+
this._sy = Math.max(1, maxY / MAX_PX);
|
|
298
|
+
this.$.sizer.style.width = cw + maxX / this._sx + 'px';
|
|
299
|
+
this.$.sizer.style.height = ch + maxY / this._sy + 'px';
|
|
300
|
+
Object.assign(this.$.view.style, { width: cw + 'px', height: ch + 'px' });
|
|
301
|
+
const set = (el, l, t, w, h) => Object.assign(el.style, { left: l + 'px', top: t + 'px', width: Math.max(0, w) + 'px', height: Math.max(0, h) + 'px' });
|
|
302
|
+
set(this.$.corner, 0, 0, o.rowHeaderWidth, this._hdrH);
|
|
303
|
+
set(this.$.colhead, o.rowHeaderWidth, 0, vw, this._hdrH);
|
|
304
|
+
set(this.$.rowhead, 0, this._hdrH, o.rowHeaderWidth, vh);
|
|
305
|
+
set(this.$.body, o.rowHeaderWidth, this._hdrH, vw, vh);
|
|
306
|
+
this._vw = vw; this._vh = vh;
|
|
307
|
+
this._hasData = this._nRows > 0 && this._nCols > 0;
|
|
308
|
+
this.emit('layout', { headerLevels: this._hdrLevels, headerHeight: this._hdrH, rowHeaderWidth: o.rowHeaderWidth, rowHeight: o.rowHeight });
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ------------------------------------------------------------------ rendering
|
|
312
|
+
_render() {
|
|
313
|
+
const r = this.result;
|
|
314
|
+
if (!r || !this._entries) return;
|
|
315
|
+
const o = this.opts, rh = o.rowHeight, cwid = o.colWidth, nv = this._nv;
|
|
316
|
+
const sc = this.$.sc;
|
|
317
|
+
const sx = sc.scrollLeft * this._sx, sy = sc.scrollTop * this._sy;
|
|
318
|
+
const r0 = Math.max(0, Math.floor(sy / rh)), r1 = Math.min(this._nRows, Math.ceil((sy + this._vh) / rh));
|
|
319
|
+
const c0 = Math.max(0, Math.floor(sx / cwid)), c1 = Math.min(this._nCols, Math.ceil((sx + this._vw) / cwid));
|
|
320
|
+
const entries = this._entries, rows = this._rows;
|
|
321
|
+
const grandRowIdx = rows.length;
|
|
322
|
+
const rules = this._rules;
|
|
323
|
+
|
|
324
|
+
// body cells
|
|
325
|
+
const cells = [];
|
|
326
|
+
const sel = this.selected;
|
|
327
|
+
for (let ri = r0; ri < r1; ri++) {
|
|
328
|
+
const isGrand = ri === grandRowIdx;
|
|
329
|
+
const rn = isGrand ? r.rowRoot : rows[ri];
|
|
330
|
+
const top = ri * rh - sy;
|
|
331
|
+
const rowSub = !isGrand && rn.children.length > 0;
|
|
332
|
+
for (let c = c0; c < c1; c++) {
|
|
333
|
+
const e = entries[(c / nv) | 0], j = c % nv;
|
|
334
|
+
const v = r.get(rn, e.node, j);
|
|
335
|
+
let cls = 'mp-c';
|
|
336
|
+
if (isGrand || e.kind === 'grand') cls += ' mp-gt'; else if (rowSub || e.kind === 'sub') cls += ' mp-sub';
|
|
337
|
+
if (v === null) cls += ' mp-null';
|
|
338
|
+
if (sel && sel.r === ri && sel.c === c) cls += ' mp-sel';
|
|
339
|
+
const m = rules ? rules(rn, e.node, j, v) : null;
|
|
340
|
+
let text = v === null ? '' : this._fmts[j](v), extra = '';
|
|
341
|
+
if (m) {
|
|
342
|
+
if (m.text !== undefined) text = m.text; else if (v !== null && m.fmtFn) text = m.fmtFn(v);
|
|
343
|
+
if (m.style) { extra = styleCss(m.style); if (m.style.align) extra += 'justify-content:' + (m.style.align === 'left' ? 'flex-start' : m.style.align === 'center' ? 'center' : 'flex-end') + ';'; if (m.style.background) cls += ' mp-fill'; }
|
|
344
|
+
}
|
|
345
|
+
cells.push(`<div class="${cls}" data-r="${ri}" data-c="${c}" style="left:${c * cwid - sx}px;top:${top}px;width:${cwid}px;height:${rh}px;${extra}">${esc(text)}</div>`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
this.$.body.innerHTML = cells.join('');
|
|
349
|
+
|
|
350
|
+
// row headers
|
|
351
|
+
const rhs = [];
|
|
352
|
+
const rw = o.rowHeaderWidth;
|
|
353
|
+
for (let ri = r0; ri < r1; ri++) {
|
|
354
|
+
const top = ri * rh - sy;
|
|
355
|
+
if (ri === grandRowIdx) {
|
|
356
|
+
rhs.push(`<div class="mp-rh mp-gt" style="top:${top}px;left:0;width:${rw}px;height:${rh}px"><span class="mp-tg mp-nt"></span><span class="mp-lb">${r.rowDims.length ? 'Grand Total' : 'Total'}</span></div>`);
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const n = rows[ri];
|
|
360
|
+
const has = n.children.length > 0;
|
|
361
|
+
const open = has && this._isOpen(n, this.rowOpen, this._expRows);
|
|
362
|
+
rhs.push(`<div class="mp-rh${has ? ' mp-sub' : ''}" data-r="${ri}" style="top:${top}px;left:0;width:${rw}px;height:${rh}px;padding-left:${8 + n.level * 16}px" title="${esc(n.path().join(' › '))}"><span class="mp-tg${has ? '' : ' mp-nt'}" data-act="tr" data-r="${ri}">${open ? '▾' : '▸'}</span><span class="mp-lb">${esc(n.label)}</span></div>`);
|
|
363
|
+
}
|
|
364
|
+
this.$.rowhead.innerHTML = rhs.join('');
|
|
365
|
+
|
|
366
|
+
// column headers
|
|
367
|
+
const chs = [];
|
|
368
|
+
const C = r.colDims.length;
|
|
369
|
+
const ss = this.sortState;
|
|
370
|
+
const sortMark = (e, j) => (ss && ss.key === e.node.key && ss.kind === e.kind && ss.j === j ? `<span class="mp-si">${ss.dir === 'desc' ? '▼' : '▲'}</span>` : '');
|
|
371
|
+
const hs = this._headers;
|
|
372
|
+
for (let i = 0; i < hs.length; i++) {
|
|
373
|
+
const h = hs[i];
|
|
374
|
+
if (h.col0 >= c1 || h.col0 + h.span <= c0) continue;
|
|
375
|
+
const bottom = h.level + h.levelSpan >= C;
|
|
376
|
+
const sortable = bottom && !this._valLevel;
|
|
377
|
+
const e = sortable ? entries[(h.col0 / nv) | 0] : null;
|
|
378
|
+
chs.push(`<div class="mp-ch${h.grand ? ' mp-gt' : ''}${sortable ? ' mp-sortable' : ''}" ${sortable ? `data-act="sort" data-c="${h.col0}"` : ''} style="left:${h.col0 * cwid - sx}px;top:${h.level * rh}px;width:${h.span * cwid}px;height:${h.levelSpan * rh}px" title="${esc(h.label)}">${h.toggle ? `<span class="mp-tg" data-act="tc" data-h="${i}">${h.open ? '▾' : '▸'}</span>` : ''}<span class="mp-lb">${esc(h.label)}</span>${e ? sortMark(e, 0) : ''}</div>`);
|
|
379
|
+
}
|
|
380
|
+
if (this._valLevel) {
|
|
381
|
+
for (let c = c0; c < c1; c++) {
|
|
382
|
+
const e = entries[(c / nv) | 0], j = c % nv;
|
|
383
|
+
chs.push(`<div class="mp-ch mp-sortable${e.kind === 'grand' ? ' mp-gt' : ''}" data-act="sort" data-c="${c}" style="left:${c * cwid - sx}px;top:${C * rh}px;width:${cwid}px;height:${rh}px" title="${esc(r.values[j].label)}"><span class="mp-lb">${esc(r.values[j].label)}</span>${sortMark(e, j)}</div>`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
this.$.colhead.innerHTML = chs.join('');
|
|
387
|
+
|
|
388
|
+
// corner
|
|
389
|
+
const dl = r.rowDims.map((d) => esc(d.label)).join(' › ');
|
|
390
|
+
this.$.corner.innerHTML = this.opts.cornerLabels === false ? '' : `<span style="overflow:hidden;text-overflow:ellipsis">${dl || 'Total'}${!this._valLevel ? ` <span style="font-weight:400">· ${esc(r.values[0].label)}</span>` : ''}</span>`;
|
|
391
|
+
if (!this._hasData && !r.stats.matchedRows) this._message('No records match the current filters');
|
|
392
|
+
else if (this.$.msg.style.display !== 'none' && !this.$.msg.classList.contains('mp-err')) this._message('');
|
|
393
|
+
this.emit('render', { r0, r1, c0, c1 });
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ------------------------------------------------------------------ interaction
|
|
397
|
+
_click(e) {
|
|
398
|
+
const t = e.target.closest('[data-act]') || null;
|
|
399
|
+
if (t) {
|
|
400
|
+
const act = t.dataset.act;
|
|
401
|
+
if (act === 'tr') { e.stopPropagation(); this.toggleRow(this._rows[+t.dataset.r]); return; }
|
|
402
|
+
if (act === 'tc') { e.stopPropagation(); this.toggleCol(this._headers[+t.dataset.h].node); return; }
|
|
403
|
+
if (act === 'sort') { this.sortByColumn(+t.dataset.c); return; }
|
|
404
|
+
if (act === 'expand') return this.expandAll();
|
|
405
|
+
if (act === 'collapse') return this.collapseAll();
|
|
406
|
+
if (act === 'csv') return this.downloadCSV();
|
|
407
|
+
if (act === 'xlsx') return this.downloadXLSX();
|
|
408
|
+
if (act === 'pdf') return this.downloadPDF();
|
|
409
|
+
if (act === 'cancel') { if (this._abort) this._abort.abort(); return; }
|
|
410
|
+
if (act === 'close') { this.$.modal.style.display = 'none'; return; }
|
|
411
|
+
}
|
|
412
|
+
const cell = e.target.closest('.mp-c');
|
|
413
|
+
if (cell) {
|
|
414
|
+
this.selected = { r: +cell.dataset.r, c: +cell.dataset.c };
|
|
415
|
+
this._render();
|
|
416
|
+
this.emit('cellclick', this._cellInfo(this.selected.r, this.selected.c));
|
|
417
|
+
} else {
|
|
418
|
+
const rhEl = e.target.closest('.mp-rh[data-r]');
|
|
419
|
+
if (rhEl) this.emit('rowclick', { node: this._rows[+rhEl.dataset.r] });
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
_context(e) {
|
|
423
|
+
const cell = e.target.closest('.mp-c');
|
|
424
|
+
if (!cell || !this.result) return;
|
|
425
|
+
const ri = +cell.dataset.r, c = +cell.dataset.c;
|
|
426
|
+
this.selected = { r: ri, c };
|
|
427
|
+
this._render();
|
|
428
|
+
const info = this._cellInfo(ri, c);
|
|
429
|
+
// listeners may call preventDefault() on the DOM event to replace the browser menu
|
|
430
|
+
this.emit('cellcontext', { ...info, event: e, clientX: e.clientX, clientY: e.clientY });
|
|
431
|
+
}
|
|
432
|
+
_dblclick(e) {
|
|
433
|
+
const cell = e.target.closest('.mp-c');
|
|
434
|
+
if (cell && this.opts.drill) this.drill(+cell.dataset.r, +cell.dataset.c);
|
|
435
|
+
}
|
|
436
|
+
_key(e) {
|
|
437
|
+
if (!this.selected) return;
|
|
438
|
+
const d = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }[e.key];
|
|
439
|
+
if (!d) { if (e.key === 'Enter') this.drill(this.selected.r, this.selected.c); return; }
|
|
440
|
+
e.preventDefault();
|
|
441
|
+
const s = this.selected;
|
|
442
|
+
const r = Math.min(this._nRows - 1, Math.max(0, s.r + d[0])), c = Math.min(this._nCols - 1, Math.max(0, s.c + d[1]));
|
|
443
|
+
this.selected = { r, c };
|
|
444
|
+
const o = this.opts, sc = this.$.sc;
|
|
445
|
+
const top = r * o.rowHeight / this._sy, left = c * o.colWidth / this._sx;
|
|
446
|
+
if (top < sc.scrollTop) sc.scrollTop = top;
|
|
447
|
+
else if (top + o.rowHeight / this._sy > sc.scrollTop + this._vh / this._sy) sc.scrollTop = top + (o.rowHeight - this._vh) / this._sy;
|
|
448
|
+
if (left < sc.scrollLeft) sc.scrollLeft = left;
|
|
449
|
+
else if (left + o.colWidth / this._sx > sc.scrollLeft + this._vw / this._sx) sc.scrollLeft = left + (o.colWidth - this._vw) / this._sx;
|
|
450
|
+
this._render();
|
|
451
|
+
this.emit('cellclick', this._cellInfo(r, c));
|
|
452
|
+
}
|
|
453
|
+
_cellInfo(ri, c) {
|
|
454
|
+
const r = this.result, nv = this._nv;
|
|
455
|
+
const rowNode = ri === this._rows.length ? r.rowRoot : this._rows[ri];
|
|
456
|
+
const e = this._entries[(c / nv) | 0], j = c % nv;
|
|
457
|
+
return { rowNode, colNode: e.node, valueIndex: j, value: r.get(rowNode, e.node, j), row: rowNode.path(), col: e.node.path(), measure: r.values[j] };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Show the raw records behind a cell. */
|
|
461
|
+
async drill(ri, c) {
|
|
462
|
+
const info = this._cellInfo(ri, c);
|
|
463
|
+
const modal = this.$.modal;
|
|
464
|
+
const title = [...info.row, ...info.col].join(' › ') || 'All records';
|
|
465
|
+
modal.style.display = 'flex';
|
|
466
|
+
modal.innerHTML = `<div class="mp-dlg"><h4><span>${esc(title)}</span><button class="mp-btn" data-act="close">Close</button></h4><div class="mp-body"><div style="padding:16px;color:var(--mp-muted)">Loading…</div></div></div>`;
|
|
467
|
+
try {
|
|
468
|
+
const d = await this.dataset.drill(this.result, info.rowNode, info.colNode, { limit: this.opts.drillLimit });
|
|
469
|
+
const fi = this.dataset.fieldInfo().filter((f) => f.role !== 'skip');
|
|
470
|
+
const names = fi.length ? fi : Object.keys(d.rows[0] || {}).filter((k) => k !== '__row').map((name) => ({ name, label: name }));
|
|
471
|
+
const th = names.map((f) => `<th>${esc(f.label)}</th>`).join('');
|
|
472
|
+
const nf = makeFormatter('number', this.opts.locale);
|
|
473
|
+
const fmt = (f, v) => (v == null ? '' : v instanceof Date ? v.toISOString().slice(0, 10) : typeof v === 'number' && f.isMeasure && !f.isDimension ? nf(v) : typeof v === 'string' && f.type === 'date' ? v.slice(0, 10) : String(v));
|
|
474
|
+
const tr = d.rows.map((row) => `<tr>${names.map((f) => `<td class="${typeof row[f.name] === 'number' ? 'mp-n' : ''}">${esc(fmt(f, row[f.name]))}</td>`).join('')}</tr>`).join('');
|
|
475
|
+
modal.querySelector('h4 span').textContent = `${title} — ${d.total.toLocaleString()} record${d.total === 1 ? '' : 's'}${d.total > d.rows.length ? ` (first ${d.rows.length})` : ''}`;
|
|
476
|
+
modal.querySelector('.mp-body').innerHTML = `<table><thead><tr>${th}</tr></thead><tbody>${tr}</tbody></table>`;
|
|
477
|
+
this.emit('drill', { ...info, ...d });
|
|
478
|
+
} catch (err) {
|
|
479
|
+
modal.querySelector('.mp-body').textContent = err.message;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// ------------------------------------------------------------------ chart view
|
|
484
|
+
getView() { return this._view; }
|
|
485
|
+
/** Switch between the pivot grid and a chart of the same result. chartOpts: see PivotChart (type, valueIndex, rowLevel, colLevel ...) */
|
|
486
|
+
setView(view, chartOpts) {
|
|
487
|
+
this._view = view === 'chart' ? 'chart' : 'table';
|
|
488
|
+
const chart = this._view === 'chart';
|
|
489
|
+
this.$.sc.style.display = chart ? 'none' : '';
|
|
490
|
+
this.$.chartwrap.style.display = chart ? 'block' : 'none';
|
|
491
|
+
if (chart) {
|
|
492
|
+
this.$.chartwrap.style.cssText = 'flex:1 1 auto;min-height:0;position:relative;display:block';
|
|
493
|
+
if (chartOpts) this.opts.chart = { ...this.opts.chart, ...chartOpts };
|
|
494
|
+
if (!this._chart) {
|
|
495
|
+
this._chart = new PivotChart(this.$.chartwrap, { ...this.opts.chart });
|
|
496
|
+
this._chart.on('pointclick', (e) => this.emit('chartclick', e));
|
|
497
|
+
}
|
|
498
|
+
this._chartUpdate();
|
|
499
|
+
} else this._render();
|
|
500
|
+
this.emit('view', this._view);
|
|
501
|
+
}
|
|
502
|
+
_chartUpdate() {
|
|
503
|
+
if (!this._chart) return;
|
|
504
|
+
this._chart.setOptions({ ...this.opts.chart });
|
|
505
|
+
if (this.result) this._chart.setResult(this.result);
|
|
506
|
+
}
|
|
507
|
+
setChartOptions(o) { this.opts.chart = { ...this.opts.chart, ...o }; if (this._view === 'chart') this._chartUpdate(); }
|
|
508
|
+
downloadChartSVG(filename = 'chart.svg') {
|
|
509
|
+
if (!this._chart) return;
|
|
510
|
+
downloadBlob(new TextEncoder().encode(this._chart.toSVG()), filename, 'image/svg+xml');
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ------------------------------------------------------------------ cell formatting rules
|
|
514
|
+
_compileRules() {
|
|
515
|
+
const r = this.result;
|
|
516
|
+
this._rules = null;
|
|
517
|
+
if (!r) return;
|
|
518
|
+
try { this._rules = compileCellRules(this.getCellRules(), r, { locale: this.opts.locale }); }
|
|
519
|
+
catch (err) { this.emit('error', err); }
|
|
520
|
+
}
|
|
521
|
+
/** Per-cell format rules (see `cleanRules` for the shape). They are part of the spec, so layouts and reports keep them. */
|
|
522
|
+
getCellRules() { return (this.spec.options && this.spec.options.cellRules) || this.opts.cellRules || []; }
|
|
523
|
+
setCellRules(rules) {
|
|
524
|
+
const clean = cleanRules(rules);
|
|
525
|
+
this.spec = { ...this.spec, options: { ...this.spec.options, cellRules: clean } };
|
|
526
|
+
if (!clean.length) delete this.spec.options.cellRules;
|
|
527
|
+
this._compileRules();
|
|
528
|
+
if (this.result) { this._render(); }
|
|
529
|
+
this.emit('rules', clean);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// ------------------------------------------------------------------ view state (saved with reports)
|
|
533
|
+
/** Expansion, sort, sizing: everything the user can change by interacting that is not in the spec. */
|
|
534
|
+
getState() {
|
|
535
|
+
const open = (m) => [...m.entries()];
|
|
536
|
+
const lv = (x) => (x === Infinity ? 'all' : x);
|
|
537
|
+
return {
|
|
538
|
+
expRows: lv(this._expRows), expCols: lv(this._expCols),
|
|
539
|
+
rowOpen: open(this.rowOpen), colOpen: open(this.colOpen),
|
|
540
|
+
sort: this.sortState ? { ...this.sortState } : null,
|
|
541
|
+
colWidth: this.opts.colWidth, rowHeight: this.opts.rowHeight, rowHeaderWidth: this.opts.rowHeaderWidth,
|
|
542
|
+
view: this._view,
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
setState(state) {
|
|
546
|
+
this._pendingState = state || null;
|
|
547
|
+
if (this.result) { this._applyPending(); this._rebuildLayout(); this._render(); if (this._view === 'chart') this._chartUpdate(); }
|
|
548
|
+
}
|
|
549
|
+
_applyPending() {
|
|
550
|
+
const st = this._pendingState;
|
|
551
|
+
if (!st) return;
|
|
552
|
+
this._pendingState = null;
|
|
553
|
+
const num = (x) => (x === 'all' ? Infinity : typeof x === 'number' ? x : undefined);
|
|
554
|
+
if (st.expRows !== undefined && num(st.expRows) !== undefined) this._expRows = num(st.expRows);
|
|
555
|
+
if (st.expCols !== undefined && num(st.expCols) !== undefined) this._expCols = num(st.expCols);
|
|
556
|
+
this.rowOpen = new Map(Array.isArray(st.rowOpen) ? st.rowOpen : []);
|
|
557
|
+
this.colOpen = new Map(Array.isArray(st.colOpen) ? st.colOpen : []);
|
|
558
|
+
for (const k of ['colWidth', 'rowHeight', 'rowHeaderWidth']) if (Number.isFinite(st[k])) this.opts[k] = st[k];
|
|
559
|
+
if (st.sort && Number.isFinite(st.sort.j)) { this.sortState = { ...st.sort }; this._applySort(); }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// ------------------------------------------------------------------ print
|
|
563
|
+
/**
|
|
564
|
+
* Print the pivot (and the chart when it is showing) through the browser print dialog.
|
|
565
|
+
* Options default to `spec.options.print`: { title, subtitle, footer, pageSize: 'a4'|'letter'|'a3'|'legal', orientation, subtotals, maxRows }.
|
|
566
|
+
* Per-cell format rules are applied. Returns the HTML used (handy for tests / custom previews).
|
|
567
|
+
*/
|
|
568
|
+
print(opts = {}) {
|
|
569
|
+
if (!this.result) throw new PivotError('Nothing to print yet');
|
|
570
|
+
const html = this.toPrintHTML(opts);
|
|
571
|
+
const f = document.createElement('iframe');
|
|
572
|
+
f.setAttribute('aria-hidden', 'true');
|
|
573
|
+
f.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden';
|
|
574
|
+
document.body.appendChild(f);
|
|
575
|
+
const doc = f.contentWindow.document;
|
|
576
|
+
doc.open(); doc.write(html); doc.close();
|
|
577
|
+
const done = () => setTimeout(() => f.remove(), 500);
|
|
578
|
+
f.contentWindow.addEventListener('afterprint', done);
|
|
579
|
+
setTimeout(() => { try { f.contentWindow.focus(); f.contentWindow.print(); } finally { setTimeout(() => f.isConnected && f.remove(), 60000); } }, 150);
|
|
580
|
+
return html;
|
|
581
|
+
}
|
|
582
|
+
toPrintHTML(opts = {}) {
|
|
583
|
+
if (!this.result) throw new PivotError('Nothing to print yet');
|
|
584
|
+
const p = { ...(this.spec.options && this.spec.options.print), ...opts };
|
|
585
|
+
const chartSVG = this._view === 'chart' && this._chart ? this._chart.toSVG() : undefined;
|
|
586
|
+
return toPrintHTML(this.result, { subtotals: true, ...p, rules: this._rules, locale: this.opts.locale, chartSVG });
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// ------------------------------------------------------------------ export
|
|
590
|
+
exportXLSX(opts) { return toXLSX(this.result, { rules: this._rules, locale: this.opts.locale, ...opts }); }
|
|
591
|
+
exportPDF(opts) {
|
|
592
|
+
const p = (this.spec.options && this.spec.options.print) || {};
|
|
593
|
+
return toPDF(this.result, { locale: this.opts.locale, rules: this._rules, title: p.title, subtitle: p.subtitle, footer: p.footer, pageSize: p.pageSize, orientation: p.orientation, font: p.font, fonts: this.opts.pdfFonts, ...opts });
|
|
594
|
+
}
|
|
595
|
+
downloadXLSX(filename = 'pivot.xlsx', opts) { downloadBlob(this.exportXLSX(opts), filename, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); }
|
|
596
|
+
downloadPDF(filename = 'pivot.pdf', opts) { downloadBlob(this.exportPDF(opts), filename, 'application/pdf'); }
|
|
597
|
+
/**
|
|
598
|
+
* The current pivot as a portable report document (spec + frozen snapshot of the numbers).
|
|
599
|
+
* @param {{title?:string, description?:string, author?:string, source?:object, snapshot?:boolean}} [meta]
|
|
600
|
+
*/
|
|
601
|
+
toReport(meta = {}) {
|
|
602
|
+
if (!this.result) throw new PivotError('Nothing to save yet');
|
|
603
|
+
const spec = JSON.parse(JSON.stringify(this.spec));
|
|
604
|
+
spec.options = { ...spec.options, view: this._view, chart: { ...this.opts.chart } };
|
|
605
|
+
const info = this.dataset && this.dataset.fieldInfo ? this.dataset.fieldInfo() : [];
|
|
606
|
+
const fields = info.filter((f) => f.formula).map((f) => ({ name: f.name, label: f.label, formula: f.formula }));
|
|
607
|
+
const schema = info.map((f) => ({ name: f.name, label: f.label, type: f.type, role: f.role }));
|
|
608
|
+
return createReport({ ...meta, spec, result: this.result, fields, schema, state: this.getState(), locale: this.opts.locale || (typeof navigator !== 'undefined' ? navigator.language : undefined) });
|
|
609
|
+
}
|
|
610
|
+
/** Download the report as JSON (render it later with renderReport) or as a self-contained .html file. */
|
|
611
|
+
async downloadReport(filename, meta = {}, { html = false, bundleUrl } = {}) {
|
|
612
|
+
const report = this.toReport(meta);
|
|
613
|
+
const base = (meta.title || 'pivot-report').replace(/[^\w\- ]+/g, '').trim().replace(/\s+/g, '-') || 'pivot-report';
|
|
614
|
+
if (!html) return downloadBlob(JSON.stringify(report), filename || base + '.report.json', 'application/json');
|
|
615
|
+
const url = bundleUrl || (document.querySelector('script[src*="pivotjet"]') || {}).src;
|
|
616
|
+
if (!url) throw new PivotError('HTML export needs the browser bundle: load pivotjet.min.js with a <script> tag or pass bundleUrl.');
|
|
617
|
+
const res = await fetch(url);
|
|
618
|
+
if (!res.ok) throw new PivotError(`Could not load the bundle (${res.status})`);
|
|
619
|
+
downloadBlob(reportToHTML(report, { bundle: await res.text(), theme: this.opts.theme }), filename || base + '.html', 'text/html');
|
|
620
|
+
}
|
|
621
|
+
exportCSV(opts) { return this.result ? this.result.toCSV(opts) : ''; }
|
|
622
|
+
downloadCSV(filename = 'pivot.csv', opts) {
|
|
623
|
+
const lines = Array.from(this.result.csvLines(opts));
|
|
624
|
+
const blob = new Blob(['' + lines.join('\r\n')], { type: 'text/csv;charset=utf-8' });
|
|
625
|
+
const a = document.createElement('a');
|
|
626
|
+
a.href = URL.createObjectURL(blob);
|
|
627
|
+
a.download = filename;
|
|
628
|
+
document.body.appendChild(a);
|
|
629
|
+
a.click();
|
|
630
|
+
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 0);
|
|
631
|
+
}
|
|
632
|
+
}
|