@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/designer.js
ADDED
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
// PivotDesigner: drag & drop field list + zones + live PivotViewer. Framework-agnostic.
|
|
2
|
+
|
|
3
|
+
import { PivotViewer } from './viewer.js';
|
|
4
|
+
import { Emitter, esc, clone } from './util.js';
|
|
5
|
+
import { injectStyles } from './styles.js';
|
|
6
|
+
import { AGGREGATES, DATE_BUCKETS } from './engine.js';
|
|
7
|
+
import { CHART_TYPES } from './chart.js';
|
|
8
|
+
import { LayoutStore, LocalStorageAdapter } from './layouts.js';
|
|
9
|
+
import { cleanRules } from './cellfmt.js';
|
|
10
|
+
import { parseReport, applyReportFields } from './report.js';
|
|
11
|
+
import { downloadBlob } from './export.js';
|
|
12
|
+
|
|
13
|
+
const AGG_LABEL = { sum: 'Sum', count: 'Count', avg: 'Average', min: 'Min', max: 'Max', distinct: 'Distinct count', median: 'Median' };
|
|
14
|
+
const CHART_LABEL = { column: 'Column', bar: 'Bar', stackedColumn: 'Stacked column', stackedBar: 'Stacked bar', line: 'Line', area: 'Area', stackedArea: 'Stacked area', pie: 'Pie', donut: 'Donut' };
|
|
15
|
+
const SHOW_AS = { value: 'Value', pctRow: '% of row total', pctCol: '% of column total', pctGrand: '% of grand total' };
|
|
16
|
+
const FORMATS = ['number', 'integer', 'currency', 'percent', 'compact'];
|
|
17
|
+
const ZONES = [
|
|
18
|
+
{ id: 'filters', title: 'Filters', hint: 'Drop fields to filter' },
|
|
19
|
+
{ id: 'cols', title: 'Columns', hint: 'Drop fields for columns' },
|
|
20
|
+
{ id: 'rows', title: 'Rows', hint: 'Drop fields for rows' },
|
|
21
|
+
{ id: 'values', title: 'Values', hint: 'Drop fields to summarize' },
|
|
22
|
+
];
|
|
23
|
+
const ZONE_NAME = Object.fromEntries(ZONES.map((z) => [z.id, z.title]));
|
|
24
|
+
|
|
25
|
+
const emptySpec = () => ({ rows: [], cols: [], values: [], filters: [], options: {} });
|
|
26
|
+
|
|
27
|
+
export class PivotDesigner extends Emitter {
|
|
28
|
+
/**
|
|
29
|
+
* @param {HTMLElement|string} container
|
|
30
|
+
* @param {{dataset?:object, spec?:object, autoUpdate?:boolean, theme?:string, viewerOptions?:object}} [options]
|
|
31
|
+
*/
|
|
32
|
+
constructor(container, options = {}) {
|
|
33
|
+
super();
|
|
34
|
+
injectStyles();
|
|
35
|
+
this.el = typeof container === 'string' ? document.querySelector(container) : container;
|
|
36
|
+
if (!this.el) throw new Error('PivotDesigner: container not found');
|
|
37
|
+
this.opts = { autoUpdate: true, theme: 'auto', ...options };
|
|
38
|
+
this.dataset = options.dataset || null;
|
|
39
|
+
this.spec = { ...emptySpec(), ...clone(options.spec || {}) };
|
|
40
|
+
this.spec.options = this.spec.options || {};
|
|
41
|
+
this.dirty = false;
|
|
42
|
+
this._pop = null;
|
|
43
|
+
this.layouts = this._makeLayoutStore();
|
|
44
|
+
this.reports = this._makeReportStore();
|
|
45
|
+
this._cur = null;
|
|
46
|
+
this._build();
|
|
47
|
+
this._renderFields();
|
|
48
|
+
this._renderZones();
|
|
49
|
+
this.viewer.dataset = this.dataset;
|
|
50
|
+
this._pushSpec(true);
|
|
51
|
+
if (this.layouts && !options.spec) this.layouts.getDefault().then((s) => { if (s) this.setSpec(s); }).catch(() => {});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------- public API
|
|
55
|
+
getSpec() { return clone(this.spec); }
|
|
56
|
+
setSpec(spec) {
|
|
57
|
+
this.spec = { ...emptySpec(), ...clone(spec || {}) };
|
|
58
|
+
this.spec.options = this.spec.options || {};
|
|
59
|
+
this._syncToolbar(); this._renderZones(); this._changed();
|
|
60
|
+
}
|
|
61
|
+
_makeLayoutStore() {
|
|
62
|
+
const L = this.opts.layouts, ds = this.dataset;
|
|
63
|
+
if (L === false) return null;
|
|
64
|
+
if (L && typeof L.save === 'function') return L;
|
|
65
|
+
if (L && typeof L.read === 'function') return new LayoutStore(L);
|
|
66
|
+
if (ds && typeof ds.layoutAdapter === 'function' && ds.supportsLayouts) return new LayoutStore(ds.layoutAdapter());
|
|
67
|
+
return new LayoutStore(new LocalStorageAdapter((L && L.namespace) || this.opts.layoutsKey || 'default'));
|
|
68
|
+
}
|
|
69
|
+
setDataset(ds) {
|
|
70
|
+
this.dataset = ds;
|
|
71
|
+
this.layouts = this._makeLayoutStore();
|
|
72
|
+
this.reports = this._makeReportStore();
|
|
73
|
+
this._renderFields();
|
|
74
|
+
const ok = (f) => ds.hasField(f);
|
|
75
|
+
for (const z of ['rows', 'cols', 'filters']) this.spec[z] = this.spec[z].filter((x) => ok(x.field));
|
|
76
|
+
this.spec.values = this.spec.values.filter((x) => x.field === '*' || ok(x.field));
|
|
77
|
+
this._renderZones();
|
|
78
|
+
this.viewer.dataset = ds;
|
|
79
|
+
this._changed();
|
|
80
|
+
}
|
|
81
|
+
getViewer() { return this.viewer; }
|
|
82
|
+
/** Opens the Configure fields (default) or Configure filters dialog. */
|
|
83
|
+
openConfigDialog(mode = 'fields') { this._configDialog(mode); }
|
|
84
|
+
async refresh() { this.dirty = false; this._syncToolbar(); return this.viewer.refresh(); }
|
|
85
|
+
destroy() {
|
|
86
|
+
clearTimeout(this._t);
|
|
87
|
+
document.removeEventListener('mousedown', this._docClick, true);
|
|
88
|
+
document.removeEventListener('keydown', this._docKey);
|
|
89
|
+
this._closePop(); if (this._dlg) this._dlg.close(); if (this._ro) this._ro.disconnect(); this.viewer.destroy(); this.root.remove();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ---------------------------------------------------------------- DOM
|
|
93
|
+
_build() {
|
|
94
|
+
const root = (this.root = document.createElement('div'));
|
|
95
|
+
root.className = 'mp-root mpd-root';
|
|
96
|
+
root.setAttribute('data-theme', this.opts.theme);
|
|
97
|
+
root.style.position = 'relative';
|
|
98
|
+
root.innerHTML = `
|
|
99
|
+
<div class="mpd-tools">
|
|
100
|
+
<button class="mp-btn mp-primary" data-a="update" style="display:none">Update</button>
|
|
101
|
+
<label title="Recalculate automatically after every change"><input type="checkbox" data-a="auto" ${this.opts.autoUpdate ? 'checked' : ''}> Auto-update</label>
|
|
102
|
+
<button class="mp-btn" data-a="config" title="Configure fields: columns, rows and values">⚙ Fields</button>
|
|
103
|
+
<button class="mp-btn" data-a="cfgfilters" title="Configure filters">⏷ Filters</button>
|
|
104
|
+
<button class="mp-btn" data-a="swap" title="Swap rows and columns">⇄ Swap</button>
|
|
105
|
+
<button class="mp-btn" data-a="clear">Clear</button>
|
|
106
|
+
<span class="mp-sp"></span>
|
|
107
|
+
<label><input type="checkbox" data-a="grand" checked> Grand totals</label>
|
|
108
|
+
<label><input type="checkbox" data-a="subtotals" checked> Column subtotals</label>
|
|
109
|
+
<span class="mpd-seg"><button class="mp-btn" data-a="view" data-v="table">Table</button><button class="mp-btn" data-a="view" data-v="chart">Chart</button></span>
|
|
110
|
+
<select class="mp-btn" data-a="ctype" style="display:none" title="Chart type">${CHART_TYPES.map((t) => `<option value="${t}">${CHART_LABEL[t] || t}</option>`).join('')}</select>
|
|
111
|
+
<button class="mp-btn" data-a="expand">Expand all</button>
|
|
112
|
+
<button class="mp-btn" data-a="collapse">Collapse all</button>
|
|
113
|
+
<button class="mp-btn" data-a="layouts">Layouts ▾</button>
|
|
114
|
+
<button class="mp-btn" data-a="layout" title="Edit the layout as JSON">JSON</button>
|
|
115
|
+
${this.reports ? '<button class="mp-btn" data-a="reports" title="Save and open reports">Reports ▾</button>' : ''}
|
|
116
|
+
<button class="mp-btn" data-a="cells" title="Conditional and per-cell formatting">Cell formats ▾</button>
|
|
117
|
+
<button class="mp-btn" data-a="print" title="Print the pivot">Print ▾</button>
|
|
118
|
+
<button class="mp-btn" data-a="export">Export ▾</button>
|
|
119
|
+
<button class="mp-btn" data-a="full" title="Full screen">⛶</button>
|
|
120
|
+
</div>
|
|
121
|
+
<div class="mpd-fields"><h5>Fields <button class="mpd-fx" data-a="fxfield" title="Add a calculated field (per record)">+ fx</button></h5><input type="search" placeholder="Search fields…" data-a="fsearch"><div class="mpd-flist"></div></div>
|
|
122
|
+
<div class="mpd-main">
|
|
123
|
+
<div class="mpd-zones">${ZONES.map((z) => `<div class="mpd-zone" data-zone="${z.id}"><h5>${z.title}${z.id === 'values' ? ' <button class="mpd-fx" data-a="fxvalue" title="Add a calculated value, e.g. sum(Revenue) / sum(Qty)">+ fx</button>' : ''}</h5><div class="mpd-chips"></div></div>`).join('')}</div>
|
|
124
|
+
<div class="mpd-pivot"></div>
|
|
125
|
+
</div>`;
|
|
126
|
+
this.el.appendChild(root);
|
|
127
|
+
this.$ = { flist: root.querySelector('.mpd-flist'), pivot: root.querySelector('.mpd-pivot') };
|
|
128
|
+
// Rows / Columns drop zones live in the grid's top-left corner (like mdg-pivot): column fields beside the
|
|
129
|
+
// column headers, row fields in the line under them. fieldZones: 'top' keeps all four zones in the top strip.
|
|
130
|
+
const inGrid = this.opts.fieldZones !== 'top';
|
|
131
|
+
this.viewer = new PivotViewer(this.$.pivot, { theme: this.opts.theme, actions: false, ...(inGrid ? { headerExtraRows: 1, cornerLabels: false } : {}), ...(this.opts.viewerOptions || {}) });
|
|
132
|
+
if (inGrid) {
|
|
133
|
+
root.classList.add('mpd-gridzones');
|
|
134
|
+
const c = (this.$.corner = document.createElement('div'));
|
|
135
|
+
c.className = 'mpd-corner';
|
|
136
|
+
c.innerHTML = ['cols', 'rows'].map((id) => `<div class="mpd-zone" data-zone="${id}"><div class="mpd-chips"></div></div>`).join('');
|
|
137
|
+
this.$.pivot.appendChild(c);
|
|
138
|
+
this._geo = null;
|
|
139
|
+
this.viewer.on('layout', (g) => { this._geo = g; this._placeCorner(); });
|
|
140
|
+
if (typeof ResizeObserver !== 'undefined') { this._ro = new ResizeObserver(() => this._placeCorner()); this._ro.observe(this.$.pivot); }
|
|
141
|
+
}
|
|
142
|
+
this.viewer.on('compute-end', (r) => this.emit('compute-end', r));
|
|
143
|
+
this.viewer.on('error', (e) => this.emit('error', e));
|
|
144
|
+
this.viewer.on('cellclick', (e) => this.emit('cellclick', e));
|
|
145
|
+
this.viewer.on('drill', (e) => this.emit('drill', e));
|
|
146
|
+
this.viewer.on('cellcontext', (e) => {
|
|
147
|
+
if (e.event) e.event.preventDefault();
|
|
148
|
+
const at = { getBoundingClientRect: () => ({ left: e.clientX, right: e.clientX, top: e.clientY, bottom: e.clientY, width: 0, height: 0 }), contains: () => false };
|
|
149
|
+
this._rulesPop(at, { scope: { value: e.valueIndex, kind: 'any', row: e.row, col: e.col, exact: true } });
|
|
150
|
+
});
|
|
151
|
+
this._syncToolbar();
|
|
152
|
+
|
|
153
|
+
root.addEventListener('click', (e) => this._onClick(e));
|
|
154
|
+
root.addEventListener('input', (e) => { if (e.target.dataset.a === 'fsearch') this._renderFields(e.target.value); });
|
|
155
|
+
root.addEventListener('change', (e) => this._onToolChange(e));
|
|
156
|
+
root.addEventListener('dragstart', (e) => this._dragStart(e));
|
|
157
|
+
root.addEventListener('dragend', () => this._dragEnd());
|
|
158
|
+
root.addEventListener('dragover', (e) => { const z = e.target.closest('.mpd-zone'); if (z && this._drag) { e.preventDefault(); z.classList.add('mpd-over'); } });
|
|
159
|
+
root.addEventListener('dragleave', (e) => { const z = e.target.closest('.mpd-zone'); if (z && !z.contains(e.relatedTarget)) z.classList.remove('mpd-over'); });
|
|
160
|
+
root.addEventListener('drop', (e) => this._drop(e));
|
|
161
|
+
this._docClick = (e) => { if (this._pop && !this._pop.el.contains(e.target) && !(this._pop.anchor && this._pop.anchor.contains(e.target))) this._closePop(); };
|
|
162
|
+
this._docKey = (e) => { if (e.key === 'Escape') this._closePop(); };
|
|
163
|
+
document.addEventListener('mousedown', this._docClick, true);
|
|
164
|
+
document.addEventListener('keydown', this._docKey);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
_fieldInfo() { return this.dataset ? this.dataset.fieldInfo() : []; }
|
|
168
|
+
|
|
169
|
+
_renderFields(search = '') {
|
|
170
|
+
const q = search.toLowerCase();
|
|
171
|
+
const html = this._fieldInfo()
|
|
172
|
+
.filter((f) => f.role !== 'skip' && (!q || f.label.toLowerCase().includes(q)))
|
|
173
|
+
.map((f) => {
|
|
174
|
+
const ico = f.formula ? '<span class="mpd-ico m" title="Calculated field">fx</span>' : f.type === 'date' ? '<span class="mpd-ico t">D</span>' : f.isMeasure ? '<span class="mpd-ico m">#</span>' : '<span class="mpd-ico d">Aa</span>';
|
|
175
|
+
const off = f.overflow ? ' mpd-off' : '';
|
|
176
|
+
const tip = f.formula ? `= ${f.formula}` : f.overflow ? 'Too many distinct values to group by' : f.cardinality != null ? `${f.cardinality.toLocaleString()} distinct values` : 'measure';
|
|
177
|
+
return `<div class="mpd-field${off}" draggable="${f.overflow ? 'false' : 'true'}" data-field="${esc(f.name)}" title="${esc(tip)}">${ico}<span class="mpd-t">${esc(f.label)}</span><button data-a="fmenu" data-field="${esc(f.name)}" title="Add to…">+</button></div>`;
|
|
178
|
+
}).join('');
|
|
179
|
+
this.$.flist.innerHTML = html || '<div class="mpd-hint" style="padding:10px">No fields</div>';
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
_chipLabel(zone, it) {
|
|
183
|
+
if (zone === 'values' && it.calc) return it.label || it.calc;
|
|
184
|
+
const f = it.field === '*' ? null : this._fieldInfo().find((x) => x.name === it.field);
|
|
185
|
+
const name = f ? f.label : it.field;
|
|
186
|
+
if (zone === 'values') return it.label || (it.field === '*' ? 'Count' : `${AGG_LABEL[it.agg || 'sum']} of ${name}`);
|
|
187
|
+
if (zone === 'filters') {
|
|
188
|
+
const n = (it.include || it.exclude || []).length;
|
|
189
|
+
return it.include ? `${name} (${n} selected)` : n ? `${name} (${n} hidden)` : name;
|
|
190
|
+
}
|
|
191
|
+
return it.bucket ? `${name} (${it.bucket})` : name;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
_renderZones() {
|
|
195
|
+
for (const z of ZONES) {
|
|
196
|
+
const items = this.spec[z.id];
|
|
197
|
+
for (const box of this.root.querySelectorAll(`.mpd-zone[data-zone="${z.id}"] .mpd-chips`)) box.innerHTML = items.length
|
|
198
|
+
? items.map((it, i) => `<span class="mpd-chip" draggable="true" data-zone="${z.id}" data-i="${i}" title="${esc(this._chipLabel(z.id, it))}"><span class="mpd-t" data-a="chip">${esc(this._chipLabel(z.id, it))}</span><button data-a="rm" data-zone="${z.id}" data-i="${i}" title="Remove">×</button></span>`).join('')
|
|
199
|
+
: `<span class="mpd-hint" style="padding:0">${z.hint}</span>`;
|
|
200
|
+
}
|
|
201
|
+
this._placeCorner();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Sizes the in-grid Rows / Columns zones over the viewer's top-left corner. */
|
|
205
|
+
_placeCorner() {
|
|
206
|
+
const c = this.$ && this.$.corner;
|
|
207
|
+
if (!c || !this.viewer.$) return;
|
|
208
|
+
const v = this.viewer, rh = v.opts.rowHeight, w = v.opts.rowHeaderWidth;
|
|
209
|
+
const levels = Math.max(this._geo ? this._geo.headerLevels : 1, this.spec.cols.length, 1);
|
|
210
|
+
const p = this.$.pivot.getBoundingClientRect(), s = v.$.sc.getBoundingClientRect();
|
|
211
|
+
Object.assign(c.style, { left: s.left - p.left + 'px', top: s.top - p.top + 'px', width: w + 'px', height: (levels + 1) * rh + 'px' });
|
|
212
|
+
c.style.setProperty('--rh', rh + 'px');
|
|
213
|
+
const [cols, rows] = c.children;
|
|
214
|
+
Object.assign(cols.style, { top: '0px', height: levels * rh + 'px' });
|
|
215
|
+
Object.assign(rows.style, { top: levels * rh + 'px', height: rh + 'px' });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
_syncToolbar() {
|
|
219
|
+
const o = this.spec.options;
|
|
220
|
+
const q = (a) => this.root.querySelector(`[data-a="${a}"]`);
|
|
221
|
+
q('grand').checked = o.grandTotals !== false;
|
|
222
|
+
q('subtotals').checked = o.colSubtotals !== false;
|
|
223
|
+
q('update').style.display = !this.opts.autoUpdate && this.dirty ? '' : 'none';
|
|
224
|
+
q('auto').checked = !!this.opts.autoUpdate;
|
|
225
|
+
const chart = o.view === 'chart';
|
|
226
|
+
this.root.querySelectorAll('[data-a="view"]').forEach((b) => b.classList.toggle('mpd-on', (b.dataset.v === 'chart') === chart));
|
|
227
|
+
const ct = q('ctype');
|
|
228
|
+
ct.style.display = chart ? '' : 'none';
|
|
229
|
+
ct.value = (o.chart && o.chart.type) || 'column';
|
|
230
|
+
q('expand').style.display = q('collapse').style.display = chart ? 'none' : '';
|
|
231
|
+
}
|
|
232
|
+
_applyView() {
|
|
233
|
+
const o = this.spec.options;
|
|
234
|
+
this.viewer.setView(o.view === 'chart' ? 'chart' : 'table', o.chart);
|
|
235
|
+
this.root.classList.toggle('mpd-chartview', o.view === 'chart'); // no grid corner in chart view: zones move back to the top strip
|
|
236
|
+
}
|
|
237
|
+
_viewChanged() {
|
|
238
|
+
this._syncToolbar();
|
|
239
|
+
this._applyView();
|
|
240
|
+
this.emit('change', this.getSpec());
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---------------------------------------------------------------- spec mutation
|
|
244
|
+
_changed() {
|
|
245
|
+
this._renderZones();
|
|
246
|
+
this.emit('change', this.getSpec());
|
|
247
|
+
if (this.opts.autoUpdate) this._pushSpec();
|
|
248
|
+
else { this.dirty = true; this._syncToolbar(); }
|
|
249
|
+
}
|
|
250
|
+
_pushSpec(first) {
|
|
251
|
+
clearTimeout(this._t);
|
|
252
|
+
this.dirty = false;
|
|
253
|
+
this._syncToolbar();
|
|
254
|
+
if (!this.dataset) return;
|
|
255
|
+
this._applyView();
|
|
256
|
+
this._t = setTimeout(() => { this.viewer.setSpec(clone(this.spec)); }, first ? 0 : 120);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
_defaultItem(zone, field) {
|
|
260
|
+
const info = this._fieldInfo().find((f) => f.name === field);
|
|
261
|
+
if (zone === 'values') {
|
|
262
|
+
if (info && info.isMeasure) return { field, agg: 'sum' };
|
|
263
|
+
return { field: '*', agg: 'count', label: `Count of ${info ? info.label : field}` };
|
|
264
|
+
}
|
|
265
|
+
if (zone === 'filters') return { field, exclude: [] };
|
|
266
|
+
return { field, sort: 'asc' };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
_canDrop(zone, field) {
|
|
270
|
+
if (field === undefined) return zone === 'values';
|
|
271
|
+
const info = this._fieldInfo().find((f) => f.name === field);
|
|
272
|
+
if (!info) return field === '*' && zone === 'values';
|
|
273
|
+
if (zone === 'values') return true;
|
|
274
|
+
return info.isDimension;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
_move(src, dst, field, dstIndex, target) {
|
|
278
|
+
const S = target || this.spec; // target: a draft spec (configure dialog); omitted = the live spec
|
|
279
|
+
// src: {zone, index} | null (from field list)
|
|
280
|
+
if (src && src.zone) {
|
|
281
|
+
const it0 = S[src.zone][src.index];
|
|
282
|
+
if (it0 && (it0.calc !== undefined || it0.field === '*') && dst !== 'values') return; // calc / count values only live in Values
|
|
283
|
+
}
|
|
284
|
+
let item;
|
|
285
|
+
if (src && src.zone) {
|
|
286
|
+
item = S[src.zone].splice(src.index, 1)[0];
|
|
287
|
+
if (src.zone === dst && dstIndex > src.index) dstIndex--;
|
|
288
|
+
if (dst === 'values' && src.zone !== 'values') item = this._defaultItem('values', item.field);
|
|
289
|
+
else if (src.zone === 'values' && dst !== 'values') item = this._defaultItem(dst, item.field === '*' ? field : item.field);
|
|
290
|
+
else if (src.zone !== dst) item = this._defaultItem(dst, item.field);
|
|
291
|
+
} else item = this._defaultItem(dst, field);
|
|
292
|
+
if (!item || (item.field === '*' && dst !== 'values')) return;
|
|
293
|
+
if (!this._canDrop(dst, item.field)) return;
|
|
294
|
+
// a field lives in rows OR cols, once
|
|
295
|
+
if (dst === 'rows' || dst === 'cols') {
|
|
296
|
+
for (const z of ['rows', 'cols']) S[z] = S[z].filter((x) => x.field !== item.field);
|
|
297
|
+
}
|
|
298
|
+
if (dst === 'filters') S.filters = S.filters.filter((x) => x.field !== item.field);
|
|
299
|
+
const arr = S[dst];
|
|
300
|
+
arr.splice(Math.max(0, Math.min(dstIndex ?? arr.length, arr.length)), 0, item);
|
|
301
|
+
if (!target) this._changed();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ---------------------------------------------------------------- drag & drop
|
|
305
|
+
_dragStart(e) {
|
|
306
|
+
const chip = e.target.closest('.mpd-chip'), fld = e.target.closest('.mpd-field');
|
|
307
|
+
if (chip) { this._drag = { src: { zone: chip.dataset.zone, index: +chip.dataset.i }, field: this.spec[chip.dataset.zone][+chip.dataset.i].field }; chip.classList.add('mpd-drag'); }
|
|
308
|
+
else if (fld && fld.draggable) this._drag = { src: null, field: fld.dataset.field };
|
|
309
|
+
else return;
|
|
310
|
+
e.dataTransfer.effectAllowed = 'move';
|
|
311
|
+
e.dataTransfer.setData('text/plain', this._drag.field);
|
|
312
|
+
}
|
|
313
|
+
_dragEnd() {
|
|
314
|
+
this._drag = null;
|
|
315
|
+
this.root.querySelectorAll('.mpd-over,.mpd-drag').forEach((x) => x.classList.remove('mpd-over', 'mpd-drag'));
|
|
316
|
+
}
|
|
317
|
+
_drop(e) {
|
|
318
|
+
const z = e.target.closest('.mpd-zone');
|
|
319
|
+
const d = this._drag;
|
|
320
|
+
if (!z || !d) return;
|
|
321
|
+
e.preventDefault();
|
|
322
|
+
const dst = z.dataset.zone;
|
|
323
|
+
const chips = [...z.querySelectorAll('.mpd-chip')];
|
|
324
|
+
let idx = 0;
|
|
325
|
+
for (const c of chips) {
|
|
326
|
+
const r = c.getBoundingClientRect();
|
|
327
|
+
if (e.clientY > r.bottom || (e.clientY >= r.top && e.clientX > r.left + r.width / 2)) idx = +c.dataset.i + 1;
|
|
328
|
+
}
|
|
329
|
+
this._dragEnd();
|
|
330
|
+
this._drag = null;
|
|
331
|
+
this._move(d.src, dst, d.field, idx);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------------------------------------------------------------- clicks
|
|
335
|
+
_onToolChange(e) {
|
|
336
|
+
const a = e.target.dataset.a;
|
|
337
|
+
if (a === 'auto') { this.opts.autoUpdate = e.target.checked; if (e.target.checked && this.dirty) this._pushSpec(); this._syncToolbar(); }
|
|
338
|
+
else if (a === 'grand') { this.spec.options.grandTotals = e.target.checked; this._changed(); }
|
|
339
|
+
else if (a === 'subtotals') { this.spec.options.colSubtotals = e.target.checked; this._changed(); }
|
|
340
|
+
else if (a === 'ctype') { this.spec.options.chart = { ...(this.spec.options.chart || {}), type: e.target.value }; this._viewChanged(); }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
_onClick(e) {
|
|
344
|
+
const t = e.target.closest('[data-a]');
|
|
345
|
+
if (!t) return;
|
|
346
|
+
const a = t.dataset.a;
|
|
347
|
+
switch (a) {
|
|
348
|
+
case 'update': this._pushSpec(true); break;
|
|
349
|
+
case 'swap': [this.spec.rows, this.spec.cols] = [this.spec.cols, this.spec.rows]; this._changed(); break;
|
|
350
|
+
case 'clear': Object.assign(this.spec, { rows: [], cols: [], values: [], filters: [] }); this._changed(); break;
|
|
351
|
+
case 'expand': this.viewer.expandAll(); break;
|
|
352
|
+
case 'collapse': this.viewer.collapseAll(); break;
|
|
353
|
+
case 'view': this.spec.options.view = t.dataset.v; if (t.dataset.v === 'chart' && !this.spec.options.chart) this.spec.options.chart = { type: 'column' }; this._viewChanged(); break;
|
|
354
|
+
case 'export': this._exportPop(t); break;
|
|
355
|
+
case 'cells': this._rulesPop(t); break;
|
|
356
|
+
case 'reports': this._reportsPop(t); break;
|
|
357
|
+
case 'print': this._printPop(t); break;
|
|
358
|
+
case 'layouts': this._layoutsPop(t); break;
|
|
359
|
+
case 'config': this._configDialog('fields'); break;
|
|
360
|
+
case 'cfgfilters': this._configDialog('filters'); break;
|
|
361
|
+
case 'full': this.root.classList.toggle('mpd-full'); this._placeCorner(); break;
|
|
362
|
+
case 'fxfield': this._fxFieldPop(t); break;
|
|
363
|
+
case 'fxvalue': this._fxValuePop(t); break;
|
|
364
|
+
case 'layout': this._layoutPop(t); break;
|
|
365
|
+
case 'rm': { this.spec[t.dataset.zone].splice(+t.dataset.i, 1); this._closePop(); this._changed(); break; }
|
|
366
|
+
case 'chip': { const c = t.closest('.mpd-chip'); this._chipPop(c, c.dataset.zone, +c.dataset.i); break; }
|
|
367
|
+
case 'fmenu': this._addMenu(t, t.dataset.field); break;
|
|
368
|
+
default: break;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ---------------------------------------------------------------- configure dialog (mdg-pivot layout)
|
|
373
|
+
/**
|
|
374
|
+
* Modal with the field list (search, select all, checkboxes) beside Columns / Rows / Values panes (move up/down,
|
|
375
|
+
* drag between panes) and Apply / Cancel, like mdg-pivot's "Configure Pivot fields". mode 'filters' shows
|
|
376
|
+
* the field list beside a single Filters pane. Edits a draft; Apply commits it as one change.
|
|
377
|
+
*/
|
|
378
|
+
_configDialog(mode = 'fields') {
|
|
379
|
+
this._closePop();
|
|
380
|
+
if (this._dlg) this._dlg.close();
|
|
381
|
+
const fieldsMode = mode !== 'filters';
|
|
382
|
+
const panes = fieldsMode ? [['cols', 'Columns'], ['rows', 'Rows'], ['values', 'Values']] : [['filters', 'Filters']];
|
|
383
|
+
const keys = panes.map((p) => p[0]);
|
|
384
|
+
const S = { rows: clone(this.spec.rows), cols: clone(this.spec.cols), values: clone(this.spec.values), filters: clone(this.spec.filters), options: this.spec.options };
|
|
385
|
+
const st = { search: '', showSearch: false, sel: null, drag: null };
|
|
386
|
+
const info = (name) => this._fieldInfo().find((f) => f.name === name);
|
|
387
|
+
const isOn = (name) => keys.some((z) => S[z].some((x) => x.field === name));
|
|
388
|
+
const canAdd = (f) => (fieldsMode ? !f.overflow || f.isMeasure : this._canDrop('filters', f.name));
|
|
389
|
+
|
|
390
|
+
const el = document.createElement('div');
|
|
391
|
+
el.className = 'mpd-modal';
|
|
392
|
+
el.innerHTML = `<div class="mpd-dlg" role="dialog" aria-modal="true" style="--n:${panes.length + 1}">
|
|
393
|
+
<div class="mpd-dh"><h3>${fieldsMode ? '▦ Configure Pivot fields' : '⏷ Configure Pivot filters'}</h3><small>${fieldsMode ? 'Drag & drop fields to configure your pivot report.' : 'Drag & drop fields to filter your pivot report.'}</small></div>
|
|
394
|
+
<div class="mpd-dcols">
|
|
395
|
+
<div class="mpd-pane"><div class="mpd-ph" data-h="list"></div><div class="mpd-pbody" data-b="list"></div></div>
|
|
396
|
+
${panes.map(([z, title]) => `<div class="mpd-pane"><div class="mpd-ph"><span>${title}</span>${z === 'filters' ? '' : `<span class="mpd-mv"><button data-mv="${z}" data-d="-1" title="Move up">▲</button><button data-mv="${z}" data-d="1" title="Move down">▼</button></span>`}</div><div class="mpd-pbody" data-b="${z}" data-zone="${z}"></div></div>`).join('')}
|
|
397
|
+
</div>
|
|
398
|
+
<div class="mpd-df"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span>
|
|
399
|
+
${fieldsMode ? '<button class="mp-btn mpd-green" data-x="fx">Add Formula Field</button>' : ''}
|
|
400
|
+
<button class="mp-btn mp-primary" data-x="apply">Apply</button><button class="mp-btn" data-x="cancel">Cancel</button></div>
|
|
401
|
+
</div>`;
|
|
402
|
+
this.root.appendChild(el);
|
|
403
|
+
const $ = (s) => el.querySelector(s);
|
|
404
|
+
|
|
405
|
+
const label = (z, it) => {
|
|
406
|
+
if (z === 'values') {
|
|
407
|
+
if (it.calc !== undefined) return it.label || it.calc;
|
|
408
|
+
if (it.field === '*') return it.label || 'Count';
|
|
409
|
+
return (info(it.field) || { label: it.field }).label;
|
|
410
|
+
}
|
|
411
|
+
return this._chipLabel(z, it);
|
|
412
|
+
};
|
|
413
|
+
const aggOptions = (it) => {
|
|
414
|
+
const f = info(it.field);
|
|
415
|
+
const aggs = it.field === '*' ? ['count'] : f && f.isMeasure ? AGGREGATES : ['count', 'distinct'];
|
|
416
|
+
return aggs.map((g) => `<option value="${g}"${g === (it.agg || 'sum') ? ' selected' : ''}>${AGG_LABEL[g]}</option>`).join('');
|
|
417
|
+
};
|
|
418
|
+
const paint = () => {
|
|
419
|
+
// field list
|
|
420
|
+
const q = st.search.toLowerCase();
|
|
421
|
+
const infos = this._fieldInfo().filter((f) => f.role !== 'skip' && (!q || f.label.toLowerCase().includes(q)));
|
|
422
|
+
const row = (f) => `<div class="mpd-dr${isOn(f.name) ? ' on' : ''}" draggable="${canAdd(f)}" data-field="${esc(f.name)}" title="${esc(f.formula ? '= ' + f.formula : f.label)}"><span class="mpd-grip">≡</span><span class="mpd-t">${esc(f.label)}</span><input type="checkbox" data-chk="${esc(f.name)}"${isOn(f.name) ? ' checked' : ''}${canAdd(f) ? '' : ' disabled'}></div>`;
|
|
423
|
+
const plain = infos.filter((f) => !f.formula), calc = infos.filter((f) => f.formula);
|
|
424
|
+
const enabled = infos.filter(canAdd);
|
|
425
|
+
const all = enabled.length > 0 && enabled.every((f) => isOn(f.name));
|
|
426
|
+
$('[data-h="list"]').innerHTML = st.showSearch
|
|
427
|
+
? `<input type="search" data-search placeholder="Search fields…" value="${esc(st.search)}" style="flex:1"><button data-x="nosearch" title="Close search">×</button>`
|
|
428
|
+
: `<span>List of Fields</span><span class="mpd-mv"><button data-x="search" title="Search">🔍</button><input type="checkbox" data-all title="Select all"${all ? ' checked' : ''}></span>`;
|
|
429
|
+
$('[data-b="list"]').innerHTML = plain.map(row).join('') + (calc.length ? `<div class="mpd-sub">Formula fields</div>${calc.map(row).join('')}` : '') || '<div class="mpd-hint" style="padding:10px">No fields</div>';
|
|
430
|
+
// zone panes
|
|
431
|
+
for (const [z] of panes) {
|
|
432
|
+
$(`[data-b="${z}"]`).innerHTML = S[z].map((it, i) => `<div class="mpd-dr${st.sel && st.sel.zone === z && st.sel.index === i ? ' sel' : ''}" draggable="true" data-zone="${z}" data-i="${i}"><span class="mpd-grip">≡</span><span class="mpd-t" title="${esc(this._chipLabel(z, it))}">${esc(label(z, it))}</span>${z === 'values' && it.calc === undefined ? `<select data-agg="${i}" title="Summarize by">${aggOptions(it)}</select>` : ''}</div>`).join('')
|
|
433
|
+
|| `<div class="mpd-hint" style="padding:10px">${(ZONES.find((x) => x.id === z) || {}).hint || ''}</div>`;
|
|
434
|
+
}
|
|
435
|
+
const focus = el.querySelector('[data-search]');
|
|
436
|
+
if (focus && st.focusSearch) { focus.focus(); focus.setSelectionRange(focus.value.length, focus.value.length); st.focusSearch = false; }
|
|
437
|
+
};
|
|
438
|
+
const toggle = (name, on) => {
|
|
439
|
+
const f = info(name);
|
|
440
|
+
if (!f) return;
|
|
441
|
+
if (on) {
|
|
442
|
+
if (isOn(name)) return;
|
|
443
|
+
if (!fieldsMode) { this._move(null, 'filters', name, undefined, S); return; }
|
|
444
|
+
this._move(null, f.isMeasure && !f.isDimension ? 'values' : f.isDimension ? 'rows' : 'values', name, undefined, S);
|
|
445
|
+
} else {
|
|
446
|
+
for (const z of keys) S[z] = S[z].filter((x) => x.field !== name);
|
|
447
|
+
st.sel = null;
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
const close = () => { el.remove(); document.removeEventListener('keydown', onKey, true); if (this._dlg && this._dlg.el === el) this._dlg = null; };
|
|
451
|
+
const onKey = (e) => { if (e.key === 'Escape' && !this._pop) { e.stopPropagation(); close(); } };
|
|
452
|
+
document.addEventListener('keydown', onKey, true);
|
|
453
|
+
this._dlg = { el, close, refresh: paint };
|
|
454
|
+
|
|
455
|
+
el.addEventListener('click', (e) => {
|
|
456
|
+
if (e.target === el) { close(); return; }
|
|
457
|
+
const x = e.target.closest('[data-x]'), mv = e.target.closest('[data-mv]');
|
|
458
|
+
if (mv) {
|
|
459
|
+
const z = mv.dataset.mv, d = +mv.dataset.d, s = st.sel;
|
|
460
|
+
if (s && s.zone === z) {
|
|
461
|
+
const j = s.index + d;
|
|
462
|
+
if (j >= 0 && j < S[z].length) { const [it] = S[z].splice(s.index, 1); S[z].splice(j, 0, it); s.index = j; paint(); }
|
|
463
|
+
}
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (x) {
|
|
467
|
+
switch (x.dataset.x) {
|
|
468
|
+
case 'apply':
|
|
469
|
+
for (const z of keys) this.spec[z] = S[z];
|
|
470
|
+
close(); this._changed(); break;
|
|
471
|
+
case 'cancel': close(); break;
|
|
472
|
+
case 'search': st.showSearch = true; st.focusSearch = true; paint(); break;
|
|
473
|
+
case 'nosearch': st.showSearch = false; st.search = ''; paint(); break;
|
|
474
|
+
case 'fx': this._fxFieldPop(x); break;
|
|
475
|
+
default: break;
|
|
476
|
+
}
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const r = e.target.closest('.mpd-dr[data-zone]');
|
|
480
|
+
if (r && !e.target.closest('select')) { st.sel = { zone: r.dataset.zone, index: +r.dataset.i }; paint(); }
|
|
481
|
+
});
|
|
482
|
+
el.addEventListener('input', (e) => { if (e.target.dataset.search !== undefined) { st.search = e.target.value; st.focusSearch = true; paint(); } });
|
|
483
|
+
el.addEventListener('change', (e) => {
|
|
484
|
+
const t = e.target;
|
|
485
|
+
if (t.dataset.chk !== undefined) { toggle(t.dataset.chk, t.checked); paint(); }
|
|
486
|
+
else if (t.dataset.all !== undefined) {
|
|
487
|
+
const q = st.search.toLowerCase();
|
|
488
|
+
for (const f of this._fieldInfo().filter((f) => f.role !== 'skip' && canAdd(f) && (!q || f.label.toLowerCase().includes(q)))) toggle(f.name, t.checked);
|
|
489
|
+
paint();
|
|
490
|
+
} else if (t.dataset.agg !== undefined) {
|
|
491
|
+
const it = S.values[+t.dataset.agg];
|
|
492
|
+
it.agg = t.value; delete it.label;
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
el.addEventListener('dragstart', (e) => {
|
|
496
|
+
const r = e.target.closest('.mpd-dr');
|
|
497
|
+
if (!r) return;
|
|
498
|
+
st.drag = r.dataset.zone ? { src: { zone: r.dataset.zone, index: +r.dataset.i }, field: S[r.dataset.zone][+r.dataset.i].field } : { src: null, field: r.dataset.field };
|
|
499
|
+
e.dataTransfer.effectAllowed = 'move';
|
|
500
|
+
e.dataTransfer.setData('text/plain', st.drag.field);
|
|
501
|
+
});
|
|
502
|
+
el.addEventListener('dragend', () => { st.drag = null; el.querySelectorAll('.mpd-over').forEach((n) => n.classList.remove('mpd-over')); });
|
|
503
|
+
el.addEventListener('dragover', (e) => { const b = e.target.closest('.mpd-pbody[data-zone]'); if (b && st.drag) { e.preventDefault(); b.classList.add('mpd-over'); } });
|
|
504
|
+
el.addEventListener('dragleave', (e) => { const b = e.target.closest('.mpd-pbody[data-zone]'); if (b && !b.contains(e.relatedTarget)) b.classList.remove('mpd-over'); });
|
|
505
|
+
el.addEventListener('drop', (e) => {
|
|
506
|
+
const b = e.target.closest('.mpd-pbody[data-zone]'), d = st.drag;
|
|
507
|
+
if (!b || !d) return;
|
|
508
|
+
e.preventDefault();
|
|
509
|
+
let idx = 0;
|
|
510
|
+
for (const n of b.querySelectorAll('.mpd-dr')) { const r = n.getBoundingClientRect(); if (e.clientY > r.top + r.height / 2) idx = +n.dataset.i + 1; }
|
|
511
|
+
st.drag = null; el.querySelectorAll('.mpd-over').forEach((n) => n.classList.remove('mpd-over'));
|
|
512
|
+
this._move(d.src, b.dataset.zone, d.field, idx, S);
|
|
513
|
+
st.sel = null;
|
|
514
|
+
paint();
|
|
515
|
+
});
|
|
516
|
+
paint();
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ---------------------------------------------------------------- popovers
|
|
520
|
+
_closePop() { if (this._pop) { this._pop.el.remove(); this._pop = null; } }
|
|
521
|
+
_openPop(anchor, html) {
|
|
522
|
+
this._closePop();
|
|
523
|
+
const el = document.createElement('div');
|
|
524
|
+
el.className = 'mpd-pop';
|
|
525
|
+
el.innerHTML = html;
|
|
526
|
+
this.root.appendChild(el);
|
|
527
|
+
const rr = this.root.getBoundingClientRect(), ar = anchor.getBoundingClientRect();
|
|
528
|
+
const w = el.offsetWidth;
|
|
529
|
+
el.style.left = Math.max(4, Math.min(ar.left - rr.left, rr.width - w - 4)) + 'px';
|
|
530
|
+
el.style.top = ar.bottom - rr.top + 4 + 'px';
|
|
531
|
+
this._pop = { el, anchor };
|
|
532
|
+
return el;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
_addMenu(anchor, field) {
|
|
536
|
+
const info = this._fieldInfo().find((f) => f.name === field);
|
|
537
|
+
const items = ZONES.filter((z) => this._canDrop(z.id, field))
|
|
538
|
+
.map((z) => `<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-to="${z.id}">Add to ${z.title}</button></div>`).join('');
|
|
539
|
+
const el = this._openPop(anchor, `<h6>${esc(info ? info.label : field)}</h6>${items}`);
|
|
540
|
+
el.addEventListener('click', (e) => {
|
|
541
|
+
const b = e.target.closest('[data-to]');
|
|
542
|
+
if (!b) return;
|
|
543
|
+
this._closePop();
|
|
544
|
+
this._move(null, b.dataset.to, field);
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
_chipPop(chip, zone, i) {
|
|
549
|
+
const it = this.spec[zone][i];
|
|
550
|
+
const info = this._fieldInfo().find((f) => f.name === it.field);
|
|
551
|
+
const title = `<h6>${esc(it.calc !== undefined ? 'Calculated value' : info ? info.label : 'Count')}</h6>`;
|
|
552
|
+
const moveTo = ZONES.filter((z) => z.id !== zone && (it.field === '*' ? false : this._canDrop(z.id, it.field)))
|
|
553
|
+
.map((z) => `<button class="mpd-link" data-to="${z.id}">→ ${z.title}</button>`).join('');
|
|
554
|
+
const foot = `<hr><div class="mpd-actions"><span style="flex:1">${moveTo}</span><button class="mp-btn" data-x="rm">Remove</button><button class="mp-btn mp-primary" data-x="close">Done</button></div>`;
|
|
555
|
+
let body = '';
|
|
556
|
+
if (zone === 'values' && it.calc !== undefined) {
|
|
557
|
+
body = `
|
|
558
|
+
<h6>Formula</h6><div class="mpd-row"><input type="text" data-k="calc" value="${esc(it.calc)}" placeholder="sum(Revenue) / sum(Qty)"></div>
|
|
559
|
+
<h6>Show as</h6><div class="mpd-row"><select data-k="showAs">${Object.entries(SHOW_AS).map(([k, v]) => `<option value="${k}" ${k === (it.showAs || 'value') ? 'selected' : ''}>${v}</option>`).join('')}</select></div>
|
|
560
|
+
<h6>Number format</h6><div class="mpd-row"><select data-k="format"><option value="">Auto</option>${FORMATS.map((f) => `<option ${it.format === f ? 'selected' : ''}>${f}</option>`).join('')}</select></div>
|
|
561
|
+
<h6>Name</h6><div class="mpd-row"><input type="text" data-k="label" value="${esc(it.label || '')}" placeholder="Calculation"></div>
|
|
562
|
+
<div class="mpd-hint" style="padding:4px 2px 0">Aggregates: sum count avg min max distinct median. Reference other values as [Label].</div>`;
|
|
563
|
+
} else if (zone === 'values') {
|
|
564
|
+
const measure = it.field !== '*' && info && info.isMeasure;
|
|
565
|
+
const aggs = measure ? AGGREGATES : (it.field !== '*' && info && info.isDimension ? ['count', 'distinct'] : ['count']);
|
|
566
|
+
body = `
|
|
567
|
+
<h6>Summarize by</h6><div class="mpd-row"><select data-k="agg">${aggs.map((g) => `<option value="${g}" ${g === (it.agg || 'sum') ? 'selected' : ''}>${AGG_LABEL[g]}</option>`).join('')}</select></div>
|
|
568
|
+
<h6>Show as</h6><div class="mpd-row"><select data-k="showAs">${Object.entries(SHOW_AS).map(([k, v]) => `<option value="${k}" ${k === (it.showAs || 'value') ? 'selected' : ''}>${v}</option>`).join('')}</select></div>
|
|
569
|
+
<h6>Number format</h6><div class="mpd-row"><select data-k="format"><option value="">Auto</option>${FORMATS.map((f) => `<option ${it.format === f ? 'selected' : ''}>${f}</option>`).join('')}</select></div>
|
|
570
|
+
<h6>Name</h6><div class="mpd-row"><input type="text" data-k="label" value="${esc(it.label || '')}" placeholder="${esc(this._chipLabel('values', { ...it, label: '' }))}"></div>`;
|
|
571
|
+
} else if (zone === 'filters') {
|
|
572
|
+
return this._filterPop(chip, zone, i);
|
|
573
|
+
} else {
|
|
574
|
+
body = `<h6>Sort</h6><div class="mpd-row"><select data-k="sort">${[['asc', 'A → Z / oldest first'], ['desc', 'Z → A / newest first'], ['natural', 'Order of appearance']].map(([k, v]) => `<option value="${k}" ${k === (it.sort || 'asc') ? 'selected' : ''}>${v}</option>`).join('')}</select></div>`;
|
|
575
|
+
if (info && info.type === 'date') {
|
|
576
|
+
body += `<h6>Group dates by</h6><div class="mpd-row"><select data-k="bucket"><option value="">Exact value</option>${DATE_BUCKETS.map((b) => `<option ${it.bucket === b ? 'selected' : ''}>${b}</option>`).join('')}</select></div>`;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const el = this._openPop(chip, title + body + foot);
|
|
580
|
+
el.addEventListener('change', (e) => {
|
|
581
|
+
const k = e.target.dataset.k;
|
|
582
|
+
if (!k) return;
|
|
583
|
+
const v = e.target.value;
|
|
584
|
+
if (v === '' || (k === 'showAs' && v === 'value')) delete it[k]; else it[k] = v;
|
|
585
|
+
if (k === 'agg') delete it.label; // auto-name follows the aggregate
|
|
586
|
+
this._changed();
|
|
587
|
+
});
|
|
588
|
+
el.addEventListener('click', (e) => {
|
|
589
|
+
const to = e.target.closest('[data-to]');
|
|
590
|
+
const x = e.target.closest('[data-x]');
|
|
591
|
+
if (to) { this._closePop(); this._move({ zone, index: i }, to.dataset.to, it.field, undefined); }
|
|
592
|
+
else if (x && x.dataset.x === 'rm') { this.spec[zone].splice(i, 1); this._closePop(); this._changed(); }
|
|
593
|
+
else if (x) this._closePop();
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
_filterPop(chip, zone, i) {
|
|
598
|
+
const it = this.spec.filters[i];
|
|
599
|
+
const info = this._fieldInfo().find((f) => f.name === it.field);
|
|
600
|
+
const el = this._openPop(chip, `<h6>Filter · ${esc(info ? info.label : it.field)}</h6>
|
|
601
|
+
<div class="mpd-row"><input type="search" data-q placeholder="Search values…"></div>
|
|
602
|
+
<div class="mpd-row"><button class="mpd-link" data-x="all">Select all</button><button class="mpd-link" data-x="none">Select none</button></div>
|
|
603
|
+
<div class="mpd-list"></div>
|
|
604
|
+
<div class="mpd-actions"><button class="mp-btn" data-x="rm">Remove filter</button><button class="mp-btn mp-primary" data-x="close">Done</button></div>`);
|
|
605
|
+
const list = el.querySelector('.mpd-list');
|
|
606
|
+
const set = () => new Set(it.include || it.exclude || []);
|
|
607
|
+
const checked = (v) => (it.include ? set().has(v) : !set().has(v));
|
|
608
|
+
const paint = async (search = '') => {
|
|
609
|
+
list.innerHTML = '<div class="mpd-more">Loading…</div>';
|
|
610
|
+
let d;
|
|
611
|
+
try { d = await this.dataset.distinct(it.field, { search, limit: 300 }); } catch (err) { list.innerHTML = `<div class="mpd-more">${esc(err.message)}</div>`; return; }
|
|
612
|
+
list.innerHTML = d.items.map((x, k) => `<label><input type="checkbox" data-k="${k}" ${checked(x.value) ? 'checked' : ''}> <span>${esc(x.label)}</span></label>`).join('')
|
|
613
|
+
+ (d.total > d.items.length ? `<div class="mpd-more">+ ${(d.total - d.items.length).toLocaleString()} more — refine the search</div>` : '');
|
|
614
|
+
list._items = d.items;
|
|
615
|
+
};
|
|
616
|
+
paint();
|
|
617
|
+
el.querySelector('[data-q]').addEventListener('input', (e) => paint(e.target.value));
|
|
618
|
+
list.addEventListener('change', (e) => {
|
|
619
|
+
const k = e.target.dataset.k;
|
|
620
|
+
if (k === undefined) return;
|
|
621
|
+
const v = list._items[+k].value;
|
|
622
|
+
const s = set();
|
|
623
|
+
// include-mode: checked == member. exclude-mode: unchecked == member.
|
|
624
|
+
if (it.include) { if (e.target.checked) s.add(v); else s.delete(v); it.include = [...s]; }
|
|
625
|
+
else { if (e.target.checked) s.delete(v); else s.add(v); it.exclude = [...s]; }
|
|
626
|
+
this._changed();
|
|
627
|
+
chip.querySelector('.mpd-t') && (chip.querySelector('.mpd-t').textContent = this._chipLabel('filters', it));
|
|
628
|
+
});
|
|
629
|
+
el.addEventListener('click', (e) => {
|
|
630
|
+
const x = e.target.closest('[data-x]');
|
|
631
|
+
if (!x) return;
|
|
632
|
+
const m = x.dataset.x;
|
|
633
|
+
if (m === 'all') { delete it.include; it.exclude = []; paint(el.querySelector('[data-q]').value); this._changed(); }
|
|
634
|
+
else if (m === 'none') { delete it.exclude; it.include = []; paint(el.querySelector('[data-q]').value); this._changed(); }
|
|
635
|
+
else if (m === 'rm') { this.spec.filters.splice(i, 1); this._closePop(); this._changed(); }
|
|
636
|
+
else this._closePop();
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
_layoutPop(anchor) {
|
|
641
|
+
const el = this._openPop(anchor, `<h6>Layout (JSON)</h6>
|
|
642
|
+
<textarea style="width:300px;height:200px;font:12px ui-monospace,Consolas,monospace;background:var(--mp-bg);color:var(--mp-fg);border:1px solid var(--mp-line);border-radius:6px" spellcheck="false">${esc(JSON.stringify(this.getSpec(), null, 2))}</textarea>
|
|
643
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span><button class="mp-btn mp-primary" data-x="apply">Apply</button></div>`);
|
|
644
|
+
el.style.left = Math.max(4, this.root.clientWidth - el.offsetWidth - 8) + 'px';
|
|
645
|
+
el.addEventListener('click', (e) => {
|
|
646
|
+
if (!e.target.closest('[data-x="apply"]')) return;
|
|
647
|
+
try { this.setSpec(JSON.parse(el.querySelector('textarea').value)); this._closePop(); }
|
|
648
|
+
catch (err) { el.querySelector('[data-err]').textContent = 'Invalid JSON'; }
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// ---------------------------------------------------------------- export / layouts / formulas
|
|
653
|
+
_exportPop(anchor) {
|
|
654
|
+
const chart = this.spec.options.view === 'chart';
|
|
655
|
+
const el = this._openPop(anchor, `<h6>Export</h6>
|
|
656
|
+
<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="csv">CSV (.csv)</button></div>
|
|
657
|
+
<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="xlsx">Excel (.xlsx)</button></div>
|
|
658
|
+
<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="pdf">PDF (.pdf)</button></div>
|
|
659
|
+
${chart ? '<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="svg">Chart image (.svg)</button></div>' : ''}
|
|
660
|
+
<h6 style="margin-top:8px">Report (saved pivot)</h6>
|
|
661
|
+
<div class="mpd-row"><input type="text" data-t placeholder="Report title…"></div>
|
|
662
|
+
<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="rjson">Report file (.json)</button></div>
|
|
663
|
+
<div class="mpd-row"><button class="mp-btn" style="flex:1;text-align:left" data-e="rhtml">Standalone page (.html)</button></div>
|
|
664
|
+
<div class="mpd-hint" data-err style="color:var(--mp-danger);padding:2px 2px 0"></div>`);
|
|
665
|
+
el.addEventListener('click', (e) => {
|
|
666
|
+
const b = e.target.closest('[data-e]');
|
|
667
|
+
if (!b) return;
|
|
668
|
+
const v = this.viewer;
|
|
669
|
+
try {
|
|
670
|
+
if (!v.getResult()) throw new Error('Nothing to export yet');
|
|
671
|
+
const meta = { title: el.querySelector('[data-t]').value.trim() || undefined };
|
|
672
|
+
const r = ({ csv: () => v.downloadCSV(), xlsx: () => v.downloadXLSX(), pdf: () => v.downloadPDF(), svg: () => v.downloadChartSVG(),
|
|
673
|
+
rjson: () => v.downloadReport(null, meta), rhtml: () => v.downloadReport(null, meta, { html: true, bundleUrl: this.opts.bundleUrl }) })[b.dataset.e]();
|
|
674
|
+
if (r && r.then) { r.then(() => this._closePop(), (err) => { el.querySelector('[data-err]').textContent = err.message; }); return; }
|
|
675
|
+
this._closePop();
|
|
676
|
+
} catch (err) { el.querySelector('[data-err]').textContent = err.message; }
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async _layoutsPop(anchor) {
|
|
681
|
+
if (!this.layouts) return;
|
|
682
|
+
const el = this._openPop(anchor, '<h6>Saved layouts</h6><div class="mpd-list" data-l style="max-height:200px"></div><div class="mpd-row"><input type="text" data-n placeholder="Name this layout…"><button class="mp-btn mp-primary" data-x="save">Save</button></div><div class="mpd-hint" data-err style="color:var(--mp-danger);padding:2px 2px 0"></div>');
|
|
683
|
+
const list = el.querySelector('[data-l]');
|
|
684
|
+
const err = (m) => { el.querySelector('[data-err]').textContent = m || ''; };
|
|
685
|
+
const paint = async () => {
|
|
686
|
+
let items = [];
|
|
687
|
+
try { items = await this.layouts.list(); } catch (e) { err(e.message); }
|
|
688
|
+
list.innerHTML = items.length
|
|
689
|
+
? items.map((l) => `<div class="mpd-lrow" data-id="${esc(l.id)}"><span class="mpd-lname" data-x="load" title="Apply">${esc(l.name)}</span><button data-x="def" title="${l.isDefault ? 'Default layout (click to clear)' : 'Open this layout by default'}">${l.isDefault ? '★' : '☆'}</button><button data-x="del" title="Delete">×</button></div>`).join('')
|
|
690
|
+
: '<div class="mpd-more">No saved layouts yet</div>';
|
|
691
|
+
};
|
|
692
|
+
await paint();
|
|
693
|
+
el.addEventListener('click', async (e) => {
|
|
694
|
+
const x = e.target.closest('[data-x]');
|
|
695
|
+
if (!x) return;
|
|
696
|
+
const id = x.closest('[data-id]') && x.closest('[data-id]').dataset.id;
|
|
697
|
+
err('');
|
|
698
|
+
try {
|
|
699
|
+
if (x.dataset.x === 'save') {
|
|
700
|
+
const name = el.querySelector('[data-n]').value;
|
|
701
|
+
const sid = await this.layouts.save(name, this.getSpec());
|
|
702
|
+
el.querySelector('[data-n]').value = '';
|
|
703
|
+
this.emit('layout-save', { id: sid, name });
|
|
704
|
+
await paint();
|
|
705
|
+
} else if (x.dataset.x === 'load') {
|
|
706
|
+
const spec = await this.layouts.load(id);
|
|
707
|
+
if (spec) { this.setSpec(spec); this.emit('layout-load', { id }); this._closePop(); }
|
|
708
|
+
} else if (x.dataset.x === 'del') { await this.layouts.remove(id); await paint(); }
|
|
709
|
+
else if (x.dataset.x === 'def') {
|
|
710
|
+
const cur = (await this.layouts.list()).find((l) => l.id === id);
|
|
711
|
+
await this.layouts.setDefault(cur && cur.isDefault ? null : id);
|
|
712
|
+
await paint();
|
|
713
|
+
}
|
|
714
|
+
} catch (ex) { err(ex.message); }
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
_fxFieldPop(anchor) {
|
|
719
|
+
const can = this.dataset && typeof this.dataset.addCalculatedField === 'function';
|
|
720
|
+
const el = this._openPop(anchor, `<h6>Calculated field</h6>
|
|
721
|
+
${can ? `<div class="mpd-row"><input type="text" data-n placeholder="Name, e.g. Profit"></div>
|
|
722
|
+
<div class="mpd-row"><input type="text" data-f placeholder="Formula, e.g. Revenue - Cost"></div>
|
|
723
|
+
<div class="mpd-hint" style="padding:2px">Computed per record from numeric fields (use [Field Name] for spaces). Then summarize it like any measure.</div>
|
|
724
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span><button class="mp-btn mp-primary" data-x="add">Add field</button></div>`
|
|
725
|
+
: '<div class="mpd-hint" style="padding:4px 2px">Per-record calculated fields need an in-memory dataset. Add them with <code>addCalculatedField()</code> where the data is loaded, or use a calculated <b>value</b> (fx in Values) which works on any source.</div>'}`);
|
|
726
|
+
if (!can) return;
|
|
727
|
+
el.addEventListener('click', (e) => {
|
|
728
|
+
if (!e.target.closest('[data-x="add"]')) return;
|
|
729
|
+
try {
|
|
730
|
+
this.dataset.addCalculatedField({ name: el.querySelector('[data-n]').value.trim(), formula: el.querySelector('[data-f]').value });
|
|
731
|
+
this._closePop();
|
|
732
|
+
this._renderFields();
|
|
733
|
+
if (this._dlg) this._dlg.refresh();
|
|
734
|
+
this.emit('field-added', { name: el.querySelector('[data-n]').value.trim() });
|
|
735
|
+
} catch (err) { el.querySelector('[data-err]').textContent = err.message; }
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
_fxValuePop(anchor) {
|
|
740
|
+
const el = this._openPop(anchor, `<h6>Calculated value</h6>
|
|
741
|
+
<div class="mpd-row"><input type="text" data-n placeholder="Name, e.g. Margin %"></div>
|
|
742
|
+
<div class="mpd-row"><input type="text" data-f placeholder="Formula, e.g. (sum(Revenue) - sum(Cost)) / sum(Revenue)"></div>
|
|
743
|
+
<div class="mpd-hint" style="padding:2px">Evaluated on the aggregated numbers, so ratios are right at every subtotal and grand total. Functions: sum count avg min max distinct median, abs round if iferror …</div>
|
|
744
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span><button class="mp-btn mp-primary" data-x="add">Add value</button></div>`);
|
|
745
|
+
el.addEventListener('click', (e) => {
|
|
746
|
+
if (!e.target.closest('[data-x="add"]')) return;
|
|
747
|
+
const calc = el.querySelector('[data-f]').value.trim();
|
|
748
|
+
if (!calc) { el.querySelector('[data-err]').textContent = 'Enter a formula'; return; }
|
|
749
|
+
this.spec.values.push({ calc, label: el.querySelector('[data-n]').value.trim() || 'Calculation' });
|
|
750
|
+
this._closePop();
|
|
751
|
+
this._changed();
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// ---------------------------------------------------------------- per-cell formats + print
|
|
756
|
+
_rulesChanged() {
|
|
757
|
+
const rules = this.spec.options.cellRules || [];
|
|
758
|
+
if (!rules.length) delete this.spec.options.cellRules;
|
|
759
|
+
try { this.viewer.setCellRules(rules); } catch (err) { this.emit('error', err); }
|
|
760
|
+
this.emit('change', this.getSpec());
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
_ruleSummary(r) {
|
|
764
|
+
const sc = r.scope || {};
|
|
765
|
+
const vals = this.spec.values || [];
|
|
766
|
+
const vname = sc.value === undefined ? 'all values' : typeof sc.value === 'number' ? ((vals[sc.value] && (vals[sc.value].label || vals[sc.value].field)) || 'value ' + (sc.value + 1)) : sc.value;
|
|
767
|
+
const kind = { any: '', leaf: 'detail cells', sub: 'subtotals', grand: 'grand totals', total: 'all totals' }[sc.kind || 'any'];
|
|
768
|
+
const where = [sc.row ? 'row ' + (sc.row.join(' > ') || 'grand total') : '', sc.col ? 'column ' + (sc.col.join(' > ') || 'grand total') : '', sc.exact ? '(exact)' : ''].filter(Boolean).join(', ');
|
|
769
|
+
const w = r.when ? { empty: 'is empty', notempty: 'has a value', between: `between ${r.when.a} and ${r.when.b}`, outside: `outside ${r.when.a}–${r.when.b}` }[r.when.op] || `${r.when.op} ${r.when.a}` : '';
|
|
770
|
+
const what = [r.style && r.style.background ? 'fill' : '', r.style && r.style.color ? 'text colour' : '', r.style && (r.style.bold || r.style.italic) ? 'font' : '', r.format ? 'number format' : '', r.text != null ? `text "${r.text}"` : ''].filter(Boolean).join(', ');
|
|
771
|
+
return `${[vname, kind, where].filter(Boolean).join(' · ')}${w ? ' · when ' + w : ''} → ${what || 'style'}`;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** Cell formats editor. `prefill` (from a right-click) targets one exact cell. */
|
|
775
|
+
_rulesPop(anchor, prefill) {
|
|
776
|
+
const vals = this.spec.values || [];
|
|
777
|
+
const rules = () => this.spec.options.cellRules || (this.spec.options.cellRules = []);
|
|
778
|
+
const vopts = ['<option value="">All values</option>', ...vals.map((v, i) => `<option value="${i}">${esc(v.label || (v.field ? `${v.agg || 'sum'} of ${v.field}` : 'Calculation'))}</option>`)].join('');
|
|
779
|
+
const el = this._openPop(anchor, `<h6>Cell formats</h6>
|
|
780
|
+
<div class="mpd-list" data-rl style="max-height:130px;margin-bottom:6px"></div>
|
|
781
|
+
<div class="mpd-hint" style="padding:0 0 4px"><b data-title>New rule</b> — rules apply top to bottom; later ones win.</div>
|
|
782
|
+
<div class="mpd-row"><select data-f="value">${vopts}</select>
|
|
783
|
+
<select data-f="kind"><option value="any">Any cell</option><option value="leaf">Detail cells</option><option value="sub">Subtotals</option><option value="grand">Grand totals</option><option value="total">All totals</option></select></div>
|
|
784
|
+
<div class="mpd-row"><input type="text" data-f="row" placeholder="Row path, e.g. East > Widget"><input type="text" data-f="col" placeholder="Column path"></div>
|
|
785
|
+
<div class="mpd-row"><label class="mpd-hint" style="padding:0"><input type="checkbox" data-f="exact"> exactly that row / column only</label></div>
|
|
786
|
+
<div class="mpd-row"><select data-f="op"><option value="">Always</option><option value=">">greater than</option><option value=">=">at least</option><option value="<">less than</option><option value="<=">at most</option><option value="=">equals</option><option value="!=">not equal</option><option value="between">between</option><option value="outside">outside</option><option value="empty">is empty</option></select>
|
|
787
|
+
<input type="number" data-f="a" placeholder="value" style="width:80px"><input type="number" data-f="b" placeholder="and" style="width:80px"></div>
|
|
788
|
+
<div class="mpd-row"><select data-f="fmt"><option value="">Number format: unchanged</option><option value="number">Number</option><option value="integer">Integer</option><option value="currency">Currency</option><option value="percent">Percent</option><option value="compact">Compact</option></select>
|
|
789
|
+
<input type="number" min="0" max="10" data-f="dec" placeholder="decimals" style="width:78px"><input type="text" data-f="prefix" placeholder="prefix" style="width:60px"><input type="text" data-f="suffix" placeholder="suffix" style="width:60px"></div>
|
|
790
|
+
<div class="mpd-row"><input type="text" data-f="text" placeholder="Show this text instead of the number (optional)"></div>
|
|
791
|
+
<div class="mpd-row">
|
|
792
|
+
<label class="mpd-hint" style="padding:0"><input type="checkbox" data-f="usecolor"> Text <input type="color" data-f="color" value="#9c0006"></label>
|
|
793
|
+
<label class="mpd-hint" style="padding:0"><input type="checkbox" data-f="usebg"> Fill <input type="color" data-f="bg" value="#ffc7ce"></label>
|
|
794
|
+
<label class="mpd-hint" style="padding:0"><input type="checkbox" data-f="bold"> Bold</label>
|
|
795
|
+
<label class="mpd-hint" style="padding:0"><input type="checkbox" data-f="italic"> Italic</label>
|
|
796
|
+
<select data-f="font"><option value="">Font: default</option><option value="sans">Sans</option><option value="serif">Serif</option><option value="mono">Mono</option>${(this.opts.fontFamilies || []).map((f) => `<option value="${esc(f)}">${esc(f)}</option>`).join('')}</select>
|
|
797
|
+
<input type="number" min="5" max="96" data-f="size" placeholder="size" style="width:62px">
|
|
798
|
+
<select data-f="align"><option value="">Align: auto</option><option value="left">Left</option><option value="center">Center</option><option value="right">Right</option></select></div>
|
|
799
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span><button class="mp-btn" data-x="cancel" style="display:none">Cancel edit</button><button class="mp-btn mp-primary" data-x="save">Add rule</button></div>`);
|
|
800
|
+
el.style.maxHeight = '78vh'; el.style.overflow = 'auto'; el.style.width = '430px';
|
|
801
|
+
const F = (k) => el.querySelector(`[data-f="${k}"]`);
|
|
802
|
+
const err = (m) => { el.querySelector('[data-err]').textContent = m || ''; };
|
|
803
|
+
let editing = -1;
|
|
804
|
+
const GRAND = '(grand total)';
|
|
805
|
+
const path = (s) => (s.trim() === GRAND ? [] : s.split('>').map((x) => x.trim()).filter(Boolean));
|
|
806
|
+
const unpath = (a) => (!a ? '' : a.length ? a.join(' > ') : GRAND);
|
|
807
|
+
const read = () => {
|
|
808
|
+
const r = { scope: { kind: F('kind').value } };
|
|
809
|
+
if (F('value').value !== '') r.scope.value = Number(F('value').value);
|
|
810
|
+
if (F('row').value.trim()) r.scope.row = path(F('row').value);
|
|
811
|
+
if (F('col').value.trim()) r.scope.col = path(F('col').value);
|
|
812
|
+
if (F('exact').checked) r.scope.exact = true;
|
|
813
|
+
const op = F('op').value;
|
|
814
|
+
if (op) { r.when = { op }; if (op !== 'empty') { r.when.a = F('a').value; if (op === 'between' || op === 'outside') r.when.b = F('b').value; } }
|
|
815
|
+
const fmt = F('fmt').value, dec = F('dec').value, pre = F('prefix').value, suf = F('suffix').value;
|
|
816
|
+
if (fmt || dec !== '' || pre || suf) {
|
|
817
|
+
const o = {};
|
|
818
|
+
if (fmt) o.preset = fmt;
|
|
819
|
+
if (dec !== '') { o.minimumFractionDigits = Number(dec); o.maximumFractionDigits = Number(dec); }
|
|
820
|
+
if (pre) o.prefix = pre;
|
|
821
|
+
if (suf) o.suffix = suf;
|
|
822
|
+
r.format = Object.keys(o).length === 1 && o.preset ? o.preset : o;
|
|
823
|
+
}
|
|
824
|
+
if (F('text').value !== '') r.text = F('text').value;
|
|
825
|
+
const st = {};
|
|
826
|
+
if (F('usecolor').checked) st.color = F('color').value;
|
|
827
|
+
if (F('usebg').checked) st.background = F('bg').value;
|
|
828
|
+
if (F('bold').checked) st.bold = true;
|
|
829
|
+
if (F('italic').checked) st.italic = true;
|
|
830
|
+
if (F('align').value) st.align = F('align').value;
|
|
831
|
+
if (F('font').value) st.font = F('font').value;
|
|
832
|
+
if (F('size').value !== '') st.size = Number(F('size').value);
|
|
833
|
+
if (Object.keys(st).length) r.style = st;
|
|
834
|
+
return r;
|
|
835
|
+
};
|
|
836
|
+
const fill = (r) => {
|
|
837
|
+
const sc = r.scope || {}, st = r.style || {}, f = r.format;
|
|
838
|
+
F('value').value = sc.value === undefined ? '' : String(sc.value);
|
|
839
|
+
F('kind').value = sc.kind || 'any';
|
|
840
|
+
F('row').value = unpath(sc.row); F('col').value = unpath(sc.col);
|
|
841
|
+
F('exact').checked = !!sc.exact;
|
|
842
|
+
F('op').value = r.when ? r.when.op : ''; F('a').value = r.when && r.when.a !== undefined ? r.when.a : ''; F('b').value = r.when && r.when.b !== undefined ? r.when.b : '';
|
|
843
|
+
const fo = typeof f === 'string' ? { preset: f } : (f && typeof f === 'object' ? f : {});
|
|
844
|
+
F('fmt').value = fo.preset || ''; F('dec').value = fo.maximumFractionDigits ?? ''; F('prefix').value = fo.prefix || ''; F('suffix').value = fo.suffix || '';
|
|
845
|
+
F('text').value = r.text ?? '';
|
|
846
|
+
F('usecolor').checked = !!st.color; if (st.color && /^#[0-9a-f]{6}$/i.test(st.color)) F('color').value = st.color;
|
|
847
|
+
F('usebg').checked = !!st.background; if (st.background && /^#[0-9a-f]{6}$/i.test(st.background)) F('bg').value = st.background;
|
|
848
|
+
F('bold').checked = !!st.bold; F('italic').checked = !!st.italic; F('align').value = st.align || '';
|
|
849
|
+
F('font').value = st.font || ''; F('size').value = st.size ?? '';
|
|
850
|
+
};
|
|
851
|
+
const paint = () => {
|
|
852
|
+
const list = el.querySelector('[data-rl]');
|
|
853
|
+
const rs = rules();
|
|
854
|
+
list.innerHTML = rs.length
|
|
855
|
+
? rs.map((r, i) => `<div class="mpd-lrow"><span class="mpd-lname" title="${esc(this._ruleSummary(r))}">${esc(r.name || this._ruleSummary(r))}</span><button class="mp-btn" data-x="edit" data-i="${i}" title="Edit">✎</button><button class="mp-btn" data-x="up" data-i="${i}" title="Move up">↑</button><button class="mp-btn" data-x="del" data-i="${i}" title="Delete">×</button></div>`).join('')
|
|
856
|
+
: '<div class="mpd-hint">No rules yet. Add one below, or right-click any cell to format just that cell.</div>';
|
|
857
|
+
};
|
|
858
|
+
const setEditing = (i) => {
|
|
859
|
+
editing = i;
|
|
860
|
+
el.querySelector('[data-title]').textContent = i < 0 ? 'New rule' : `Editing rule ${i + 1}`;
|
|
861
|
+
el.querySelector('[data-x="save"]').textContent = i < 0 ? 'Add rule' : 'Save rule';
|
|
862
|
+
el.querySelector('[data-x="cancel"]').style.display = i < 0 ? 'none' : '';
|
|
863
|
+
};
|
|
864
|
+
if (prefill) {
|
|
865
|
+
fill({ scope: prefill.scope, style: { bold: false } });
|
|
866
|
+
F('bold').checked = false;
|
|
867
|
+
F('usebg').checked = true;
|
|
868
|
+
el.querySelector('[data-title]').textContent = 'Format this cell';
|
|
869
|
+
}
|
|
870
|
+
paint();
|
|
871
|
+
el.addEventListener('click', (e) => {
|
|
872
|
+
const b = e.target.closest('[data-x]');
|
|
873
|
+
if (!b) return;
|
|
874
|
+
const i = Number(b.dataset.i);
|
|
875
|
+
try {
|
|
876
|
+
err('');
|
|
877
|
+
if (b.dataset.x === 'save') {
|
|
878
|
+
const r = read();
|
|
879
|
+
const next = cleanRules([r])[0]; // validates just this rule
|
|
880
|
+
const rs = rules();
|
|
881
|
+
if (editing >= 0) rs[editing] = next; else rs.push(next);
|
|
882
|
+
this._rulesChanged(); paint(); setEditing(-1);
|
|
883
|
+
} else if (b.dataset.x === 'edit') { fill(rules()[i]); setEditing(i); }
|
|
884
|
+
else if (b.dataset.x === 'cancel') setEditing(-1);
|
|
885
|
+
else if (b.dataset.x === 'del') { rules().splice(i, 1); this._rulesChanged(); paint(); setEditing(-1); }
|
|
886
|
+
else if (b.dataset.x === 'up' && i > 0) { const rs = rules(); [rs[i - 1], rs[i]] = [rs[i], rs[i - 1]]; this._rulesChanged(); paint(); }
|
|
887
|
+
} catch (ex) { err(ex.message.replace(/^Cell rule #\d+: /, '')); }
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
_printPop(anchor) {
|
|
892
|
+
const p = this.spec.options.print || {};
|
|
893
|
+
const el = this._openPop(anchor, `<h6>Print</h6>
|
|
894
|
+
<div class="mpd-row"><input type="text" data-p="title" placeholder="Title" value="${esc(p.title || '')}"></div>
|
|
895
|
+
<div class="mpd-row"><input type="text" data-p="subtitle" placeholder="Subtitle (optional)" value="${esc(p.subtitle || '')}"></div>
|
|
896
|
+
<div class="mpd-row"><input type="text" data-p="footer" placeholder="Footer (optional)" value="${esc(p.footer || '')}"></div>
|
|
897
|
+
<div class="mpd-row"><select data-p="pageSize">${['a4', 'letter', 'a3', 'legal'].map((s) => `<option value="${s}"${(p.pageSize || 'a4') === s ? ' selected' : ''}>${s.toUpperCase()}</option>`).join('')}</select>
|
|
898
|
+
<select data-p="font"><option value="sans"${(p.font || 'sans') === 'sans' ? ' selected' : ''}>Sans</option><option value="serif"${p.font === 'serif' ? ' selected' : ''}>Serif</option><option value="mono"${p.font === 'mono' ? ' selected' : ''}>Mono</option>${(this.opts.fontFamilies || []).map((f) => `<option value="${esc(f)}"${p.font === f ? ' selected' : ''}>${esc(f)}</option>`).join('')}</select>
|
|
899
|
+
<select data-p="orientation"><option value="landscape"${p.orientation !== 'portrait' ? ' selected' : ''}>Landscape</option><option value="portrait"${p.orientation === 'portrait' ? ' selected' : ''}>Portrait</option></select></div>
|
|
900
|
+
<div class="mpd-hint" style="padding:2px">Prints the whole pivot (not just what is on screen) with your cell formats. Choose "Save as PDF" in the print dialog for a file. These settings are saved with layouts and reports.</div>
|
|
901
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span><button class="mp-btn mp-primary" data-x="print">Print…</button></div>`);
|
|
902
|
+
el.addEventListener('click', (e) => {
|
|
903
|
+
if (!e.target.closest('[data-x="print"]')) return;
|
|
904
|
+
const g = (k) => el.querySelector(`[data-p="${k}"]`).value;
|
|
905
|
+
const pr = { pageSize: g('pageSize'), orientation: g('orientation'), font: g('font') };
|
|
906
|
+
for (const k of ['title', 'subtitle', 'footer']) if (g(k).trim()) pr[k] = g(k).trim();
|
|
907
|
+
this.spec.options.print = pr;
|
|
908
|
+
try {
|
|
909
|
+
this.viewer.spec = { ...this.viewer.spec, options: { ...this.viewer.spec.options, print: pr } };
|
|
910
|
+
this.viewer.print();
|
|
911
|
+
this._closePop();
|
|
912
|
+
this.emit('change', this.getSpec());
|
|
913
|
+
} catch (err) { el.querySelector('[data-err]').textContent = err.message; }
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// ---------------------------------------------------------------- saved reports (server or custom store)
|
|
918
|
+
_makeReportStore() {
|
|
919
|
+
const R = this.opts.reports, ds = this.dataset;
|
|
920
|
+
if (R === false) return null;
|
|
921
|
+
if (R && typeof R.save === 'function') return R;
|
|
922
|
+
if (ds && typeof ds.reportStore === 'function' && ds.supportsReports) return ds.reportStore();
|
|
923
|
+
return null;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** Open a saved report document in the designer (spec, cell formats, view state; formula columns are re-created on in-memory data). */
|
|
927
|
+
loadReport(report, ref) {
|
|
928
|
+
const r = parseReport(report);
|
|
929
|
+
if (this.dataset && typeof this.dataset.addCalculatedField === 'function') applyReportFields(this.dataset, r);
|
|
930
|
+
this._renderFields();
|
|
931
|
+
if (r.state) this.viewer.setState(r.state);
|
|
932
|
+
this._cur = ref ? { id: ref.id, version: ref.version, title: r.title } : null;
|
|
933
|
+
this.setSpec(r.spec);
|
|
934
|
+
this.emit('report-load', r);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
async _reportsPop(anchor) {
|
|
938
|
+
const store = this.reports;
|
|
939
|
+
if (!store) return;
|
|
940
|
+
const cur = this._cur;
|
|
941
|
+
const el = this._openPop(anchor, `<h6>Saved reports</h6><div class="mpd-list" data-l style="max-height:230px"></div>
|
|
942
|
+
<div class="mpd-row"><input type="text" data-n placeholder="Report title…" value="${esc(cur ? cur.title : '')}"></div>
|
|
943
|
+
<div class="mpd-row"><label class="mpd-hint" style="padding:0"><input type="checkbox" data-snap checked> include a snapshot of the numbers (opens without data)</label></div>
|
|
944
|
+
<div class="mpd-actions"><span class="mpd-hint" data-err style="flex:1;color:var(--mp-danger);padding:0"></span>
|
|
945
|
+
<button class="mp-btn" data-x="new">Save as new</button><button class="mp-btn mp-primary" data-x="save">${cur ? `Save (v${cur.version + 1})` : 'Save'}</button></div>`);
|
|
946
|
+
el.style.width = '420px';
|
|
947
|
+
const err = (m) => { el.querySelector('[data-err]').textContent = m || ''; };
|
|
948
|
+
const list = el.querySelector('[data-l]');
|
|
949
|
+
const when = (t) => new Date(t).toLocaleString();
|
|
950
|
+
const paint = async () => {
|
|
951
|
+
let items = [];
|
|
952
|
+
try { items = await store.list(); } catch (e) { err(e.message); }
|
|
953
|
+
const canExport = typeof store.exportBytes === 'function', canLink = typeof store.shareUrl === 'function';
|
|
954
|
+
list.innerHTML = items.length ? items.map((r) => `<div class="mpd-lrow" data-id="${esc(r.id)}"><span class="mpd-lname" data-x="open" title="Open · v${r.version} · ${esc(when(r.updated))}${r.author ? ' · ' + esc(r.author) : ''}">${cur && cur.id === r.id ? '● ' : ''}${esc(r.title)} <span class="mpd-hint" style="padding:0">v${r.version}</span></span>
|
|
955
|
+
<button class="mp-btn" data-x="vers" title="Versions">🕘</button>${canExport ? '<button class="mp-btn" data-x="pdf" title="Download PDF (rendered by the server)">PDF</button><button class="mp-btn" data-x="xlsx" title="Download Excel">XLS</button>' : ''}${canLink ? '<button class="mp-btn" data-x="link" title="Copy share link">🔗</button>' : ''}<button class="mp-btn" data-x="del" title="Delete">×</button></div><div data-v="${esc(r.id)}"></div>`).join('')
|
|
956
|
+
: '<div class="mpd-hint">No saved reports yet.</div>';
|
|
957
|
+
};
|
|
958
|
+
await paint();
|
|
959
|
+
const save = async (asNew) => {
|
|
960
|
+
const title = el.querySelector('[data-n]').value.trim() || 'Untitled report';
|
|
961
|
+
const v = this.viewer;
|
|
962
|
+
if (!v.getResult()) throw new Error('Nothing to save yet: run the pivot first');
|
|
963
|
+
const report = v.toReport({ title, snapshot: el.querySelector('[data-snap]').checked });
|
|
964
|
+
const out = await store.save(report, !asNew && cur ? { id: cur.id, baseVersion: cur.version } : {});
|
|
965
|
+
this._cur = { id: out.id, version: out.version, title };
|
|
966
|
+
this.emit('report-save', { id: out.id, version: out.version, title });
|
|
967
|
+
this._closePop();
|
|
968
|
+
};
|
|
969
|
+
el.addEventListener('click', async (e) => {
|
|
970
|
+
const b = e.target.closest('[data-x]');
|
|
971
|
+
if (!b) return;
|
|
972
|
+
const row = b.closest('[data-id]'), id = row && row.dataset.id;
|
|
973
|
+
try {
|
|
974
|
+
err('');
|
|
975
|
+
switch (b.dataset.x) {
|
|
976
|
+
case 'save': await save(false); break;
|
|
977
|
+
case 'new': await save(true); break;
|
|
978
|
+
case 'open': { const r = await store.load(id); const meta = (await store.list()).find((x) => x.id === id); this.loadReport(r, { id, version: meta ? meta.version : 1 }); this._closePop(); break; }
|
|
979
|
+
case 'del': if (confirm('Delete this report and all its versions?')) { await store.remove(id); if (this._cur && this._cur.id === id) this._cur = null; await paint(); } break;
|
|
980
|
+
case 'pdf': case 'xlsx': downloadBlob(await store.exportBytes(id, b.dataset.x), `${(row.querySelector('.mpd-lname').textContent.replace(/ v\d+$/, '').trim() || 'report').replace(/[^\w -]+/g, '')}.${b.dataset.x}`, b.dataset.x === 'pdf' ? 'application/pdf' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); break;
|
|
981
|
+
case 'link': { const url = new URL(store.shareUrl(id), location.href).href; try { await navigator.clipboard.writeText(url); err('Link copied'); } catch { prompt('Share link', url); } break; }
|
|
982
|
+
case 'vers': {
|
|
983
|
+
const box = list.querySelector(`[data-v="${CSS.escape(id)}"]`);
|
|
984
|
+
if (box.innerHTML) { box.innerHTML = ''; break; }
|
|
985
|
+
const vs = await store.versions(id);
|
|
986
|
+
box.innerHTML = vs.map((x) => `<div class="mpd-lrow" style="padding-left:18px"><span class="mpd-lname" data-x="openv" data-v="${x.version}" data-id="${esc(id)}" title="Open this version">v${x.version} · ${esc(when(x.updated))}</span></div>`).join('');
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
case 'openv': { const r = await store.load(b.dataset.id, { version: Number(b.dataset.v) }); const meta = (await store.list()).find((x) => x.id === b.dataset.id); this.loadReport(r, { id: b.dataset.id, version: meta ? meta.version : Number(b.dataset.v) }); this._closePop(); break; }
|
|
990
|
+
default: break;
|
|
991
|
+
}
|
|
992
|
+
} catch (ex) { err(ex.name === 'ConflictError' ? `${ex.message}. Use "Save as new" or reopen the report.` : ex.message); }
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|