@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/expr.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Safe formula language (no eval / new Function, so it works under strict CSP).
|
|
2
|
+
//
|
|
3
|
+
// numbers, + - * / % ^, parentheses, unary minus, comparisons (> < >= <= == !=), && ||
|
|
4
|
+
// functions: abs round floor ceil sqrt ln log10 exp pow min max if iferror
|
|
5
|
+
// references: Revenue [Net Revenue] and, for result formulas, aggregates: sum(Revenue) count() avg([Unit Price])
|
|
6
|
+
//
|
|
7
|
+
// Missing data (null) propagates; divide by zero yields null.
|
|
8
|
+
|
|
9
|
+
export const AGG_FUNCS = ['sum', 'count', 'avg', 'min', 'max', 'distinct', 'median'];
|
|
10
|
+
|
|
11
|
+
export class FormulaError extends Error { constructor(m) { super(m); this.name = 'FormulaError'; } }
|
|
12
|
+
|
|
13
|
+
function tokenize(src) {
|
|
14
|
+
const t = [];
|
|
15
|
+
let i = 0;
|
|
16
|
+
const n = src.length;
|
|
17
|
+
while (i < n) {
|
|
18
|
+
const c = src[i];
|
|
19
|
+
if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { i++; continue; }
|
|
20
|
+
if ((c >= '0' && c <= '9') || (c === '.' && src[i + 1] >= '0' && src[i + 1] <= '9')) {
|
|
21
|
+
let j = i;
|
|
22
|
+
while (j < n && ((src[j] >= '0' && src[j] <= '9') || src[j] === '.')) j++;
|
|
23
|
+
if ((src[j] === 'e' || src[j] === 'E') && /[-+\d]/.test(src[j + 1] || '')) { j += 2; while (j < n && src[j] >= '0' && src[j] <= '9') j++; }
|
|
24
|
+
t.push({ k: 'num', v: parseFloat(src.slice(i, j)) });
|
|
25
|
+
i = j; continue;
|
|
26
|
+
}
|
|
27
|
+
if (c === '[') {
|
|
28
|
+
const j = src.indexOf(']', i);
|
|
29
|
+
if (j < 0) throw new FormulaError('Missing "]"');
|
|
30
|
+
t.push({ k: 'id', v: src.slice(i + 1, j).trim(), br: true });
|
|
31
|
+
i = j + 1; continue;
|
|
32
|
+
}
|
|
33
|
+
if (/[A-Za-z_]/.test(c)) {
|
|
34
|
+
let j = i + 1;
|
|
35
|
+
while (j < n && /[A-Za-z0-9_.]/.test(src[j])) j++;
|
|
36
|
+
t.push({ k: 'id', v: src.slice(i, j) });
|
|
37
|
+
i = j; continue;
|
|
38
|
+
}
|
|
39
|
+
const two = src.slice(i, i + 2);
|
|
40
|
+
if (['>=', '<=', '==', '!=', '&&', '||'].includes(two)) { t.push({ k: 'op', v: two }); i += 2; continue; }
|
|
41
|
+
if ('+-*/%^(),<>'.includes(c)) { t.push({ k: 'op', v: c }); i++; continue; }
|
|
42
|
+
throw new FormulaError(`Unexpected character "${c}"`);
|
|
43
|
+
}
|
|
44
|
+
return t;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parse(src) {
|
|
48
|
+
const toks = tokenize(src);
|
|
49
|
+
let p = 0;
|
|
50
|
+
const peek = () => toks[p];
|
|
51
|
+
const eat = (v) => { const x = toks[p]; if (x && x.k === 'op' && x.v === v) { p++; return true; } return false; };
|
|
52
|
+
const expect = (v) => { if (!eat(v)) throw new FormulaError(`Expected "${v}"`); };
|
|
53
|
+
|
|
54
|
+
const bin = (next, ops) => () => {
|
|
55
|
+
let l = next();
|
|
56
|
+
for (;;) {
|
|
57
|
+
const t = peek();
|
|
58
|
+
if (t && t.k === 'op' && ops.includes(t.v)) { p++; l = { t: 'bin', op: t.v, l, r: next() }; } else return l;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const atom = () => {
|
|
62
|
+
const t = toks[p++];
|
|
63
|
+
if (!t) throw new FormulaError('Unexpected end of formula');
|
|
64
|
+
if (t.k === 'num') return { t: 'num', v: t.v };
|
|
65
|
+
if (t.k === 'id') {
|
|
66
|
+
if (!t.br && peek() && peek().k === 'op' && peek().v === '(') {
|
|
67
|
+
p++;
|
|
68
|
+
const args = [];
|
|
69
|
+
if (!eat(')')) { do args.push(or()); while (eat(',')); expect(')'); }
|
|
70
|
+
return { t: 'call', name: t.v.toLowerCase(), args };
|
|
71
|
+
}
|
|
72
|
+
return { t: 'ref', name: t.v };
|
|
73
|
+
}
|
|
74
|
+
if (t.v === '(') { const e = or(); expect(')'); return e; }
|
|
75
|
+
throw new FormulaError(`Unexpected "${t.v}"`);
|
|
76
|
+
};
|
|
77
|
+
const power = () => { const b = atom(); if (eat('^')) return { t: 'bin', op: '^', l: b, r: unary() }; return b; };
|
|
78
|
+
const unary = () => { if (eat('-')) return { t: 'neg', e: unary() }; if (eat('+')) return unary(); return power(); };
|
|
79
|
+
const mul = bin(unary, ['*', '/', '%']);
|
|
80
|
+
const add = bin(mul, ['+', '-']);
|
|
81
|
+
const cmp = bin(add, ['>', '<', '>=', '<=', '==', '!=']);
|
|
82
|
+
const and = bin(cmp, ['&&']);
|
|
83
|
+
const or = bin(and, ['||']);
|
|
84
|
+
const ast = or();
|
|
85
|
+
if (p < toks.length) throw new FormulaError(`Unexpected "${toks[p].v}"`);
|
|
86
|
+
return ast;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const FN = {
|
|
90
|
+
abs: (a) => Math.abs(a), floor: (a) => Math.floor(a), ceil: (a) => Math.ceil(a),
|
|
91
|
+
sqrt: (a) => (a < 0 ? null : Math.sqrt(a)), ln: (a) => (a <= 0 ? null : Math.log(a)), log10: (a) => (a <= 0 ? null : Math.log10(a)),
|
|
92
|
+
exp: (a) => Math.exp(a), round: (a, d = 0) => { const m = 10 ** d; return Math.round(a * m) / m; }, pow: (a, b) => a ** b,
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Compile a formula. `refs` lists the distinct inputs in first-use order:
|
|
97
|
+
* { kind:'ref', name } plain reference
|
|
98
|
+
* { kind:'agg', fn, field } aggregate call such as sum(Revenue); field '*' for count()
|
|
99
|
+
* `evaluate(values)` takes an array aligned with `refs` (number | null each).
|
|
100
|
+
* @param {string} src
|
|
101
|
+
* @param {{aggregates?: boolean}} [opts] allow aggregate calls (result-level formulas)
|
|
102
|
+
*/
|
|
103
|
+
export function compileFormula(src, opts = {}) {
|
|
104
|
+
const ast = parse(String(src));
|
|
105
|
+
const refs = [];
|
|
106
|
+
const idx = new Map();
|
|
107
|
+
const slot = (key, ref) => { let i = idx.get(key); if (i === undefined) { i = refs.length; refs.push(ref); idx.set(key, i); } return i; };
|
|
108
|
+
|
|
109
|
+
const build = (n) => {
|
|
110
|
+
switch (n.t) {
|
|
111
|
+
case 'num': { const v = n.v; return () => v; }
|
|
112
|
+
case 'ref': { const i = slot('r:' + n.name, { kind: 'ref', name: n.name }); return (v) => v[i]; }
|
|
113
|
+
case 'neg': { const e = build(n.e); return (v) => { const x = e(v); return x === null ? null : -x; }; }
|
|
114
|
+
case 'bin': {
|
|
115
|
+
const l = build(n.l), r = build(n.r), op = n.op;
|
|
116
|
+
if (op === '&&') return (v) => { const a = l(v), b = r(v); return a === null || b === null ? null : a && b ? 1 : 0; };
|
|
117
|
+
if (op === '||') return (v) => { const a = l(v), b = r(v); return a === null || b === null ? null : a || b ? 1 : 0; };
|
|
118
|
+
return (v) => {
|
|
119
|
+
const a = l(v), b = r(v);
|
|
120
|
+
if (a === null || b === null) return null;
|
|
121
|
+
let x;
|
|
122
|
+
switch (op) {
|
|
123
|
+
case '+': x = a + b; break;
|
|
124
|
+
case '-': x = a - b; break;
|
|
125
|
+
case '*': x = a * b; break;
|
|
126
|
+
case '/': if (b === 0) return null; x = a / b; break;
|
|
127
|
+
case '%': if (b === 0) return null; x = a % b; break;
|
|
128
|
+
case '^': x = a ** b; break;
|
|
129
|
+
case '>': return a > b ? 1 : 0;
|
|
130
|
+
case '<': return a < b ? 1 : 0;
|
|
131
|
+
case '>=': return a >= b ? 1 : 0;
|
|
132
|
+
case '<=': return a <= b ? 1 : 0;
|
|
133
|
+
case '==': return a === b ? 1 : 0;
|
|
134
|
+
default: return a !== b ? 1 : 0;
|
|
135
|
+
}
|
|
136
|
+
return x - x === 0 ? x : null;
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
case 'call': {
|
|
140
|
+
const name = n.name;
|
|
141
|
+
if (AGG_FUNCS.includes(name)) {
|
|
142
|
+
if (!opts.aggregates) throw new FormulaError(`${name}() can only be used in a pivot value formula`);
|
|
143
|
+
let field = '*';
|
|
144
|
+
if (n.args.length > 1) throw new FormulaError(`${name}() takes one field`);
|
|
145
|
+
if (n.args.length === 1) {
|
|
146
|
+
if (n.args[0].t !== 'ref') throw new FormulaError(`${name}() expects a field name`);
|
|
147
|
+
field = n.args[0].name;
|
|
148
|
+
} else if (name !== 'count') throw new FormulaError(`${name}() needs a field, e.g. ${name}(Revenue)`);
|
|
149
|
+
const i = slot(`a:${name}:${field}`, { kind: 'agg', fn: name, field });
|
|
150
|
+
return (v) => v[i];
|
|
151
|
+
}
|
|
152
|
+
const args = n.args.map(build);
|
|
153
|
+
if (name === 'if') {
|
|
154
|
+
if (args.length !== 3) throw new FormulaError('if(cond, a, b) takes 3 arguments');
|
|
155
|
+
return (v) => { const c = args[0](v); return c === null ? null : c ? args[1](v) : args[2](v); };
|
|
156
|
+
}
|
|
157
|
+
if (name === 'iferror') {
|
|
158
|
+
if (args.length !== 2) throw new FormulaError('iferror(a, fallback) takes 2 arguments');
|
|
159
|
+
return (v) => { const a = args[0](v); return a === null ? args[1](v) : a; };
|
|
160
|
+
}
|
|
161
|
+
if (name === 'min' || name === 'max') {
|
|
162
|
+
if (!args.length) throw new FormulaError(`${name}() needs arguments`);
|
|
163
|
+
const f = name === 'min' ? Math.min : Math.max;
|
|
164
|
+
return (v) => { let m = null; for (const a of args) { const x = a(v); if (x === null) return null; m = m === null ? x : f(m, x); } return m; };
|
|
165
|
+
}
|
|
166
|
+
const f = FN[name];
|
|
167
|
+
if (!f) throw new FormulaError(`Unknown function "${name}"`);
|
|
168
|
+
return (v) => {
|
|
169
|
+
const xs = args.map((a) => a(v));
|
|
170
|
+
if (xs.some((x) => x === null)) return null;
|
|
171
|
+
const r = f(...xs);
|
|
172
|
+
return r === null || r - r !== 0 ? null : r;
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
default: throw new FormulaError('Bad expression');
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
const fn = build(ast);
|
|
179
|
+
return { refs, evaluate: (vals) => { const r = fn(vals); return r === null || r - r !== 0 ? null : r; } };
|
|
180
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Number formatting presets, cached Intl.NumberFormat instances.
|
|
2
|
+
|
|
3
|
+
export const PRESETS = {
|
|
4
|
+
number: { maximumFractionDigits: 2 },
|
|
5
|
+
integer: { maximumFractionDigits: 0 },
|
|
6
|
+
currency: { style: 'currency', currency: 'USD' },
|
|
7
|
+
percent: { style: 'percent', maximumFractionDigits: 1 },
|
|
8
|
+
compact: { notation: 'compact', maximumFractionDigits: 1 },
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const cache = new Map();
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string|object|Function} fmt preset name, Intl options (+ prefix/suffix), or function
|
|
15
|
+
* @param {string} [locale]
|
|
16
|
+
* @returns {(v:number|null)=>string}
|
|
17
|
+
*/
|
|
18
|
+
export function makeFormatter(fmt, locale) {
|
|
19
|
+
if (typeof fmt === 'function') return fmt;
|
|
20
|
+
const spec = fmt == null ? 'number' : fmt;
|
|
21
|
+
const key = (locale || '') + '|' + (typeof spec === 'string' ? spec : JSON.stringify(spec));
|
|
22
|
+
let f = cache.get(key);
|
|
23
|
+
if (f) return f;
|
|
24
|
+
let opts, prefix = '', suffix = '';
|
|
25
|
+
if (typeof spec === 'string') opts = PRESETS[spec] || PRESETS.number;
|
|
26
|
+
else {
|
|
27
|
+
const { preset, prefix: p, suffix: s, ...rest } = spec;
|
|
28
|
+
opts = { ...(preset ? PRESETS[preset] : {}), ...rest };
|
|
29
|
+
prefix = p || '';
|
|
30
|
+
suffix = s || '';
|
|
31
|
+
}
|
|
32
|
+
let nf;
|
|
33
|
+
try { nf = new Intl.NumberFormat(locale, opts); } catch { nf = new Intl.NumberFormat(locale, PRESETS.number); }
|
|
34
|
+
f = (v) => (v == null || v !== v || v === Infinity || v === -Infinity ? '' : prefix + nf.format(v) + suffix);
|
|
35
|
+
cache.set(key, f);
|
|
36
|
+
return f;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function formatDateLabel(ms) {
|
|
40
|
+
const iso = new Date(ms).toISOString();
|
|
41
|
+
return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : iso.slice(0, 19) + 'Z';
|
|
42
|
+
}
|
package/src/holistic.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// "Holistic" aggregates (distinct count, median) cannot be rolled up from leaf cells, so they get a
|
|
2
|
+
// dedicated pass that tracks state for every (row level x column level) combination at once.
|
|
3
|
+
//
|
|
4
|
+
// distinct : exact. One numeric hash-set entry per distinct (cell, value) pair.
|
|
5
|
+
// median : quantile sketch (relative accuracy 0.1%, DDSketch-style log buckets) that also keeps
|
|
6
|
+
// the exact min/max of each bucket, so data with well-separated values (integers,
|
|
7
|
+
// prices, ...) comes out exact and everything else is within 0.1%.
|
|
8
|
+
//
|
|
9
|
+
// Memory is bounded by `maxEntries` (default 20M) and fails with a PivotLimitError, not a crash.
|
|
10
|
+
|
|
11
|
+
import { CHUNK_SIZE } from './dataset.js';
|
|
12
|
+
import { PivotLimitError } from './errors.js';
|
|
13
|
+
|
|
14
|
+
const ALPHA = 0.001;
|
|
15
|
+
const GAMMA = (1 + ALPHA) / (1 - ALPHA);
|
|
16
|
+
const LG = Math.log(GAMMA);
|
|
17
|
+
const L = 60000;
|
|
18
|
+
const B = 4 * L + 3;
|
|
19
|
+
|
|
20
|
+
function bucketOf(v) {
|
|
21
|
+
if (v === 0) return 2 * L + 1;
|
|
22
|
+
const w = v < 0 ? -v : v;
|
|
23
|
+
let idx = Math.ceil(Math.log(w) / LG);
|
|
24
|
+
if (idx > L) idx = L; else if (idx < -L) idx = -L;
|
|
25
|
+
return v < 0 ? L - idx : 2 * L + 2 + idx + L;
|
|
26
|
+
}
|
|
27
|
+
function repOf(o) {
|
|
28
|
+
if (o === 2 * L + 1) return 0;
|
|
29
|
+
if (o < 2 * L + 1) { const idx = L - o; return -(2 * Math.pow(GAMMA, idx)) / (GAMMA + 1); }
|
|
30
|
+
const idx = o - (2 * L + 2) - L;
|
|
31
|
+
return (2 * Math.pow(GAMMA, idx)) / (GAMMA + 1);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @returns {Promise<Map<number, {maps: Array<Map<number,number>>, colSpace:number[], C:number}>>} keyed by value index
|
|
36
|
+
*/
|
|
37
|
+
function distinctLayout(sub, rowDims, colDims, R, C, colSpace, denseBits) {
|
|
38
|
+
if (!(denseBits > 0)) return null;
|
|
39
|
+
const rowSpace = [1];
|
|
40
|
+
for (let k = 0; k < R; k++) rowSpace.push(rowSpace[k] * rowDims[k].card);
|
|
41
|
+
const np = [];
|
|
42
|
+
let bits = 0;
|
|
43
|
+
for (let rl = 0; rl <= R; rl++) for (let cl = 0; cl <= C; cl++) { const n = rowSpace[rl] * colSpace[cl]; np.push(n); bits += n * sub; }
|
|
44
|
+
if (bits > denseBits) return null;
|
|
45
|
+
return { bits: np.map((n) => new Uint32Array(((n * sub) >>> 5) + 1)), dcnt: np.map((n) => new Int32Array(n)), np };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function medianLayout(st, nRows, rowDims, colDims, R, C, colSpace, denseCells) {
|
|
49
|
+
if (!(denseCells > 0)) return null;
|
|
50
|
+
const rowSpace = [1];
|
|
51
|
+
for (let k = 0; k < R; k++) rowSpace.push(rowSpace[k] * rowDims[k].card);
|
|
52
|
+
const np = [];
|
|
53
|
+
let pairsTotal = 0;
|
|
54
|
+
for (let rl = 0; rl <= R; rl++) for (let cl = 0; cl <= C; cl++) { const n = rowSpace[rl] * colSpace[cl]; np.push(n); pairsTotal += n; }
|
|
55
|
+
if (pairsTotal > denseCells) return null; // cheap exit before scanning the column
|
|
56
|
+
const seen = new Uint8Array(B);
|
|
57
|
+
let left = nRows;
|
|
58
|
+
for (let ci = 0; left > 0; ci++) {
|
|
59
|
+
const a = st.chunks[ci], len = Math.min(CHUNK_SIZE, left);
|
|
60
|
+
left -= len;
|
|
61
|
+
for (let i = 0; i < len; i++) { const x = a[i]; if (x === x) seen[bucketOf(x)] = 1; }
|
|
62
|
+
}
|
|
63
|
+
const lbOf = new Int32Array(B), ob = [];
|
|
64
|
+
for (let o = 0; o < B; o++) if (seen[o]) { lbOf[o] = ob.length; ob.push(o); }
|
|
65
|
+
const nb = Math.max(ob.length, 1);
|
|
66
|
+
if (pairsTotal * nb > denseCells) return null;
|
|
67
|
+
const cn = np.map((n) => new Int32Array(n * nb));
|
|
68
|
+
const mnD = np.map((n) => new Float64Array(n * nb).fill(Infinity));
|
|
69
|
+
const mxD = np.map((n) => new Float64Array(n * nb).fill(-Infinity));
|
|
70
|
+
return { dense: true, lbOf, ob, nb, np, cn, mnD, mxD };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function computeHolistic({ ds, rowDims, colDims, filters, items, nRows, slicer, maxEntries = 20_000_000, denseCells = 12_000_000, denseBits = 400_000_000, scale = (p) => p }) {
|
|
74
|
+
const R = rowDims.length, C = colDims.length, nCombo = (R + 1) * (C + 1);
|
|
75
|
+
const colSpace = [1];
|
|
76
|
+
for (let k = 0; k < C; k++) colSpace.push(colSpace[k] * colDims[k].card);
|
|
77
|
+
let rowSpaceTot = 1;
|
|
78
|
+
for (const d of rowDims) rowSpaceTot *= d.card;
|
|
79
|
+
const pairMax = rowSpaceTot * colSpace[C];
|
|
80
|
+
const states = items.map((it) => {
|
|
81
|
+
const f = ds.getField(it.field);
|
|
82
|
+
const sub = it.agg === 'distinct' ? f.dim.values.length : B;
|
|
83
|
+
if (pairMax * sub > Number.MAX_SAFE_INTEGER) throw new PivotLimitError(`${it.agg}(${it.field}) with these dimensions is too large to index. Use fewer or coarser dimensions.`);
|
|
84
|
+
const st = { it, sub, chunks: it.agg === 'distinct' ? f.dim.chunks : f.meas.chunks };
|
|
85
|
+
if (it.agg === 'distinct') {
|
|
86
|
+
// Fast path: one bit per (pair, value) plus a running count per pair, when the bitmaps fit `denseBits`.
|
|
87
|
+
const bm = distinctLayout(sub, rowDims, colDims, R, C, colSpace, denseBits);
|
|
88
|
+
if (bm) Object.assign(st, bm);
|
|
89
|
+
else st.sets = Array.from({ length: nCombo }, () => new Set());
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
// Fast path: flat typed arrays indexed [bucket][pair] with buckets compacted to the ones that occur.
|
|
93
|
+
// Used when (combos x pairs x occupied buckets) fits `denseCells`; otherwise the Map path below.
|
|
94
|
+
const dense = medianLayout(st, nRows, rowDims, colDims, R, C, colSpace, denseCells);
|
|
95
|
+
if (dense) Object.assign(st, dense);
|
|
96
|
+
else { st.maps = Array.from({ length: nCombo }, () => new Map()); st.cnt = []; st.mn = []; st.mx = []; }
|
|
97
|
+
}
|
|
98
|
+
return st;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const nChunks = Math.ceil(nRows / CHUNK_SIZE);
|
|
102
|
+
const rkp = new Float64Array(R + 1), ckp = new Float64Array(C + 1);
|
|
103
|
+
for (let ci = 0; ci < nChunks; ci++) {
|
|
104
|
+
const len = Math.min(CHUNK_SIZE, nRows - ci * CHUNK_SIZE);
|
|
105
|
+
const rA = rowDims.map((d) => d.store.chunks[ci]);
|
|
106
|
+
const cA = colDims.map((d) => d.store.chunks[ci]);
|
|
107
|
+
const fA = filters.map((f) => f.store.chunks[ci]);
|
|
108
|
+
const sA = states.map((s) => s.chunks[ci]);
|
|
109
|
+
outer:
|
|
110
|
+
for (let i = 0; i < len; i++) {
|
|
111
|
+
for (let f = 0; f < filters.length; f++) if (filters[f].mask[fA[f][i]] !== 1) continue outer;
|
|
112
|
+
for (let k = 0; k < R; k++) { let g = rA[k][i]; const m = rowDims[k].map; if (m !== null) g = m[g]; rkp[k + 1] = rkp[k] * rowDims[k].card + g; }
|
|
113
|
+
for (let k = 0; k < C; k++) { let g = cA[k][i]; const m = colDims[k].map; if (m !== null) g = m[g]; ckp[k + 1] = ckp[k] * colDims[k].card + g; }
|
|
114
|
+
for (let s = 0; s < states.length; s++) {
|
|
115
|
+
const st = states[s];
|
|
116
|
+
if (st.bits || st.sets) {
|
|
117
|
+
const code = sA[s][i];
|
|
118
|
+
if (code === 0) continue;
|
|
119
|
+
const card = st.sub;
|
|
120
|
+
if (st.bits) {
|
|
121
|
+
for (let rl = 0; rl <= R; rl++) {
|
|
122
|
+
for (let cl = 0; cl <= C; cl++) {
|
|
123
|
+
const combo = rl * (C + 1) + cl, pair = rkp[rl] * colSpace[cl] + ckp[cl];
|
|
124
|
+
const bit = pair * card + code, w = bit >>> 5, m = 1 << (bit & 31), arr = st.bits[combo];
|
|
125
|
+
if ((arr[w] & m) === 0) { arr[w] |= m; st.dcnt[combo][pair]++; }
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
for (let rl = 0; rl <= R; rl++) for (let cl = 0; cl <= C; cl++) st.sets[rl * (C + 1) + cl].add((rkp[rl] * colSpace[cl] + ckp[cl]) * card + code);
|
|
131
|
+
} else {
|
|
132
|
+
const x = sA[s][i];
|
|
133
|
+
if (x !== x) continue;
|
|
134
|
+
const o = bucketOf(x);
|
|
135
|
+
if (st.dense) {
|
|
136
|
+
const lb = st.lbOf[o], nb1 = C + 1;
|
|
137
|
+
for (let rl = 0; rl <= R; rl++) {
|
|
138
|
+
for (let cl = 0; cl <= C; cl++) {
|
|
139
|
+
const combo = rl * nb1 + cl;
|
|
140
|
+
const idx = lb * st.np[combo] + (rkp[rl] * colSpace[cl] + ckp[cl]);
|
|
141
|
+
st.cn[combo][idx]++;
|
|
142
|
+
if (x < st.mnD[combo][idx]) st.mnD[combo][idx] = x;
|
|
143
|
+
if (x > st.mxD[combo][idx]) st.mxD[combo][idx] = x;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
for (let rl = 0; rl <= R; rl++) {
|
|
149
|
+
for (let cl = 0; cl <= C; cl++) {
|
|
150
|
+
const m = st.maps[rl * (C + 1) + cl];
|
|
151
|
+
const key = (rkp[rl] * colSpace[cl] + ckp[cl]) * B + o;
|
|
152
|
+
const at = m.get(key);
|
|
153
|
+
if (at === undefined) { m.set(key, st.cnt.length); st.cnt.push(1); st.mn.push(x); st.mx.push(x); }
|
|
154
|
+
else { st.cnt[at]++; if (x < st.mn[at]) st.mn[at] = x; if (x > st.mx[at]) st.mx[at] = x; }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
let entries = 0;
|
|
161
|
+
for (const st of states) entries += st.sets ? st.sets.reduce((a, x) => a + x.size, 0) : st.dense || st.bits ? 0 : st.cnt.length;
|
|
162
|
+
if (entries > maxEntries) throw new PivotLimitError(`distinct/median would track more than ${maxEntries.toLocaleString()} states. Use fewer dimensions, add filters, or drop these aggregates.`);
|
|
163
|
+
await slicer.tick(scale((ci + 1) / nChunks));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// finalise -> per value index: maps of pairKey -> number
|
|
167
|
+
const out = new Map();
|
|
168
|
+
for (const st of states) {
|
|
169
|
+
const maps = [];
|
|
170
|
+
for (let combo = 0; combo < nCombo; combo++) {
|
|
171
|
+
const res = new Map();
|
|
172
|
+
if (st.bits) {
|
|
173
|
+
const d = st.dcnt[combo];
|
|
174
|
+
for (let pair = 0; pair < d.length; pair++) if (d[pair] > 0) res.set(pair, d[pair]);
|
|
175
|
+
st.bits[combo] = st.dcnt[combo] = null;
|
|
176
|
+
} else if (st.sets) {
|
|
177
|
+
for (const v of st.sets[combo]) { const pk = Math.floor(v / st.sub); res.set(pk, (res.get(pk) || 0) + 1); }
|
|
178
|
+
st.sets[combo] = null;
|
|
179
|
+
} else if (st.dense) {
|
|
180
|
+
const np = st.np[combo], nb = st.nb, cn = st.cn[combo], mn = st.mnD[combo], mx = st.mxD[combo], ob = st.ob;
|
|
181
|
+
for (let pair = 0; pair < np; pair++) {
|
|
182
|
+
let n = 0;
|
|
183
|
+
for (let lb = 0; lb < nb; lb++) n += cn[lb * np + pair];
|
|
184
|
+
if (n === 0) continue;
|
|
185
|
+
const pick = (rank) => {
|
|
186
|
+
let acc = 0;
|
|
187
|
+
for (let lb = 0; lb < nb; lb++) {
|
|
188
|
+
const at = lb * np + pair, c = cn[at];
|
|
189
|
+
if (c === 0) continue;
|
|
190
|
+
acc += c;
|
|
191
|
+
if (acc >= rank) {
|
|
192
|
+
if (mn[at] === mx[at]) return mn[at];
|
|
193
|
+
const r = repOf(ob[lb]);
|
|
194
|
+
return r < mn[at] ? mn[at] : r > mx[at] ? mx[at] : r;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return NaN;
|
|
198
|
+
};
|
|
199
|
+
res.set(pair, n % 2 ? pick((n + 1) / 2) : (pick(n / 2) + pick(n / 2 + 1)) / 2);
|
|
200
|
+
}
|
|
201
|
+
st.cn[combo] = st.mnD[combo] = st.mxD[combo] = null;
|
|
202
|
+
} else {
|
|
203
|
+
const byPair = new Map();
|
|
204
|
+
for (const [key, at] of st.maps[combo]) {
|
|
205
|
+
const pk = Math.floor(key / B);
|
|
206
|
+
let a = byPair.get(pk);
|
|
207
|
+
if (!a) byPair.set(pk, (a = []));
|
|
208
|
+
a.push(key - pk * B, at);
|
|
209
|
+
}
|
|
210
|
+
for (const [pk, a] of byPair) {
|
|
211
|
+
const ent = [];
|
|
212
|
+
let n = 0;
|
|
213
|
+
for (let q = 0; q < a.length; q += 2) { ent.push({ o: a[q], at: a[q + 1] }); n += st.cnt[a[q + 1]]; }
|
|
214
|
+
ent.sort((p, q) => p.o - q.o);
|
|
215
|
+
const pick = (rank) => { // 1-based rank
|
|
216
|
+
let acc = 0;
|
|
217
|
+
for (const e of ent) {
|
|
218
|
+
acc += st.cnt[e.at];
|
|
219
|
+
if (acc >= rank) {
|
|
220
|
+
const mn = st.mn[e.at], mx = st.mx[e.at];
|
|
221
|
+
if (mn === mx) return mn;
|
|
222
|
+
const r = repOf(e.o);
|
|
223
|
+
return r < mn ? mn : r > mx ? mx : r;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return NaN;
|
|
227
|
+
};
|
|
228
|
+
res.set(pk, n % 2 ? pick((n + 1) / 2) : (pick(n / 2) + pick(n / 2 + 1)) / 2);
|
|
229
|
+
}
|
|
230
|
+
st.maps[combo] = null;
|
|
231
|
+
}
|
|
232
|
+
maps.push(res);
|
|
233
|
+
}
|
|
234
|
+
out.set(st.it.j, { maps, colSpace, C });
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { PivotSource, PivotSpec, PivotResult, AxisNode, ValueSpec, ChartOptions, ChartModel, LayoutAdapter, ExportOptions, PivotReport, ReportMeta, CellRule, ViewState, PrintOptions } from './core.js';
|
|
2
|
+
type Dataset = PivotSource;
|
|
3
|
+
export * from './core.js';
|
|
4
|
+
|
|
5
|
+
export interface ViewerOptions {
|
|
6
|
+
/** blank header rows reserved under the column headers (the designer uses 1 for its in-grid Rows zone) */
|
|
7
|
+
headerExtraRows?: number;
|
|
8
|
+
/** show the row-dimension names in the grid corner (default true) */
|
|
9
|
+
cornerLabels?: boolean;
|
|
10
|
+
/** embedded TrueType/OpenType fonts for PDF export, by family name */
|
|
11
|
+
pdfFonts?: Record<string, import('./core.js').PdfFontFiles>;
|
|
12
|
+
dataset?: Dataset;
|
|
13
|
+
spec?: PivotSpec;
|
|
14
|
+
rowHeight?: number;
|
|
15
|
+
colWidth?: number;
|
|
16
|
+
rowHeaderWidth?: number;
|
|
17
|
+
theme?: 'light' | 'dark' | 'auto';
|
|
18
|
+
locale?: string;
|
|
19
|
+
grandTotals?: boolean;
|
|
20
|
+
colSubtotals?: boolean;
|
|
21
|
+
expandRows?: boolean | number | 'auto';
|
|
22
|
+
expandCols?: boolean | number | 'auto';
|
|
23
|
+
statusBar?: boolean;
|
|
24
|
+
/** show Expand / Collapse / Export buttons in the status bar */
|
|
25
|
+
actions?: boolean;
|
|
26
|
+
/** double-click a cell to see its source records */
|
|
27
|
+
drill?: boolean;
|
|
28
|
+
drillLimit?: number;
|
|
29
|
+
emptyText?: string;
|
|
30
|
+
maxCells?: number;
|
|
31
|
+
/** 'table' (default) or 'chart' */
|
|
32
|
+
view?: 'table' | 'chart';
|
|
33
|
+
chart?: ChartOptions;
|
|
34
|
+
/** conditional / per-cell format rules (also read from spec.options.cellRules) */
|
|
35
|
+
cellRules?: CellRule[];
|
|
36
|
+
/** initial view state (see getState) */
|
|
37
|
+
state?: ViewState;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface CellInfo {
|
|
41
|
+
rowNode: AxisNode;
|
|
42
|
+
colNode: AxisNode;
|
|
43
|
+
valueIndex: number;
|
|
44
|
+
value: number | null;
|
|
45
|
+
row: string[];
|
|
46
|
+
col: string[];
|
|
47
|
+
measure: ValueSpec;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Off = () => void;
|
|
51
|
+
|
|
52
|
+
export class PivotViewer {
|
|
53
|
+
constructor(container: HTMLElement | string, options?: ViewerOptions);
|
|
54
|
+
readonly dataset: Dataset | null;
|
|
55
|
+
setData(dataset: Dataset): Promise<PivotResult | null>;
|
|
56
|
+
setSpec(spec: PivotSpec): Promise<PivotResult | null>;
|
|
57
|
+
getSpec(): PivotSpec;
|
|
58
|
+
getResult(): PivotResult | null;
|
|
59
|
+
setResult(result: PivotResult): void;
|
|
60
|
+
setOptions(options: Partial<ViewerOptions>): void;
|
|
61
|
+
refresh(): Promise<PivotResult | null>;
|
|
62
|
+
expandAll(axis?: 'rows' | 'cols'): void;
|
|
63
|
+
collapseAll(axis?: 'rows' | 'cols'): void;
|
|
64
|
+
expandToLevel(level: number, axis?: 'rows' | 'cols'): void;
|
|
65
|
+
sortByColumn(columnIndex: number, dir?: 'asc' | 'desc' | null): void;
|
|
66
|
+
drill(rowIndex: number, columnIndex: number): Promise<void>;
|
|
67
|
+
exportCSV(opts?: { subtotals?: boolean; grandTotals?: boolean; delimiter?: string }): string;
|
|
68
|
+
downloadCSV(filename?: string, opts?: { subtotals?: boolean; grandTotals?: boolean; delimiter?: string }): void;
|
|
69
|
+
exportXLSX(opts?: ExportOptions & { sheetName?: string }): Uint8Array;
|
|
70
|
+
exportPDF(opts?: ExportOptions & { title?: string; pageSize?: 'a4' | 'letter'; orientation?: 'landscape' | 'portrait'; locale?: string }): Uint8Array;
|
|
71
|
+
downloadXLSX(filename?: string, opts?: ExportOptions & { sheetName?: string }): void;
|
|
72
|
+
downloadPDF(filename?: string, opts?: ExportOptions & { title?: string; locale?: string }): void;
|
|
73
|
+
downloadChartSVG(filename?: string): void;
|
|
74
|
+
setView(view: 'table' | 'chart'): void;
|
|
75
|
+
getView(): 'table' | 'chart';
|
|
76
|
+
setChartOptions(opts: ChartOptions): void;
|
|
77
|
+
/** current pivot (spec, view and a snapshot of the numbers) as a portable report */
|
|
78
|
+
toReport(meta?: ReportMeta): PivotReport;
|
|
79
|
+
getCellRules(): CellRule[];
|
|
80
|
+
/** validates (throws PivotError), re-renders, stores in the spec so layouts/reports keep them */
|
|
81
|
+
setCellRules(rules: CellRule[]): void;
|
|
82
|
+
getState(): ViewState;
|
|
83
|
+
setState(state: ViewState | null): void;
|
|
84
|
+
/** open the browser print dialog for the whole pivot (and chart); defaults from spec.options.print */
|
|
85
|
+
print(opts?: PrintOptions): string;
|
|
86
|
+
toPrintHTML(opts?: PrintOptions): string;
|
|
87
|
+
/** download as .report.json, or as a standalone .html page (needs the browser bundle via <script> or bundleUrl) */
|
|
88
|
+
downloadReport(filename?: string | null, meta?: ReportMeta, opts?: { html?: boolean; bundleUrl?: string }): Promise<void>;
|
|
89
|
+
on(event: 'compute-start', fn: (e: { spec: PivotSpec }) => void): Off;
|
|
90
|
+
on(event: 'compute-end', fn: (r: PivotResult) => void): Off;
|
|
91
|
+
on(event: 'cellclick', fn: (e: CellInfo) => void): Off;
|
|
92
|
+
on(event: 'drill', fn: (e: CellInfo & { rows: any[]; total: number }) => void): Off;
|
|
93
|
+
on(event: 'cellcontext', fn: (e: CellInfo & { event: MouseEvent; clientX: number; clientY: number }) => void): Off;
|
|
94
|
+
on(event: 'rules', fn: (rules: CellRule[]) => void): Off;
|
|
95
|
+
on(event: 'view', fn: (e: { view: 'table' | 'chart' }) => void): Off;
|
|
96
|
+
on(event: 'chartclick', fn: (e: any) => void): Off;
|
|
97
|
+
on(event: 'toggle' | 'sort' | 'render' | 'cancel' | 'rowclick', fn: (e: any) => void): Off;
|
|
98
|
+
on(event: 'error', fn: (e: Error) => void): Off;
|
|
99
|
+
destroy(): void;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface DesignerOptions {
|
|
103
|
+
/** where the Rows / Columns drop zones live: 'grid' (default, in the grid's top-left corner like mdg-pivot) or 'top' (all four zones in a strip above the grid) */
|
|
104
|
+
fieldZones?: 'grid' | 'top';
|
|
105
|
+
/** saved reports: a store (e.g. LocalStorageReportStore), false to hide the menu; a RemoteDataset with server reports uses the server */
|
|
106
|
+
reports?: false | import('./core.js').ReportStoreApi;
|
|
107
|
+
/** font families offered in the cell-format and print editors */
|
|
108
|
+
fontFamilies?: string[];
|
|
109
|
+
dataset?: Dataset;
|
|
110
|
+
spec?: PivotSpec;
|
|
111
|
+
autoUpdate?: boolean;
|
|
112
|
+
theme?: 'light' | 'dark' | 'auto';
|
|
113
|
+
viewerOptions?: ViewerOptions;
|
|
114
|
+
/** saved layouts: true (browser localStorage, default), false, or a LayoutAdapter. A RemoteDataset with server layouts uses the server. */
|
|
115
|
+
layouts?: boolean | LayoutAdapter;
|
|
116
|
+
/** localStorage namespace for saved layouts */
|
|
117
|
+
layoutsKey?: string;
|
|
118
|
+
/** URL of pivotjet.min.js, used by Export > Standalone page when not loaded via <script> */
|
|
119
|
+
bundleUrl?: string;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export class PivotDesigner {
|
|
123
|
+
constructor(container: HTMLElement | string, options?: DesignerOptions);
|
|
124
|
+
getSpec(): PivotSpec;
|
|
125
|
+
setSpec(spec: PivotSpec): void;
|
|
126
|
+
setDataset(dataset: Dataset): void;
|
|
127
|
+
getViewer(): PivotViewer;
|
|
128
|
+
/** open the Configure fields (columns / rows / values) or Configure filters dialog */
|
|
129
|
+
openConfigDialog(mode?: 'fields' | 'filters'): void;
|
|
130
|
+
/** open a saved report document (spec, cell formats, view state; formula columns are re-created on in-memory data) */
|
|
131
|
+
loadReport(report: PivotReport | string, ref?: { id: string; version: number }): void;
|
|
132
|
+
refresh(): Promise<PivotResult | null>;
|
|
133
|
+
on(event: 'change', fn: (spec: PivotSpec) => void): Off;
|
|
134
|
+
on(event: 'compute-end', fn: (r: PivotResult) => void): Off;
|
|
135
|
+
on(event: 'cellclick', fn: (e: CellInfo) => void): Off;
|
|
136
|
+
on(event: 'layout-save' | 'layout-load' | 'field-added' | 'drill' | 'error', fn: (e: any) => void): Off;
|
|
137
|
+
destroy(): void;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export class PivotChart {
|
|
141
|
+
constructor(container: HTMLElement | string, opts?: ChartOptions & { result?: PivotResult; height?: number | string });
|
|
142
|
+
setResult(result: PivotResult): void;
|
|
143
|
+
setOptions(opts: ChartOptions): void;
|
|
144
|
+
getModel(): ChartModel | null;
|
|
145
|
+
toSVG(): string;
|
|
146
|
+
on(event: 'pointclick' | 'legendtoggle', fn: (e: any) => void): Off;
|
|
147
|
+
destroy(): void;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Render a saved report. Live (recomputed from `dataset`) when a dataset is given, otherwise from the embedded snapshot.
|
|
152
|
+
*/
|
|
153
|
+
export function renderReport(container: HTMLElement | string, report: PivotReport | string, options?: ViewerOptions & { dataset?: Dataset; mode?: 'auto' | 'live' | 'snapshot' }): PivotViewer;
|
|
154
|
+
|
|
155
|
+
export function injectStyles(): void;
|
package/src/index.js
ADDED