@salmonui/pivot-table 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +49 -2
  3. package/dist/engine/csv.d.ts +12 -0
  4. package/dist/engine/csv.d.ts.map +1 -0
  5. package/dist/engine/csv.js +93 -0
  6. package/dist/engine/csv.js.map +1 -0
  7. package/dist/engine/engine.d.ts +103 -0
  8. package/dist/engine/engine.d.ts.map +1 -0
  9. package/dist/engine/engine.js +1851 -0
  10. package/dist/engine/engine.js.map +1 -0
  11. package/dist/engine/fields.d.ts +59 -0
  12. package/dist/engine/fields.d.ts.map +1 -0
  13. package/dist/engine/fields.js +293 -0
  14. package/dist/engine/fields.js.map +1 -0
  15. package/dist/engine/formula.d.ts +29 -0
  16. package/dist/engine/formula.d.ts.map +1 -0
  17. package/dist/engine/formula.js +286 -0
  18. package/dist/engine/formula.js.map +1 -0
  19. package/dist/engine/hash.d.ts +8 -0
  20. package/dist/engine/hash.d.ts.map +1 -0
  21. package/dist/engine/hash.js +71 -0
  22. package/dist/engine/hash.js.map +1 -0
  23. package/dist/engine/index.d.ts +9 -0
  24. package/dist/engine/index.d.ts.map +1 -0
  25. package/dist/engine/index.js +12 -0
  26. package/dist/engine/index.js.map +1 -0
  27. package/dist/engine/labels.d.ts +24 -0
  28. package/dist/engine/labels.d.ts.map +1 -0
  29. package/dist/engine/labels.js +47 -0
  30. package/dist/engine/labels.js.map +1 -0
  31. package/dist/engine/model.d.ts +11 -0
  32. package/dist/engine/model.d.ts.map +1 -0
  33. package/dist/engine/model.js +76 -0
  34. package/dist/engine/model.js.map +1 -0
  35. package/dist/engine/types.d.ts +252 -0
  36. package/dist/engine/types.d.ts.map +1 -0
  37. package/dist/engine/types.js +8 -0
  38. package/dist/engine/types.js.map +1 -0
  39. package/dist/engine/worker-host.d.ts +42 -0
  40. package/dist/engine/worker-host.d.ts.map +1 -0
  41. package/dist/engine/worker-host.js +126 -0
  42. package/dist/engine/worker-host.js.map +1 -0
  43. package/dist/engine/worker-protocol.d.ts +105 -0
  44. package/dist/engine/worker-protocol.d.ts.map +1 -0
  45. package/dist/engine/worker-protocol.js +66 -0
  46. package/dist/engine/worker-protocol.js.map +1 -0
  47. package/dist/engine/worker.d.ts +5 -0
  48. package/dist/engine/worker.d.ts.map +1 -0
  49. package/dist/engine/worker.js +79 -0
  50. package/dist/engine/worker.js.map +1 -0
  51. package/dist/pivot-table/PivotAxisBar.d.ts +17 -0
  52. package/dist/pivot-table/PivotAxisBar.d.ts.map +1 -0
  53. package/dist/pivot-table/PivotAxisBar.js +68 -0
  54. package/dist/pivot-table/PivotAxisBar.js.map +1 -0
  55. package/dist/pivot-table/PivotFieldList.d.ts +23 -0
  56. package/dist/pivot-table/PivotFieldList.d.ts.map +1 -0
  57. package/dist/pivot-table/PivotFieldList.js +106 -0
  58. package/dist/pivot-table/PivotFieldList.js.map +1 -0
  59. package/dist/pivot-table/PivotTable.d.ts +91 -0
  60. package/dist/pivot-table/PivotTable.d.ts.map +1 -0
  61. package/dist/pivot-table/PivotTable.js +320 -0
  62. package/dist/pivot-table/PivotTable.js.map +1 -0
  63. package/dist/pivot-table/PivotToolbar.d.ts +21 -0
  64. package/dist/pivot-table/PivotToolbar.d.ts.map +1 -0
  65. package/dist/pivot-table/PivotToolbar.js +102 -0
  66. package/dist/pivot-table/PivotToolbar.js.map +1 -0
  67. package/dist/pivot-table/chart-view.d.ts +48 -0
  68. package/dist/pivot-table/chart-view.d.ts.map +1 -0
  69. package/dist/pivot-table/chart-view.js +84 -0
  70. package/dist/pivot-table/chart-view.js.map +1 -0
  71. package/dist/pivot-table/chart.d.ts +122 -0
  72. package/dist/pivot-table/chart.d.ts.map +1 -0
  73. package/dist/pivot-table/chart.js +207 -0
  74. package/dist/pivot-table/chart.js.map +1 -0
  75. package/dist/pivot-table/columns.d.ts +49 -0
  76. package/dist/pivot-table/columns.d.ts.map +1 -0
  77. package/dist/pivot-table/columns.js +279 -0
  78. package/dist/pivot-table/columns.js.map +1 -0
  79. package/dist/pivot-table/controller.d.ts +164 -0
  80. package/dist/pivot-table/controller.d.ts.map +1 -0
  81. package/dist/pivot-table/controller.js +691 -0
  82. package/dist/pivot-table/controller.js.map +1 -0
  83. package/dist/pivot-table/default-text.d.ts +167 -0
  84. package/dist/pivot-table/default-text.d.ts.map +1 -0
  85. package/dist/pivot-table/default-text.js +55 -0
  86. package/dist/pivot-table/default-text.js.map +1 -0
  87. package/dist/pivot-table/dialogs.d.ts +69 -0
  88. package/dist/pivot-table/dialogs.d.ts.map +1 -0
  89. package/dist/pivot-table/dialogs.js +409 -0
  90. package/dist/pivot-table/dialogs.js.map +1 -0
  91. package/dist/pivot-table/export-impl.d.ts +11 -0
  92. package/dist/pivot-table/export-impl.d.ts.map +1 -0
  93. package/dist/pivot-table/export-impl.js +175 -0
  94. package/dist/pivot-table/export-impl.js.map +1 -0
  95. package/dist/pivot-table/export.d.ts +36 -0
  96. package/dist/pivot-table/export.d.ts.map +1 -0
  97. package/dist/pivot-table/export.js +6 -0
  98. package/dist/pivot-table/export.js.map +1 -0
  99. package/dist/pivot-table/field-item.d.ts +42 -0
  100. package/dist/pivot-table/field-item.d.ts.map +1 -0
  101. package/dist/pivot-table/field-item.js +159 -0
  102. package/dist/pivot-table/field-item.js.map +1 -0
  103. package/dist/pivot-table/field-menu.d.ts +26 -0
  104. package/dist/pivot-table/field-menu.d.ts.map +1 -0
  105. package/dist/pivot-table/field-menu.js +94 -0
  106. package/dist/pivot-table/field-menu.js.map +1 -0
  107. package/dist/pivot-table/grid-model.d.ts +54 -0
  108. package/dist/pivot-table/grid-model.d.ts.map +1 -0
  109. package/dist/pivot-table/grid-model.js +154 -0
  110. package/dist/pivot-table/grid-model.js.map +1 -0
  111. package/dist/pivot-table/locale.d.ts +139 -0
  112. package/dist/pivot-table/locale.d.ts.map +1 -0
  113. package/dist/pivot-table/locale.js +125 -0
  114. package/dist/pivot-table/locale.js.map +1 -0
  115. package/dist/pivot-table/menu-popup.d.ts +11 -0
  116. package/dist/pivot-table/menu-popup.d.ts.map +1 -0
  117. package/dist/pivot-table/menu-popup.js +17 -0
  118. package/dist/pivot-table/menu-popup.js.map +1 -0
  119. package/dist/pivot-table/model-ops.d.ts +27 -0
  120. package/dist/pivot-table/model-ops.d.ts.map +1 -0
  121. package/dist/pivot-table/model-ops.js +115 -0
  122. package/dist/pivot-table/model-ops.js.map +1 -0
  123. package/dist/pivot-table/state.d.ts +6 -0
  124. package/dist/pivot-table/state.d.ts.map +1 -0
  125. package/dist/pivot-table/state.js +61 -0
  126. package/dist/pivot-table/state.js.map +1 -0
  127. package/dist/pivot-table/types.d.ts +330 -0
  128. package/dist/pivot-table/types.d.ts.map +1 -0
  129. package/dist/pivot-table/types.js +4 -0
  130. package/dist/pivot-table/types.js.map +1 -0
  131. package/dist/pivot-table/usePivot.d.ts +11 -0
  132. package/dist/pivot-table/usePivot.d.ts.map +1 -0
  133. package/dist/pivot-table/usePivot.js +41 -0
  134. package/dist/pivot-table/usePivot.js.map +1 -0
  135. package/dist/pivot-table/windowed.d.ts +147 -0
  136. package/dist/pivot-table/windowed.d.ts.map +1 -0
  137. package/dist/pivot-table/windowed.js +265 -0
  138. package/dist/pivot-table/windowed.js.map +1 -0
  139. package/dist/pivot-table-chart.d.ts +3 -0
  140. package/dist/pivot-table-chart.d.ts.map +1 -0
  141. package/dist/pivot-table-chart.js +8 -0
  142. package/dist/pivot-table-chart.js.map +1 -0
  143. package/dist/pivot-table.css +4762 -0
  144. package/dist/pivot-table.d.ts +19 -0
  145. package/dist/pivot-table.d.ts.map +1 -0
  146. package/dist/pivot-table.js +18 -0
  147. package/dist/pivot-table.js.map +1 -0
  148. package/package.json +64 -4
@@ -0,0 +1,1851 @@
1
+ // Pivot engine: field index -> group transform ->
2
+ // member, label and value filters -> bucket (tuple ids per axis) ->
3
+ // mergeable aggregate states in typed arrays -> calculated fields -> show
4
+ // values as -> sort -> layout. DOM-free, zero dependencies, Worker-safe.
5
+ //
6
+ // Aggregation model: every row node of the row tree owns a "profile", the
7
+ // states of that node against every column node (all column depths at
8
+ // once). Visible frontier nodes (collapsed or innermost) build their profile
9
+ // from their own units; expanded nodes and totals merge their children's
10
+ // profiles, so subtotals, grand totals, column drill and collapse never scan
11
+ // raw rows, and drilling a row member scans only that member's units.
12
+ // Units are raw rows, or pre-aggregated records (one per distinct row x
13
+ // column leaf tuple) when that is guaranteed to compress at least 4x (data
14
+ // compression; average and distinct count stay exact).
15
+ import { compileFormula } from './formula.js';
16
+ import { BLANK_LABEL, buildFieldIndex, buildLevel, encodeRow, getterOf, inferType, levelNames, memberRanks, numberFormat, numbersOf, } from './fields.js';
17
+ import { createPairMap } from './hash.js';
18
+ import { normalizePivotModel } from './model.js';
19
+ import { ENGINE_LABELS } from './labels.js';
20
+ // Measure kinds and their state widths (after the shared row count slot).
21
+ const SUM = 0;
22
+ const PRODUCT = 1;
23
+ const COUNT = 2;
24
+ const MIN = 3;
25
+ const MAX = 4;
26
+ const AVG = 5;
27
+ const VAR = 6;
28
+ const CUSTOM = 7;
29
+ const LAZY = 8;
30
+ const WIDTH = [2, 2, 1, 2, 2, 2, 3, 1, 0];
31
+ const KIND = {
32
+ sum: SUM,
33
+ product: PRODUCT,
34
+ count: COUNT,
35
+ distinctCount: LAZY,
36
+ min: MIN,
37
+ max: MAX,
38
+ average: AVG,
39
+ median: LAZY,
40
+ populationStdev: VAR,
41
+ sampleStdev: VAR,
42
+ populationVar: VAR,
43
+ sampleVar: VAR,
44
+ custom: CUSTOM,
45
+ };
46
+ const EMPTY_PROFILE = { cols: new Int32Array(0), st: new Float64Array(0), cust: null };
47
+ const DESC_KIND = ['member', 'subtotal', 'grandTotal', 'value'];
48
+ const CELL_KIND = ['value', 'subtotal', 'grandTotal', 'subtotal'];
49
+ const PERCENT = new Set(['percentOfGrandTotal', 'percentOfColumnTotal', 'percentOfRowTotal', 'percentOfParentTotal', 'percentOfParentColumnTotal', 'percentOfParentRowTotal', 'percentOfRunningTotal', 'percentOfDifferenceFrom']);
50
+ const now = (() => {
51
+ const p = globalThis.performance;
52
+ return p ? () => p.now() : () => Date.now();
53
+ })();
54
+ export function drain(gen) {
55
+ for (;;) {
56
+ const r = gen.next();
57
+ if (r.done)
58
+ return r.value;
59
+ }
60
+ }
61
+ const json = (v) => JSON.stringify(v ?? null);
62
+ function compareValue(op, v, a, b) {
63
+ switch (op) {
64
+ case 'equal':
65
+ return v === a;
66
+ case 'notEqual':
67
+ return v !== a;
68
+ case 'greaterThan':
69
+ return v > a;
70
+ case 'greaterThanOrEqual':
71
+ return v >= a;
72
+ case 'lessThan':
73
+ return v < a;
74
+ case 'lessThanOrEqual':
75
+ return v <= a;
76
+ case 'between':
77
+ return v >= Math.min(a, b ?? a) && v <= Math.max(a, b ?? a);
78
+ case 'notBetween':
79
+ return v < Math.min(a, b ?? a) || v > Math.max(a, b ?? a);
80
+ default:
81
+ return true;
82
+ }
83
+ }
84
+ /** Whether a pivot value operator matches (conditional formats reuse it). */
85
+ export const matchesValueOperator = compareValue;
86
+ export function createPivotCore(options) {
87
+ const locale = options.locale ?? 'en-US';
88
+ const collator = new Intl.Collator(locale, { numeric: true });
89
+ const custom = options.customAggregates ?? {};
90
+ const text = options.text ?? {};
91
+ const fmtCache = new Map();
92
+ let rows = options.data;
93
+ let defs = new Map();
94
+ let fieldOrder = [];
95
+ const setDefs = () => {
96
+ defs = new Map();
97
+ const list = (options.fields ?? []);
98
+ for (const d of list)
99
+ defs.set(d.field, d);
100
+ fieldOrder = list.map((d) => d.field);
101
+ if (!options.fields) {
102
+ const seen = new Set();
103
+ for (let i = 0; i < rows.length && i < 50; i++) {
104
+ const r = rows[i];
105
+ if (r && typeof r === 'object')
106
+ for (const k of Object.keys(r))
107
+ if (!seen.has(k))
108
+ seen.add(k), fieldOrder.push(k);
109
+ }
110
+ }
111
+ };
112
+ setDefs();
113
+ const fieldIdx = new Map();
114
+ const numCache = new Map();
115
+ const levelCache = new Map();
116
+ const axisCache = new Map();
117
+ const typeOf = (f) => defs.get(f)?.type ?? inferType(rows, getterOf(defs.get(f), f));
118
+ function* fieldIndex(f) {
119
+ let idx = fieldIdx.get(f);
120
+ if (!idx)
121
+ fieldIdx.set(f, (idx = yield* buildFieldIndex(rows, f, typeOf(f), getterOf(defs.get(f), f))));
122
+ return idx;
123
+ }
124
+ const numbers = (f) => {
125
+ let n = numCache.get(f);
126
+ if (!n)
127
+ numCache.set(f, (n = numbersOf(rows, getterOf(defs.get(f), f))));
128
+ return n;
129
+ };
130
+ let model = normalizePivotModel(options.model);
131
+ let env = { locale, formats: model.formats, cache: fmtCache };
132
+ function* levelsOf(field) {
133
+ const g = model.groups[field];
134
+ const names = levelNames(field, g);
135
+ const idx = yield* fieldIndex(field);
136
+ const out = [];
137
+ names.forEach((name, k) => {
138
+ const part = g?.kind === 'date' ? g.parts[k] : undefined;
139
+ const sig = `${name}\u0000${json(g)}\u0000${part ?? ''}\u0000${json(model.formats[field])}`;
140
+ let level = levelCache.get(sig);
141
+ if (!level || level.base !== idx)
142
+ levelCache.set(sig, (level = buildLevel(env, name, idx, g, part)));
143
+ out.push(level);
144
+ });
145
+ return out;
146
+ }
147
+ function* buildAxis(fields) {
148
+ const levels = [];
149
+ const owners = [];
150
+ for (const f of fields)
151
+ for (const l of yield* levelsOf(f.field))
152
+ levels.push(l), owners.push(f);
153
+ const sig = levels.map((l) => l.signature).join('\u0001');
154
+ const cached = axisCache.get(sig);
155
+ if (cached && cached.leaf.length === rows.length && levels.every((l, i) => cached.levels[i] === l))
156
+ return cached;
157
+ const n = rows.length;
158
+ const ax = { sig, levels, fields: owners, D: levels.length, leaf: new Int32Array(n), parent: [-1], member: [-1], depth: [0], kids: [], map: createPairMap(), top: [] };
159
+ const ids = levels.map((l) => l.ids);
160
+ const D = levels.length;
161
+ for (let i = 0; i < n; i++) {
162
+ let node = 0;
163
+ for (let l = 0; l < D; l++)
164
+ node = childOf(ax, node, ids[l][i], true);
165
+ ax.leaf[i] = node;
166
+ if ((i & 0x3ffff) === 0x3ffff)
167
+ yield i;
168
+ }
169
+ if (axisCache.size > 6)
170
+ axisCache.delete(axisCache.keys().next().value);
171
+ axisCache.set(sig, ax);
172
+ return ax;
173
+ }
174
+ // --- derived state of the current model
175
+ let rowAx;
176
+ let colAx;
177
+ let measures = [];
178
+ let stride = 1;
179
+ let customCount = 0;
180
+ let values = [];
181
+ let errors = [];
182
+ let mask = null;
183
+ let excluded = new Set();
184
+ let units = null;
185
+ let view = null;
186
+ let rawView = null;
187
+ let colRows = new Int32Array(1);
188
+ let profiles = [];
189
+ let lazy = new Map();
190
+ let kidsCache = new Map();
191
+ let sigs = { mask: '', base: '', sort: '' };
192
+ let lastFilterBy = {};
193
+ let rankCache = new Map();
194
+ const stats = { full: 0, incremental: 0 };
195
+ let filterLevels = [];
196
+ const reset = () => {
197
+ live = null;
198
+ fieldIdx.clear();
199
+ numCache.clear();
200
+ levelCache.clear();
201
+ axisCache.clear();
202
+ rankCache.clear();
203
+ sigs = { mask: '', base: '', sort: '' };
204
+ view = rawView = null;
205
+ profiles = [];
206
+ lazy = new Map();
207
+ kidsCache = new Map();
208
+ };
209
+ // --- measures
210
+ const measureOf = (agg, field, customId) => {
211
+ const key = `${agg}\u0000${field}\u0000${customId ?? ''}`;
212
+ const found = measures.findIndex((m) => m.key === key);
213
+ if (found !== -1)
214
+ return found;
215
+ const idx = drain(fieldIndex(field));
216
+ const kind = agg === 'custom' && !(customId && custom[customId]) ? COUNT : KIND[agg];
217
+ const m = {
218
+ key,
219
+ agg,
220
+ field,
221
+ kind,
222
+ off: stride,
223
+ num: kind === COUNT || kind === CUSTOM || (kind === LAZY && agg === 'distinctCount') ? null : numbers(field),
224
+ idx,
225
+ blank: idx.map.get(undefined) ?? -1,
226
+ custom: kind === CUSTOM ? custom[customId] : null,
227
+ ci: kind === CUSTOM ? customCount++ : -1,
228
+ };
229
+ stride += WIDTH[kind];
230
+ measures.push(m);
231
+ return measures.length - 1;
232
+ };
233
+ function setupMeasures() {
234
+ measures = [];
235
+ stride = 1;
236
+ customCount = 0;
237
+ errors = [];
238
+ const fieldNames = fieldOrder;
239
+ const calcs = new Map(model.calculatedFields.map((c) => [c.name, c]));
240
+ values = model.values.map((v, k) => {
241
+ const name = measureId(model.values, k);
242
+ const c = calcs.get(v.field);
243
+ if (c) {
244
+ let calc = null;
245
+ try {
246
+ calc = compileFormula(c.formula, fieldNames);
247
+ }
248
+ catch (e) {
249
+ const err = e;
250
+ errors.push({ name: c.name, message: err.message, position: err.position ?? 0 });
251
+ }
252
+ const refs = calc ? calc.references.map((r) => measureOf(r.aggregate, r.field)) : [];
253
+ return { name, field: v, caption: v.caption ?? c.caption ?? c.name, mi: -1, calc, refs };
254
+ }
255
+ return { name, field: v, caption: v.caption ?? defs.get(v.field)?.caption ?? v.field, mi: measureOf(v.aggregate, v.field, v.customId), calc: null, refs: [] };
256
+ });
257
+ }
258
+ /** Value field index by measure id, or by source field when that is unambiguous. */
259
+ const valueIndex = (id) => {
260
+ const k = values.findIndex((v) => v.name === id);
261
+ return k !== -1 ? k : values.findIndex((v) => v.field.field === id);
262
+ };
263
+ // --- state math
264
+ const initState = (st, o, cust, co) => {
265
+ st[o] = 0;
266
+ for (const m of measures) {
267
+ const a = o + m.off;
268
+ const k = m.kind;
269
+ if (k === LAZY)
270
+ continue;
271
+ st[a] = 0;
272
+ if (k === CUSTOM)
273
+ cust[co + m.ci] = m.custom.init();
274
+ else if (k !== COUNT)
275
+ st[a + 1] = k === PRODUCT ? 1 : k === MIN ? Infinity : k === MAX ? -Infinity : 0;
276
+ if (k === VAR)
277
+ st[a + 2] = 0;
278
+ }
279
+ };
280
+ const addRow = (st, o, i, cust, co) => {
281
+ st[o]++;
282
+ for (const m of measures) {
283
+ const a = o + m.off;
284
+ const x = m.num ? m.num[i] : 0;
285
+ switch (m.kind) {
286
+ case SUM:
287
+ case AVG:
288
+ if (x === x)
289
+ st[a]++, (st[a + 1] += x);
290
+ break;
291
+ case PRODUCT:
292
+ if (x === x)
293
+ st[a]++, (st[a + 1] *= x);
294
+ break;
295
+ case COUNT:
296
+ if (m.idx.ids[i] !== m.blank)
297
+ st[a]++;
298
+ break;
299
+ case MIN:
300
+ if (x === x) {
301
+ st[a]++;
302
+ if (x < st[a + 1])
303
+ st[a + 1] = x;
304
+ }
305
+ break;
306
+ case MAX:
307
+ if (x === x) {
308
+ st[a]++;
309
+ if (x > st[a + 1])
310
+ st[a + 1] = x;
311
+ }
312
+ break;
313
+ case VAR:
314
+ if (x === x) {
315
+ const n = ++st[a];
316
+ const d = x - st[a + 1];
317
+ st[a + 1] += d / n;
318
+ st[a + 2] += d * (x - st[a + 1]);
319
+ }
320
+ break;
321
+ case CUSTOM:
322
+ st[a]++;
323
+ cust[co + m.ci] = m.custom.add(cust[co + m.ci], m.idx.get(rows[i]));
324
+ }
325
+ }
326
+ };
327
+ const mergeState = (st, o, src, so, cust, co, scust, sco) => {
328
+ st[o] += src[so];
329
+ for (const m of measures) {
330
+ const a = o + m.off;
331
+ const b = so + m.off;
332
+ switch (m.kind) {
333
+ case SUM:
334
+ case AVG:
335
+ st[a] += src[b];
336
+ st[a + 1] += src[b + 1];
337
+ break;
338
+ case PRODUCT:
339
+ st[a] += src[b];
340
+ st[a + 1] *= src[b + 1];
341
+ break;
342
+ case COUNT:
343
+ st[a] += src[b];
344
+ break;
345
+ case MIN:
346
+ st[a] += src[b];
347
+ if (src[b + 1] < st[a + 1])
348
+ st[a + 1] = src[b + 1];
349
+ break;
350
+ case MAX:
351
+ st[a] += src[b];
352
+ if (src[b + 1] > st[a + 1])
353
+ st[a + 1] = src[b + 1];
354
+ break;
355
+ case VAR: {
356
+ const nb = src[b];
357
+ if (!nb)
358
+ break;
359
+ const na = st[a];
360
+ if (!na) {
361
+ st[a] = nb;
362
+ st[a + 1] = src[b + 1];
363
+ st[a + 2] = src[b + 2];
364
+ break;
365
+ }
366
+ const n = na + nb;
367
+ const d = src[b + 1] - st[a + 1];
368
+ st[a] = n;
369
+ st[a + 1] += (d * nb) / n;
370
+ st[a + 2] += src[b + 2] + (d * d * na * nb) / n;
371
+ break;
372
+ }
373
+ case CUSTOM:
374
+ st[a] += src[b];
375
+ cust[co + m.ci] = m.custom.merge(cust[co + m.ci], scust[sco + m.ci]);
376
+ }
377
+ }
378
+ };
379
+ const stateValue = (st, o, m, cust, co) => {
380
+ if (!st[o])
381
+ return null;
382
+ const a = o + m.off;
383
+ const n = st[a];
384
+ switch (m.kind) {
385
+ case COUNT:
386
+ return n;
387
+ case CUSTOM:
388
+ return m.custom.result(cust[co + m.ci]);
389
+ case AVG:
390
+ return n ? st[a + 1] / n : null;
391
+ case VAR: {
392
+ const sample = m.agg === 'sampleVar' || m.agg === 'sampleStdev';
393
+ if (n < (sample ? 2 : 1))
394
+ return null;
395
+ const v = Math.max(0, st[a + 2]) / (sample ? n - 1 : n);
396
+ return m.agg.endsWith('Stdev') ? Math.sqrt(v) : v;
397
+ }
398
+ default:
399
+ return n ? st[a + 1] : null;
400
+ }
401
+ };
402
+ // --- filters (member and label: row mask; value filters: after aggregating the filtered level)
403
+ function labelMatch(level, m, spec) {
404
+ const key = level.keys[m];
405
+ const label = level.labels[m];
406
+ const op = spec.operator;
407
+ const cs = spec.caseSensitive === true;
408
+ const norm = (s) => (cs ? s : s.toLowerCase());
409
+ if (op === 'contains' || op === 'doesNotContain' || op === 'startsWith' || op === 'doesNotStartWith' || op === 'endsWith' || op === 'doesNotEndWith') {
410
+ const l = norm(label);
411
+ const v = norm(String(spec.value ?? ''));
412
+ const hit = op.includes('ontain') ? l.includes(v) : op.includes('tart') ? l.startsWith(v) : l.endsWith(v);
413
+ return op.startsWith('doesNot') ? !hit : hit;
414
+ }
415
+ const cmp = (x) => {
416
+ if (typeof key === 'number' && typeof x === 'number')
417
+ return key - x;
418
+ if (level.base.type === 'date' && typeof key === 'string' && typeof x === 'string' && level.remap === null)
419
+ return Date.parse(key) - Date.parse(x);
420
+ return collator.compare(cs ? label : label.toLowerCase(), cs ? String(x) : String(x).toLowerCase());
421
+ };
422
+ const c = cmp(spec.value);
423
+ switch (op) {
424
+ case 'equal':
425
+ return c === 0;
426
+ case 'notEqual':
427
+ return c !== 0;
428
+ case 'greaterThan':
429
+ return c > 0;
430
+ case 'greaterThanOrEqual':
431
+ return c >= 0;
432
+ case 'lessThan':
433
+ return c < 0;
434
+ case 'lessThanOrEqual':
435
+ return c <= 0;
436
+ default: {
437
+ const c2 = cmp(spec.value2 ?? spec.value);
438
+ const inside = (c >= 0 && c2 <= 0) || (c <= 0 && c2 >= 0);
439
+ return op === 'between' ? inside : !inside;
440
+ }
441
+ }
442
+ }
443
+ function memberTest(level, f) {
444
+ if ('include' in f || 'exclude' in f) {
445
+ const list = 'include' in f ? f.include : f.exclude;
446
+ const set = new Set(list.map(json));
447
+ const inc = 'include' in f;
448
+ return (m) => set.has(json(level.keys[m])) === inc;
449
+ }
450
+ if ('label' in f)
451
+ return (m) => labelMatch(level, m, f.label);
452
+ return null;
453
+ }
454
+ /** Levels of the fields placed on any axis; filters on fields that are not placed are ignored. */
455
+ function* filterLevel(name) {
456
+ for (const l of [...rowAx.levels, ...colAx.levels])
457
+ if (l.name === name)
458
+ return l;
459
+ const f = model.filters.find((x) => x.field === name) ?? [...model.rows, ...model.columns].find((x) => levelNames(x.field, model.groups[x.field])[0] === name);
460
+ if (!f)
461
+ return null;
462
+ return (yield* levelsOf(f.field))[0] ?? null;
463
+ }
464
+ function* buildMask() {
465
+ filterLevels = [];
466
+ const valueFilters = [];
467
+ for (const [name, f] of Object.entries(model.filterBy)) {
468
+ const level = yield* filterLevel(name);
469
+ if (!level)
470
+ continue;
471
+ if ('value' in f) {
472
+ const ri = rowAx.levels.indexOf(level);
473
+ const ci = colAx.levels.indexOf(level);
474
+ if (ri !== -1)
475
+ valueFilters.push({ level, axis: rowAx, l: ri, spec: f.value });
476
+ else if (ci !== -1)
477
+ valueFilters.push({ level, axis: colAx, l: ci, spec: f.value });
478
+ continue;
479
+ }
480
+ const test = memberTest(level, f);
481
+ if (!test)
482
+ continue;
483
+ const cache = [];
484
+ filterLevels.push({ level, allowed: (m) => (cache[m] ??= test(m) ? 1 : 0) === 1 });
485
+ }
486
+ excluded = new Set();
487
+ const n = rows.length;
488
+ if (!filterLevels.length && !valueFilters.length) {
489
+ mask = null;
490
+ return;
491
+ }
492
+ const mk = new Uint8Array(n).fill(1);
493
+ for (const { level, allowed } of filterLevels) {
494
+ const ids = level.ids;
495
+ const ok = new Uint8Array(level.keys.length);
496
+ for (let m = 0; m < ok.length; m++)
497
+ ok[m] = allowed(m) ? 1 : 0;
498
+ for (let i = 0; i < n; i++)
499
+ if (!ok[ids[i]])
500
+ mk[i] = 0;
501
+ yield 0;
502
+ }
503
+ mask = mk;
504
+ // Value filters, outer levels first: a member's total against the other axis grand total.
505
+ valueFilters.sort((a, b) => (a.axis === b.axis ? a.l - b.l : a.axis === rowAx ? -1 : 1));
506
+ for (const vf of valueFilters) {
507
+ const k = valueIndex(vf.spec.measure);
508
+ if (k === -1)
509
+ continue;
510
+ const depth = vf.l + 1;
511
+ const ax = vf.axis;
512
+ const up = ax.D - depth;
513
+ const slot = new Int32Array(ax.parent.length).fill(-1);
514
+ const nodes = [];
515
+ const list = [];
516
+ for (let i = 0; i < n; i++) {
517
+ if (!mk[i])
518
+ continue;
519
+ let node = ax.leaf[i];
520
+ for (let s = 0; s < up; s++)
521
+ node = ax.parent[node];
522
+ if (slot[node] === -1)
523
+ (slot[node] = nodes.length), nodes.push(node);
524
+ list.push(i);
525
+ }
526
+ const t = aggregateRows(list, (i, out) => ((out[0] = slot[ancestor(ax, ax.leaf[i], depth)]), 1), nodes.length);
527
+ const vals = nodes.map((_, s) => valueOfSpec(k, (mi) => tableValue(t, s, mi)));
528
+ const keep = new Set();
529
+ const { operator: op, value: a, value2: b } = vf.spec;
530
+ if (op === 'top' || op === 'bottom') {
531
+ const byParent = new Map();
532
+ nodes.forEach((node, s) => {
533
+ const p = ax.parent[node];
534
+ let list = byParent.get(p);
535
+ if (!list)
536
+ byParent.set(p, (list = []));
537
+ list.push(s);
538
+ });
539
+ for (const list of byParent.values()) {
540
+ list.sort((x, y) => (vals[y] ?? -Infinity) - (vals[x] ?? -Infinity));
541
+ if (op === 'bottom')
542
+ list.reverse();
543
+ for (const s of list.slice(0, Math.max(0, Math.floor(a))))
544
+ keep.add(nodes[s]);
545
+ }
546
+ }
547
+ else
548
+ nodes.forEach((node, s) => vals[s] !== null && compareValue(op, vals[s], a, b) && keep.add(node));
549
+ for (const node of nodes)
550
+ if (!keep.has(node))
551
+ excluded.add(`${ax === rowAx ? 'r' : 'c'}${node}`);
552
+ for (let i = 0; i < n; i++)
553
+ if (mk[i] && !keep.has(ancestor(ax, ax.leaf[i], depth)))
554
+ mk[i] = 0;
555
+ yield 0;
556
+ }
557
+ }
558
+ const ancestor = (ax, node, depth) => {
559
+ while (ax.depth[node] > depth)
560
+ node = ax.parent[node];
561
+ return node;
562
+ };
563
+ function aggregateRows(list, slotsOf, nSlots, onlyLazy = false) {
564
+ const st = new Float64Array(onlyLazy ? 0 : nSlots * stride);
565
+ const cust = customCount && !onlyLazy ? new Array(nSlots * customCount) : null;
566
+ if (!onlyLazy)
567
+ for (let s = 0; s < nSlots; s++)
568
+ initState(st, s * stride, cust, s * customCount);
569
+ const lz = new Map();
570
+ measures.forEach((m, mi) => m.kind === LAZY && lz.set(mi, []));
571
+ const out = new Int32Array(64);
572
+ for (let x = 0; x < list.length; x++) {
573
+ const i = list[x];
574
+ const k = slotsOf(i, out);
575
+ for (let j = 0; j < k; j++) {
576
+ const s = out[j];
577
+ if (!onlyLazy)
578
+ addRow(st, s * stride, i, cust, s * customCount);
579
+ for (const [mi, arr] of lz) {
580
+ const m = measures[mi];
581
+ if (m.agg === 'distinctCount') {
582
+ const id = m.idx.ids[i];
583
+ if (id !== m.blank)
584
+ (arr[s] ??= new Set()).add(id);
585
+ }
586
+ else {
587
+ const v = m.num[i];
588
+ if (v === v)
589
+ (arr[s] ??= []).push(v);
590
+ }
591
+ }
592
+ }
593
+ }
594
+ return { st, cust, lazy: lz };
595
+ }
596
+ const lazyResult = (m, bucket) => {
597
+ if (!bucket)
598
+ return m.agg === 'distinctCount' ? 0 : null;
599
+ if (bucket instanceof Set)
600
+ return bucket.size;
601
+ if (!bucket.length)
602
+ return null;
603
+ const s = Float64Array.from(bucket).sort();
604
+ const h = s.length >> 1;
605
+ return s.length & 1 ? s[h] : (s[h - 1] + s[h]) / 2;
606
+ };
607
+ const tableValue = (t, s, mi) => {
608
+ const m = measures[mi];
609
+ if (m.kind === LAZY)
610
+ return lazyResult(m, t.lazy.get(mi)[s]);
611
+ return stateValue(t.st, s * stride, m, t.cust, s * customCount);
612
+ };
613
+ // --- bucket: units in depth-first ranges of the row tree
614
+ function* buildViews() {
615
+ const n = rows.length;
616
+ const pass = mask;
617
+ const rowLeaf = rowAx.leaf;
618
+ const colLeaf = colAx.leaf;
619
+ // Data compression: pre-aggregate rows sharing every axis member when that is
620
+ // guaranteed to shrink the units 4x (distinct leaf tuples <= rows / 4).
621
+ let rl = 0;
622
+ let cl = 0;
623
+ for (const d of rowAx.depth)
624
+ if (d === rowAx.D)
625
+ rl++;
626
+ for (const d of colAx.depth)
627
+ if (d === colAx.D)
628
+ cl++;
629
+ const lazyOnly = measures.length > 0 && measures.every((m) => m.kind === LAZY);
630
+ units = null;
631
+ if (!lazyOnly && rl * cl * 4 <= n && n >= 1024) {
632
+ const cap = Math.max(16, Math.min(n, rl * cl));
633
+ const map = createPairMap(cap);
634
+ let row = new Int32Array(cap);
635
+ let col = new Int32Array(cap);
636
+ let st = new Float64Array(cap * stride);
637
+ const cust = customCount ? new Array(cap * customCount) : null;
638
+ let count = 0;
639
+ for (let i = 0; i < n; i++) {
640
+ if (pass && !pass[i])
641
+ continue;
642
+ let u = map.get(rowLeaf[i], colLeaf[i]);
643
+ if (u === -1) {
644
+ u = map.put(rowLeaf[i], colLeaf[i], count++);
645
+ if (u >= row.length) {
646
+ const r2 = new Int32Array(row.length * 2);
647
+ r2.set(row);
648
+ row = r2;
649
+ const c2 = new Int32Array(col.length * 2);
650
+ c2.set(col);
651
+ col = c2;
652
+ const s2 = new Float64Array(st.length * 2);
653
+ s2.set(st);
654
+ st = s2;
655
+ }
656
+ row[u] = rowLeaf[i];
657
+ col[u] = colLeaf[i];
658
+ initState(st, u * stride, cust, u * customCount);
659
+ }
660
+ addRow(st, u * stride, i, cust, u * customCount);
661
+ if ((i & 0x3ffff) === 0x3ffff)
662
+ yield i;
663
+ }
664
+ units = { row, col, st, cust, count };
665
+ }
666
+ view = units ? orderUnits(units.row, units.count, (u) => units.st[u * stride]) : null;
667
+ rawView = null;
668
+ if (!view)
669
+ view = rawView = yield* rawUnits();
670
+ // Rows per column node.
671
+ colRows = new Int32Array(colAx.parent.length);
672
+ for (let i = 0; i < n; i++)
673
+ if (!pass || pass[i])
674
+ colRows[colLeaf[i]]++;
675
+ for (let k = colAx.parent.length - 1; k > 0; k--)
676
+ colRows[colAx.parent[k]] += colRows[k];
677
+ }
678
+ function* rawUnits() {
679
+ const n = rows.length;
680
+ const leaf = rowAx.leaf;
681
+ if (!mask)
682
+ return orderUnits(leaf, n, null);
683
+ let count = 0;
684
+ for (let i = 0; i < n; i++)
685
+ count += mask[i];
686
+ const list = new Int32Array(count);
687
+ const leafOf = new Int32Array(count);
688
+ let k = 0;
689
+ for (let i = 0; i < n; i++)
690
+ if (mask[i])
691
+ (list[k] = i), (leafOf[k++] = leaf[i]);
692
+ yield 0;
693
+ return orderUnits(leafOf, count, null, list);
694
+ }
695
+ /** Counting sort of units by row leaf so that every row node is one contiguous range. */
696
+ function orderUnits(leafOf, count, weight, ids) {
697
+ const size = rowAx.parent.length;
698
+ const unitsPer = new Int32Array(size);
699
+ let rowsPer = unitsPer;
700
+ for (let u = 0; u < count; u++)
701
+ unitsPer[leafOf[u]]++;
702
+ if (weight) {
703
+ rowsPer = new Int32Array(size);
704
+ for (let u = 0; u < count; u++)
705
+ rowsPer[leafOf[u]] += weight(u);
706
+ }
707
+ const par = rowAx.parent;
708
+ for (let k = size - 1; k > 0; k--) {
709
+ unitsPer[par[k]] += unitsPer[k];
710
+ if (weight)
711
+ rowsPer[par[k]] += rowsPer[k];
712
+ }
713
+ const start = new Int32Array(size);
714
+ const cursor = new Int32Array(size);
715
+ for (let k = 1; k < size; k++) {
716
+ const p = par[k];
717
+ start[k] = cursor[p];
718
+ cursor[p] += unitsPer[k];
719
+ cursor[k] = start[k];
720
+ }
721
+ // Only leaves receive units (every unit's node is a leaf of the axis).
722
+ const order = new Int32Array(count);
723
+ for (let u = 0; u < count; u++)
724
+ order[cursor[leafOf[u]]++] = ids ? ids[u] : u;
725
+ return { start, units: unitsPer, order, rows: rowsPer };
726
+ }
727
+ const getRawView = () => (rawView ??= drain(rawUnits()));
728
+ // --- profiles
729
+ let scratch = new Float64Array(0);
730
+ let scust = null;
731
+ let stamp = new Int32Array(0);
732
+ let touched = new Int32Array(0);
733
+ let gen = 0;
734
+ const prepScratch = () => {
735
+ const size = colAx.parent.length;
736
+ if (stamp.length < size || scratch.length < size * stride) {
737
+ stamp = new Int32Array(size);
738
+ touched = new Int32Array(size);
739
+ scratch = new Float64Array(size * stride);
740
+ gen = 0;
741
+ }
742
+ scust = customCount ? new Array(size * customCount) : null;
743
+ gen++;
744
+ };
745
+ const compact = (k) => {
746
+ const cols = touched.slice(0, k).sort();
747
+ const w = stride;
748
+ const st = new Float64Array(k * w);
749
+ const cust = customCount ? new Array(k * customCount) : null;
750
+ for (let j = 0; j < k; j++) {
751
+ const c = cols[j];
752
+ for (let x = 0, o = c * w, d = j * w; x < w; x++)
753
+ st[d + x] = scratch[o + x];
754
+ if (cust)
755
+ for (let x = 0; x < customCount; x++)
756
+ cust[j * customCount + x] = scust[c * customCount + x];
757
+ }
758
+ return { cols, st, cust };
759
+ };
760
+ /** Accumulates units `order[s..e)` at their column leaves (plain function: generators deopt hot loops). */
761
+ const accumulate = (order, s, e, g, k) => {
762
+ const u0 = units;
763
+ const colLeaf = colAx.leaf;
764
+ const w = stride;
765
+ const cc = customCount;
766
+ for (let x = s; x < e; x++) {
767
+ const u = order[x];
768
+ const c = u0 ? u0.col[u] : colLeaf[u];
769
+ const o = c * w;
770
+ if (stamp[c] !== g) {
771
+ stamp[c] = g;
772
+ touched[k++] = c;
773
+ initState(scratch, o, scust, c * cc);
774
+ }
775
+ if (u0)
776
+ mergeState(scratch, o, u0.st, u * w, scust, c * cc, u0.cust, u * cc);
777
+ else
778
+ addRow(scratch, o, u, scust, c * cc);
779
+ }
780
+ return k;
781
+ };
782
+ function* fromUnits(r) {
783
+ const v = view;
784
+ const s = v.start[r];
785
+ const e = s + v.units[r];
786
+ if (s === e)
787
+ return EMPTY_PROFILE;
788
+ prepScratch();
789
+ const g = gen;
790
+ const cpar = colAx.parent;
791
+ let k = 0;
792
+ // Accumulate at the column leaves, then roll the leaves up level by level
793
+ // (touched holds every leaf before any parent, so parents merge final children).
794
+ for (let x = s; x < e; x += 0x20000) {
795
+ k = accumulate(v.order, x, Math.min(e, x + 0x20000), g, k);
796
+ if (e - s > 0x20000)
797
+ yield x;
798
+ }
799
+ for (let j = 0; j < k; j++) {
800
+ const c = touched[j];
801
+ const p = cpar[c];
802
+ if (p === -1)
803
+ continue;
804
+ const o = p * stride;
805
+ if (stamp[p] !== g) {
806
+ stamp[p] = g;
807
+ touched[k++] = p;
808
+ initState(scratch, o, scust, p * customCount);
809
+ }
810
+ mergeState(scratch, o, scratch, c * stride, scust, p * customCount, scust, c * customCount);
811
+ }
812
+ return compact(k);
813
+ }
814
+ const fromKids = (list) => {
815
+ const ps = list.map(ensure);
816
+ prepScratch();
817
+ const g = gen;
818
+ let k = 0;
819
+ for (const p of ps) {
820
+ const cols = p.cols;
821
+ for (let j = 0; j < cols.length; j++) {
822
+ const c = cols[j];
823
+ const o = c * stride;
824
+ if (stamp[c] !== g) {
825
+ stamp[c] = g;
826
+ touched[k++] = c;
827
+ initState(scratch, o, scust, c * customCount);
828
+ }
829
+ mergeState(scratch, o, p.st, j * stride, scust, c * customCount, p.cust, j * customCount);
830
+ }
831
+ }
832
+ return compact(k);
833
+ };
834
+ let rowExpanded = new Set();
835
+ let colExpanded = new Set();
836
+ let allRows = false;
837
+ let allCols = false;
838
+ const isOpen = (ax, node) => node === 0 || (ax.depth[node] < ax.D && (ax === rowAx ? allRows || rowExpanded.has(node) : allCols || colExpanded.has(node)));
839
+ const ensure = (r) => {
840
+ let p = profiles[r];
841
+ if (p)
842
+ return p;
843
+ if ((view.rows[r] ?? 0) === 0)
844
+ p = EMPTY_PROFILE;
845
+ // From the node's own units in view order, so values never depend on the
846
+ // history of drills (equal model + data = equal floats). The root, whose
847
+ // children are always visible, merges them in id order instead.
848
+ else
849
+ p = r === 0 && rowAx.kids[0]?.length ? fromKids(rowAx.kids[0]) : drain(fromUnits(r));
850
+ profiles[r] = p;
851
+ return p;
852
+ };
853
+ const lookup = (p, c) => {
854
+ const cols = p.cols;
855
+ let lo = 0;
856
+ let hi = cols.length - 1;
857
+ while (lo <= hi) {
858
+ const mid = (lo + hi) >> 1;
859
+ const v = cols[mid];
860
+ if (v === c)
861
+ return mid;
862
+ if (v < c)
863
+ lo = mid + 1;
864
+ else
865
+ hi = mid - 1;
866
+ }
867
+ return -1;
868
+ };
869
+ const lazyValue = (r, c, mi) => {
870
+ const key = r * measures.length + mi;
871
+ let map = lazy.get(key);
872
+ if (!map) {
873
+ const rv = getRawView();
874
+ const s = rv.start[r] ?? 0;
875
+ const list = rv.order.subarray(s, s + (rv.units[r] ?? 0));
876
+ const cpar = colAx.parent;
877
+ const slots = new Int32Array(colAx.parent.length).fill(-1);
878
+ const cols = [];
879
+ const t = aggregateRows(list, (i, out) => {
880
+ let k = 0;
881
+ for (let x = colAx.leaf[i]; x !== -1; x = cpar[x]) {
882
+ if (slots[x] === -1)
883
+ (slots[x] = cols.length), cols.push(x);
884
+ out[k++] = slots[x];
885
+ }
886
+ return k;
887
+ }, 0, true);
888
+ map = new Map();
889
+ const m = measures[mi];
890
+ const buckets = t.lazy.get(mi);
891
+ cols.forEach((col, s2) => map.set(col, lazyResult(m, buckets[s2])));
892
+ lazy.set(key, map);
893
+ }
894
+ const v = map.get(c);
895
+ return v === undefined ? null : v;
896
+ };
897
+ const baseValue = (r, c, mi) => {
898
+ const p = ensure(r);
899
+ const j = lookup(p, c);
900
+ if (j === -1)
901
+ return null;
902
+ const m = measures[mi];
903
+ if (m.kind === LAZY)
904
+ return lazyValue(r, c, mi);
905
+ return stateValue(p.st, j * stride, m, p.cust, j * customCount);
906
+ };
907
+ const valueOfSpec = (k, get) => {
908
+ const v = values[k];
909
+ if (v.mi !== -1)
910
+ return get(v.mi);
911
+ if (!v.calc)
912
+ return null;
913
+ return v.calc.evaluate((agg, field) => get(measures.findIndex((m) => m.agg === agg && m.field === field)));
914
+ };
915
+ const rawCell = (r, c, k) => valueOfSpec(k, (mi) => baseValue(r, c, mi));
916
+ // --- sort
917
+ const ranksOf = (level) => {
918
+ const spec = model.sort[level.name] ?? model.sort[level.base.field];
919
+ const key = `${level.signature}\u0000${json(spec)}`;
920
+ let r = rankCache.get(key);
921
+ if (!r || r.length !== level.keys.length)
922
+ rankCache.set(key, (r = memberRanks(level, spec ?? 'asc', collator)));
923
+ return r;
924
+ };
925
+ let valueSortCol = -1;
926
+ let valueSortMeasure = -1;
927
+ function visibleKids(ax, node) {
928
+ const tag = ax === rowAx ? node * 2 : node * 2 + 1;
929
+ let list = kidsCache.get(tag);
930
+ if (list)
931
+ return list;
932
+ const depth = ax.depth[node];
933
+ const level = ax.levels[depth];
934
+ const counts = ax === rowAx ? view.rows : colRows;
935
+ const prefix = ax === rowAx ? 'r' : 'c';
936
+ if (model.showEmptyMembers) {
937
+ const allowed = filterLevels.find((f) => f.level === level)?.allowed;
938
+ list = [];
939
+ for (let m = 0; m < level.keys.length; m++) {
940
+ if (allowed && !allowed(m))
941
+ continue;
942
+ const kid = childOf(ax, node, m, true);
943
+ if (!excluded.has(prefix + kid))
944
+ list.push(kid);
945
+ }
946
+ }
947
+ else
948
+ list = (ax.kids[node] ?? []).filter((k) => (counts[k] ?? 0) > 0);
949
+ const ranks = ranksOf(level);
950
+ const vs = model.valueSort;
951
+ if (ax === rowAx && vs && valueSortMeasure !== -1 && valueSortCol !== -1 && (vs.multipleAxis || depth === ax.D - 1)) {
952
+ const val = new Map(list.map((k) => [k, rawCell(k, valueSortCol, valueSortMeasure)]));
953
+ const dir = vs.direction === 'desc' ? -1 : 1;
954
+ list.sort((a, b) => {
955
+ const x = val.get(a) ?? null;
956
+ const y = val.get(b) ?? null;
957
+ if (x === y)
958
+ return ranks[ax.member[a]] - ranks[ax.member[b]];
959
+ if (x === null)
960
+ return 1;
961
+ if (y === null)
962
+ return -1;
963
+ return (x - y) * dir;
964
+ });
965
+ }
966
+ else
967
+ list.sort((a, b) => ranks[ax.member[a]] - ranks[ax.member[b]]);
968
+ kidsCache.set(tag, list);
969
+ return list;
970
+ }
971
+ // --- paths
972
+ const pathOf = (ax, node) => {
973
+ const out = [];
974
+ for (let x = node; x > 0; x = ax.parent[x])
975
+ out.push(ax.levels[ax.depth[x] - 1].keys[ax.member[x]]);
976
+ return out.reverse();
977
+ };
978
+ const nodeOf = (ax, path) => {
979
+ let node = 0;
980
+ for (let l = 0; l < path.length; l++) {
981
+ const level = ax.levels[l];
982
+ const m = level?.byKey.get(path[l]);
983
+ if (m === undefined)
984
+ return -1;
985
+ node = childOf(ax, node, m, false);
986
+ if (node === -1)
987
+ return -1;
988
+ }
989
+ return node;
990
+ };
991
+ const resolveExpanded = () => {
992
+ rowExpanded = new Set();
993
+ colExpanded = new Set();
994
+ allRows = allCols = model.expanded === 'all';
995
+ if (model.expanded === 'all')
996
+ return;
997
+ for (const p of model.expanded) {
998
+ const [axis, ...path] = p;
999
+ const ax = axis === 'rows' ? rowAx : colAx;
1000
+ const node = nodeOf(ax, path);
1001
+ if (node > 0)
1002
+ (axis === 'rows' ? rowExpanded : colExpanded).add(node);
1003
+ }
1004
+ };
1005
+ // --- layout
1006
+ const subOn = (ax, l) => {
1007
+ const f = ax.fields[l];
1008
+ if (f.showSubTotals !== undefined)
1009
+ return f.showSubTotals;
1010
+ const s = model.totals.sub;
1011
+ return typeof s === 'boolean' ? s : (s[ax.levels[l].name] ?? s[f.field] ?? true);
1012
+ };
1013
+ function layoutAxis(ax, isRows) {
1014
+ const M = values.length;
1015
+ const here = M > 0 && model.valuesPlacement.axis === (isRows ? 'rows' : 'columns');
1016
+ const showV = here && (M > 1 || model.showValueHeader === true);
1017
+ const D = ax.D;
1018
+ const idx = model.valuesPlacement.index;
1019
+ const vl = showV ? Math.max(0, Math.min(D, idx < 0 ? D : idx)) : -1;
1020
+ const len = D + (showV ? 1 : 0);
1021
+ const fixed = here && !showV ? 0 : -1;
1022
+ const t = model.totals;
1023
+ const grandOn = t.grand === 'both' || t.grand === (isRows ? 'rows' : 'columns');
1024
+ const grandStart = t.grandPosition === 'start';
1025
+ const subStart = t.subPosition === 'auto' ? isRows : t.subPosition === 'start';
1026
+ const L = { pn: [], pm: [], pk: [], ph: [], dk: [], dn: [], dm: [], dd: [], dp: [], ds: [], dc: [], dpar: [], roots: [], depth: Math.max(1, len), values: here };
1027
+ const open = (kind, node, m, depth, parent, ctx) => {
1028
+ const d = L.dk.length;
1029
+ L.dk.push(kind);
1030
+ L.dn.push(node);
1031
+ L.dm.push(m);
1032
+ L.dd.push(depth);
1033
+ L.dp.push(L.pn.length);
1034
+ L.ds.push(0);
1035
+ L.dc.push(null);
1036
+ L.dpar.push(parent);
1037
+ if (parent === -1)
1038
+ L.roots.push(d);
1039
+ else
1040
+ (L.dc[parent] ??= []).push(d);
1041
+ if (isRows)
1042
+ pos(node, m, ctx, d);
1043
+ return d;
1044
+ };
1045
+ const pos = (node, m, kind, d) => {
1046
+ L.pn.push(node);
1047
+ L.pm.push(m);
1048
+ L.pk.push(kind);
1049
+ L.ph.push(d);
1050
+ };
1051
+ const close = (d, ctx, carried) => {
1052
+ if (!L.dc[d]) {
1053
+ if (!isRows)
1054
+ pos(L.dn[d], L.dm[d], ctx, d);
1055
+ }
1056
+ else if (isRows)
1057
+ L.pk[L.dp[d]] = carried ? 1 : 3;
1058
+ L.ds[d] = L.pn.length - L.dp[d];
1059
+ };
1060
+ const valuesBelow = (li) => vl >= li;
1061
+ const gen = (parent, node, li, m, ctx) => {
1062
+ if (li >= len)
1063
+ return;
1064
+ if (li === vl) {
1065
+ for (let k = 0; k < M; k++) {
1066
+ const d = open(3, node, k, li, parent, ctx);
1067
+ gen(d, node, li + 1, k, ctx);
1068
+ close(d, ctx, false);
1069
+ }
1070
+ return;
1071
+ }
1072
+ if (ctx !== 0 || !isOpen(ax, node))
1073
+ return gen(parent, node, li + 1, m, ctx);
1074
+ const isRoot = node === 0;
1075
+ const level = ax.depth[node];
1076
+ const showTotal = isRoot ? grandOn : subOn(ax, level - 1);
1077
+ const atStart = isRoot ? grandStart : subStart;
1078
+ const carried = isRows && !isRoot && showTotal && atStart && vl !== li - 1 && !valuesBelow(li + 1);
1079
+ const total = () => {
1080
+ const d = open(isRoot ? 2 : 1, node, m, li, parent, isRoot ? 2 : 1);
1081
+ gen(d, node, li + 1, m, isRoot ? 2 : 1);
1082
+ close(d, isRoot ? 2 : 1, false);
1083
+ };
1084
+ if (showTotal && atStart && !carried)
1085
+ total();
1086
+ for (const kid of visibleKids(ax, node)) {
1087
+ const d = open(0, kid, m, li, parent, 0);
1088
+ gen(d, kid, li + 1, m, 0);
1089
+ const kidCarried = isRows && isOpen(ax, kid) && subOn(ax, level) && subStart && !valuesBelow(li + 2);
1090
+ close(d, 0, kidCarried);
1091
+ }
1092
+ if (showTotal && !atStart)
1093
+ total();
1094
+ };
1095
+ if (D === 0 && !showV) {
1096
+ const d = open(2, 0, fixed, 0, -1, 2);
1097
+ close(d, 2, false);
1098
+ }
1099
+ else
1100
+ gen(-1, 0, 0, fixed, D === 0 ? 2 : 0);
1101
+ return L;
1102
+ }
1103
+ // --- show values as
1104
+ function showAs(k, r, c, v) {
1105
+ const spec = values[k].field.showAs;
1106
+ if (!spec || v === null)
1107
+ return v;
1108
+ const val = (rr, cc) => rawCell(rr, cc, k);
1109
+ const div = (a, b) => (a === null || b === null || b === 0 ? null : a / b);
1110
+ switch (spec.kind) {
1111
+ case 'percentOfGrandTotal':
1112
+ return div(v, val(0, 0));
1113
+ case 'percentOfColumnTotal':
1114
+ return div(v, val(0, c));
1115
+ case 'percentOfRowTotal':
1116
+ return div(v, val(r, 0));
1117
+ case 'percentOfParentRowTotal':
1118
+ return div(v, val(r === 0 ? 0 : rowAx.parent[r], c));
1119
+ case 'percentOfParentColumnTotal':
1120
+ return div(v, val(r, c === 0 ? 0 : colAx.parent[c]));
1121
+ case 'index': {
1122
+ const g = val(0, 0);
1123
+ const rt = val(r, 0);
1124
+ const ct = val(0, c);
1125
+ return g === null || rt === null || ct === null || rt * ct === 0 ? null : (v * g) / (rt * ct);
1126
+ }
1127
+ }
1128
+ // Base-field kinds: the base level lives on the row or the column axis.
1129
+ const base = spec.baseField ?? (spec.kind === 'runningTotal' || spec.kind === 'percentOfRunningTotal' ? rowAx.levels[rowAx.D - 1]?.name ?? colAx.levels[colAx.D - 1]?.name : undefined);
1130
+ const ri = rowAx.levels.findIndex((l) => l.name === base);
1131
+ const ci = colAx.levels.findIndex((l) => l.name === base);
1132
+ if (ri === -1 && ci === -1)
1133
+ return spec.kind === 'percentOfParentTotal' ? div(v, val(0, 0)) : v;
1134
+ const ax = ri !== -1 ? rowAx : colAx;
1135
+ const node = ri !== -1 ? r : c;
1136
+ const depth = (ri !== -1 ? ri : ci) + 1;
1137
+ const at = (x) => (ri !== -1 ? val(x, c) : val(r, x));
1138
+ if (spec.kind === 'percentOfParentTotal')
1139
+ return div(v, at(ax.depth[node] > depth ? ancestor(ax, node, depth) : node));
1140
+ if (ax.depth[node] < depth)
1141
+ return spec.kind === 'runningTotal' ? v : null;
1142
+ const a = ancestor(ax, node, depth);
1143
+ const below = pathOf(ax, node).slice(depth);
1144
+ const swap = (sib) => {
1145
+ let x = sib;
1146
+ for (let l = 0; l < below.length && x !== -1; l++) {
1147
+ const m = ax.levels[depth + l].byKey.get(below[l]);
1148
+ x = m === undefined ? -1 : childOf(ax, x, m, false);
1149
+ }
1150
+ return x;
1151
+ };
1152
+ const sibs = visibleKids(ax, ax.parent[a]);
1153
+ if (spec.kind === 'differenceFrom' || spec.kind === 'percentOfDifferenceFrom') {
1154
+ const level = ax.levels[depth - 1];
1155
+ const bm = level.byKey.get(spec.baseItem ?? null);
1156
+ if (bm === undefined || bm === ax.member[a])
1157
+ return null;
1158
+ const sib = childOf(ax, ax.parent[a], bm, false);
1159
+ const b = sib === -1 ? null : swapped(swap(sib), at);
1160
+ if (b === null)
1161
+ return null;
1162
+ return spec.kind === 'differenceFrom' ? v - b : div(v - b, b);
1163
+ }
1164
+ let run = 0;
1165
+ let all = 0;
1166
+ let seen = false;
1167
+ for (const s of sibs) {
1168
+ const x = swapped(swap(s), at) ?? 0;
1169
+ all += x;
1170
+ if (!seen)
1171
+ run += x;
1172
+ if (s === a)
1173
+ seen = true;
1174
+ }
1175
+ return spec.kind === 'runningTotal' ? run : div(run, all);
1176
+ }
1177
+ const swapped = (x, at) => (x === -1 ? null : at(x));
1178
+ // --- result snapshots
1179
+ //
1180
+ // A PivotResult is an immutable snapshot: its accessors compute cells lazily from the derived state of
1181
+ // the run that produced it. Every run reassigns (never mutates in place) the
1182
+ // state that depends on the model, so a result keeps a frame of references
1183
+ // to its own run's state; reading an older result swaps that frame in for
1184
+ // the duration of the call. Frames share the caches that do not depend on
1185
+ // the model (field indexes, levels, axes) and, between runs with the same
1186
+ // mask, the row profiles, so a drill copies nothing.
1187
+ const capture = () => ({
1188
+ rows, model, env, rowAx, colAx, measures, stride, customCount, values, mask, excluded, units, view, rawView, colRows,
1189
+ profiles, lazy, kidsCache, filterLevels, valueSortCol, valueSortMeasure, rowExpanded, colExpanded, allRows, allCols,
1190
+ scratch, scust, stamp, touched, gen,
1191
+ });
1192
+ const restore = (f) => {
1193
+ ({ rows, model, env, rowAx, colAx, measures, stride, customCount, values, mask, excluded, units, view, rawView, colRows } = f);
1194
+ ({ profiles, lazy, kidsCache, filterLevels, valueSortCol, valueSortMeasure, rowExpanded, colExpanded, allRows, allCols } = f);
1195
+ ({ scratch, scust, stamp, touched, gen } = f);
1196
+ };
1197
+ /** The frame the engine's variables hold right now (null while a run or a data update is changing them). */
1198
+ let live = null;
1199
+ const within = (frame, fn) => {
1200
+ if (live === frame)
1201
+ return fn();
1202
+ const prev = capture();
1203
+ const prevLive = live;
1204
+ // Own scratch buffers: a suspended run (createPivotJob) may be using the live ones.
1205
+ if (frame.stamp === prev.stamp)
1206
+ Object.assign(frame, { scratch: new Float64Array(0), scust: null, stamp: new Int32Array(0), touched: new Int32Array(0), gen: 0 });
1207
+ restore(frame);
1208
+ live = frame;
1209
+ try {
1210
+ return fn();
1211
+ }
1212
+ finally {
1213
+ Object.assign(frame, capture());
1214
+ restore(prev);
1215
+ live = prevLive;
1216
+ }
1217
+ };
1218
+ // --- result
1219
+ let version = 0;
1220
+ const text2 = (s, label, fallback) => (s ?? fallback).replace('{label}', label);
1221
+ function makeResult() {
1222
+ const rl = layoutAxis(rowAx, true);
1223
+ const cl = layoutAxis(colAx, false);
1224
+ const ra = rowAx;
1225
+ const ca = colAx;
1226
+ const vals = values;
1227
+ const m = model;
1228
+ const pathCache = new Map();
1229
+ const keyOfPath = (ax, node) => {
1230
+ const tag = ax === ra ? node * 2 : node * 2 + 1;
1231
+ let s = pathCache.get(tag);
1232
+ if (s === undefined)
1233
+ pathCache.set(tag, (s = node === 0 ? '' : JSON.stringify(pathOf(ax, node))));
1234
+ return s;
1235
+ };
1236
+ const descKey = (L, ax, d) => {
1237
+ const kind = L.dk[d];
1238
+ const node = L.dn[d];
1239
+ const base = kind === 2 ? '' : keyOfPath(ax, node);
1240
+ const leafish = !L.dc[d] || (ax === ra && L.pk[L.dp[d]] === 1);
1241
+ const meas = L.dm[d] >= 0 && L.values ? vals[L.dm[d]].name : null;
1242
+ if (kind === 3 && L.dc[d])
1243
+ return `${base}||${meas}`;
1244
+ if (leafish && meas !== null)
1245
+ return `${base}|${meas}`;
1246
+ if (kind === 1)
1247
+ return `${base}|total`;
1248
+ return base;
1249
+ };
1250
+ const nodesCache = [new Map(), new Map()];
1251
+ const header = (axis, d) => {
1252
+ const L = axis === 'rows' ? rl : cl;
1253
+ const ax = axis === 'rows' ? ra : ca;
1254
+ const cache = nodesCache[axis === 'rows' ? 0 : 1];
1255
+ let h = cache.get(d);
1256
+ if (h)
1257
+ return h;
1258
+ const kind = L.dk[d];
1259
+ const node = L.dn[d];
1260
+ const depth = ax.depth[node];
1261
+ const level = depth > 0 ? ax.levels[depth - 1] : null;
1262
+ const memberLabel = level ? level.labels[ax.member[node]] : '';
1263
+ const label = kind === 3
1264
+ ? vals[L.dm[d]].caption
1265
+ : kind === 2
1266
+ ? text2(text.grandTotal, '', ENGINE_LABELS.grandTotalLabel)
1267
+ : kind === 1
1268
+ ? text2(text.total, memberLabel, ENGINE_LABELS.subtotalLabel)
1269
+ : memberLabel === BLANK_LABEL && text.blank
1270
+ ? text.blank
1271
+ : memberLabel;
1272
+ const kids = L.dc[d];
1273
+ const obj = {
1274
+ key: descKey(L, ax, d),
1275
+ axis,
1276
+ kind: DESC_KIND[kind],
1277
+ path: node === 0 ? [] : pathOf(ax, node),
1278
+ field: kind === 0 || kind === 1 ? (level?.name ?? null) : null,
1279
+ measure: L.dm[d] >= 0 && vals[L.dm[d]] ? vals[L.dm[d]].name : null,
1280
+ label,
1281
+ depth: L.dd[d],
1282
+ position: L.dp[d],
1283
+ span: L.ds[d],
1284
+ expandable: kind === 0 && depth < ax.D,
1285
+ expanded: kind === 0 && depth < ax.D && isOpenAt(ax, node),
1286
+ };
1287
+ if (kids) {
1288
+ let list = null;
1289
+ Object.defineProperty(obj, 'children', { enumerable: true, get: () => (list ??= kids.map((x) => header(axis, x))) });
1290
+ }
1291
+ cache.set(d, (h = Object.freeze(obj)));
1292
+ return h;
1293
+ };
1294
+ const openR = new Set(rowExpanded);
1295
+ const openC = new Set(colExpanded);
1296
+ const ar = allRows;
1297
+ const ac = allCols;
1298
+ const isOpenAt = (ax, node) => (ax === ra ? ar || openR.has(node) : ac || openC.has(node));
1299
+ const measureAt = (ri, ci) => (rl.pm[ri] >= 0 && rl.values ? rl.pm[ri] : cl.pm[ci]);
1300
+ const check = (ri, ci) => {
1301
+ if (!(ri >= 0 && ri < rl.pn.length && ci >= 0 && ci < cl.pn.length))
1302
+ throw new RangeError(`pivot cell (${ri}, ${ci}) is outside the result`);
1303
+ };
1304
+ const computed = (ri, ci) => {
1305
+ if (rl.pk[ri] === 3 || cl.pk[ci] === 3)
1306
+ return null;
1307
+ const k = measureAt(ri, ci);
1308
+ if (k < 0 || !vals[k])
1309
+ return null;
1310
+ return rawCell(rl.pn[ri], cl.pn[ci], k);
1311
+ };
1312
+ const fmt = (k, v) => {
1313
+ if (v === null || k < 0)
1314
+ return '';
1315
+ const spec = vals[k];
1316
+ const calc = m.calculatedFields.find((c) => c.name === spec.field.field);
1317
+ const f = m.formats[spec.name] ?? m.formats[spec.field.field] ?? calc?.format;
1318
+ const kind = spec.field.showAs?.kind;
1319
+ const opts = f?.number ?? (kind && PERCENT.has(kind) ? { style: 'percent', maximumFractionDigits: 2 } : { maximumFractionDigits: 2 });
1320
+ return numberFormat(env, opts, f?.locale).format(v);
1321
+ };
1322
+ const cellOf = (ri, ci) => {
1323
+ check(ri, ci);
1324
+ const k = measureAt(ri, ci);
1325
+ const raw = computed(ri, ci);
1326
+ const value = raw === null || k < 0 ? raw : showAs(k, rl.pn[ri], cl.pn[ci], raw);
1327
+ const rk = rl.pk[ri];
1328
+ const ck = cl.pk[ci];
1329
+ const kind = CELL_KIND[Math.max(rk === 2 || ck === 2 ? 2 : 0, rk === 1 || rk === 3 || ck === 1 ? 1 : 0)];
1330
+ const p = profiles[rl.pn[ri]];
1331
+ const j = p ? lookup(p, cl.pn[ci]) : -1;
1332
+ const cell = {
1333
+ rowIndex: ri,
1334
+ columnIndex: ci,
1335
+ rowKey: header('rows', rl.ph[ri]).key,
1336
+ columnKey: header('columns', cl.ph[ci]).key,
1337
+ measure: k >= 0 && vals[k] ? vals[k].name : null,
1338
+ value,
1339
+ rawValue: raw,
1340
+ formattedValue: fmt(k, value),
1341
+ kind,
1342
+ rowCount: p && j !== -1 ? p.st[j * stride] : 0,
1343
+ };
1344
+ if (!options.getCellValue)
1345
+ return cell;
1346
+ const over = options.getCellValue(cell);
1347
+ return over === value ? cell : { ...cell, value: over, formattedValue: fmt(k, over) };
1348
+ };
1349
+ const result = {
1350
+ version: ++version,
1351
+ model: m,
1352
+ rowCount: rl.pn.length,
1353
+ columnCount: cl.pn.length,
1354
+ get rowTree() {
1355
+ return rl.roots.map((d) => header('rows', d));
1356
+ },
1357
+ get columnTree() {
1358
+ return cl.roots.map((d) => header('columns', d));
1359
+ },
1360
+ columnDepth: cl.depth,
1361
+ rowDepth: rl.depth,
1362
+ errors,
1363
+ memberAt(axis, index) {
1364
+ const L = axis === 'rows' ? rl : cl;
1365
+ if (!(index >= 0 && index < L.pn.length))
1366
+ throw new RangeError(`pivot ${axis} position ${index} is outside the result`);
1367
+ return header(axis, L.ph[index]);
1368
+ },
1369
+ valueAt(ri, ci) {
1370
+ check(ri, ci);
1371
+ return within(frame, () => {
1372
+ if (options.getCellValue)
1373
+ return cellOf(ri, ci).value;
1374
+ const raw = computed(ri, ci);
1375
+ return raw === null ? null : showAs(measureAt(ri, ci), rl.pn[ri], cl.pn[ci], raw);
1376
+ });
1377
+ },
1378
+ cellAt: (ri, ci) => within(frame, () => cellOf(ri, ci)),
1379
+ rowsAt(ri, ci) {
1380
+ check(ri, ci);
1381
+ return within(frame, () => core.rowsAt(rl.pn[ri], cl.pn[ci]));
1382
+ },
1383
+ };
1384
+ const frame = capture();
1385
+ live = frame;
1386
+ return Object.freeze(result);
1387
+ }
1388
+ // --- compute
1389
+ const core = {
1390
+ get rows() {
1391
+ return rows;
1392
+ },
1393
+ set rows(next) {
1394
+ live = null;
1395
+ rows = next;
1396
+ },
1397
+ get model() {
1398
+ return model;
1399
+ },
1400
+ set model(next) {
1401
+ live = null;
1402
+ model = next;
1403
+ },
1404
+ result: null,
1405
+ progress: 0,
1406
+ reset,
1407
+ diagnostics: () => ({ rows: rows.length, units: units ? units.count : view ? view.order.length : 0, compressed: units !== null, fullComputes: stats.full, incrementalUpdates: stats.incremental }),
1408
+ *compute() {
1409
+ live = null;
1410
+ core.progress = 0;
1411
+ env = { locale, formats: model.formats, cache: fmtCache };
1412
+ rowAx = yield* buildAxis(model.rows);
1413
+ core.progress = 0.25;
1414
+ colAx = yield* buildAxis(model.columns);
1415
+ core.progress = 0.4;
1416
+ setupMeasures();
1417
+ const msig = `${measures.map((x) => x.key).join('|')}`;
1418
+ const maskSig = `${rowAx.sig}\u0002${colAx.sig}\u0002${json(model.filterBy)}\u0002${json(model.filters)}\u0002${msig}\u0002${json(model.calculatedFields)}`;
1419
+ const baseSig = maskSig.replace(json(model.filterBy), '');
1420
+ if (maskSig !== sigs.mask || !view) {
1421
+ // A member or label filter change on row fields only: keep the profiles of
1422
+ // row nodes below an unchanged member of every changed level.
1423
+ const prevLevels = filterLevels;
1424
+ const prevBy = lastFilterBy;
1425
+ const names = new Set([...Object.keys(prevBy), ...Object.keys(model.filterBy)].filter((k) => json(prevBy[k]) !== json(model.filterBy[k])));
1426
+ const rowLevel = (name) => rowAx.levels.findIndex((l) => l.name === name);
1427
+ const reuse = view !== null &&
1428
+ baseSig === sigs.base &&
1429
+ ![...Object.values(prevBy), ...Object.values(model.filterBy)].some((f) => 'value' in f) &&
1430
+ [...names].every((n) => rowLevel(n) !== -1);
1431
+ yield* buildMask();
1432
+ yield* buildViews();
1433
+ stats.full++;
1434
+ if (reuse) {
1435
+ const changed = [...names].map((n) => {
1436
+ const l = rowLevel(n);
1437
+ const level = rowAx.levels[l];
1438
+ const was = prevLevels.find((f) => f.level === level)?.allowed;
1439
+ const now2 = filterLevels.find((f) => f.level === level)?.allowed;
1440
+ const set = new Set();
1441
+ for (let m = 0; m < level.keys.length; m++)
1442
+ if ((was ? was(m) : true) !== (now2 ? now2(m) : true))
1443
+ set.add(m);
1444
+ return { depth: l + 1, set };
1445
+ });
1446
+ // A copy: older results keep the profiles of their own mask.
1447
+ profiles = profiles.slice();
1448
+ for (let x = 0; x < profiles.length; x++) {
1449
+ if (!profiles[x])
1450
+ continue;
1451
+ const keep = changed.every(({ depth, set }) => rowAx.depth[x] >= depth && !set.has(rowAx.member[ancestor(rowAx, x, depth)]));
1452
+ if (!keep)
1453
+ profiles[x] = undefined;
1454
+ }
1455
+ }
1456
+ else
1457
+ profiles = [];
1458
+ sigs.mask = maskSig;
1459
+ sigs.base = baseSig;
1460
+ lastFilterBy = model.filterBy;
1461
+ lazy = new Map();
1462
+ sigs.sort = '';
1463
+ }
1464
+ core.progress = 0.7;
1465
+ resolveExpanded();
1466
+ const vs = model.valueSort;
1467
+ valueSortCol = vs ? (vs.columnKey === '' || vs.columnKey.startsWith('|') ? 0 : nodeOf(colAx, safePath(vs.columnKey))) : -1;
1468
+ valueSortMeasure = vs ? valueIndex(vs.measure) : -1;
1469
+ const sortSig = `${json(model.sort)}${json(vs)}${model.showEmptyMembers}`;
1470
+ if (sortSig !== sigs.sort)
1471
+ (kidsCache = new Map()), (sigs.sort = sortSig);
1472
+ // Profiles of every visible row node, resumable (each from its own units).
1473
+ const stack = [0];
1474
+ const frontier = [];
1475
+ const opened = [];
1476
+ while (stack.length) {
1477
+ const r = stack.pop();
1478
+ if (isOpen(rowAx, r) && rowAx.kids[r]?.length) {
1479
+ opened.push(r);
1480
+ if (r !== 0 && !profiles[r])
1481
+ frontier.push(r);
1482
+ for (const k of rowAx.kids[r])
1483
+ if ((view.rows[k] ?? 0) > 0)
1484
+ stack.push(k);
1485
+ }
1486
+ else if (!profiles[r])
1487
+ frontier.push(r);
1488
+ }
1489
+ for (let x = 0; x < frontier.length; x++) {
1490
+ const r = frontier[x];
1491
+ if (!profiles[r])
1492
+ profiles[r] = yield* fromUnits(r);
1493
+ core.progress = 0.7 + (0.25 * x) / frontier.length;
1494
+ yield x;
1495
+ }
1496
+ for (let x = opened.length - 1; x >= 0; x--)
1497
+ ensure(opened[x]);
1498
+ core.result = makeResult();
1499
+ core.progress = 1;
1500
+ return core.result;
1501
+ },
1502
+ fields() {
1503
+ const out = [];
1504
+ for (const f of fieldOrder) {
1505
+ const d = defs.get(f);
1506
+ const info = {
1507
+ field: f,
1508
+ caption: d?.caption ?? f,
1509
+ type: typeOf(f),
1510
+ hidden: d?.hidden === true,
1511
+ sortable: d?.sortable !== false,
1512
+ filterable: d?.filterable !== false,
1513
+ removable: d?.removable !== false,
1514
+ draggable: d?.draggable !== false,
1515
+ ...(d?.folder !== undefined ? { folder: d.folder } : {}),
1516
+ get memberCount() {
1517
+ return drain(fieldIndex(f)).keys.length;
1518
+ },
1519
+ };
1520
+ out.push(info);
1521
+ }
1522
+ return out;
1523
+ },
1524
+ members(field, opts = {}) {
1525
+ const base = [...model.rows, ...model.columns, ...model.filters].map((f) => f.field).find((f) => levelNames(f, model.groups[f]).includes(field)) ?? field;
1526
+ const levels = drain(levelsOf(base));
1527
+ const level = levels.find((l) => l.name === field) ?? levels[0];
1528
+ if (!level)
1529
+ return [];
1530
+ const counts = new Array(level.keys.length).fill(0);
1531
+ level.base.counts.forEach((c, b) => (counts[level.remap ? level.remap[b] : b] += c));
1532
+ const ranks = ranksOf(level);
1533
+ const search = opts.search?.toLowerCase();
1534
+ let list = level.keys.map((_, m) => m).filter((m) => counts[m] > 0 && (!search || level.labels[m].toLowerCase().includes(search)));
1535
+ list.sort((a, b) => ranks[a] - ranks[b]);
1536
+ if (opts.limit !== undefined)
1537
+ list = list.slice(0, opts.limit);
1538
+ return list.map((m) => Object.freeze({ key: level.keys[m], label: level.labels[m], count: counts[m] }));
1539
+ },
1540
+ setRows(next) {
1541
+ live = null;
1542
+ const prev = rows;
1543
+ rows = next;
1544
+ if (!incremental(prev, next)) {
1545
+ if (!options.fields && (prev.length === 0 || next.length === 0))
1546
+ setDefs();
1547
+ reset();
1548
+ }
1549
+ },
1550
+ rowsAt(r, c) {
1551
+ const rv = getRawView();
1552
+ const s = rv.start[r] ?? 0;
1553
+ const e = s + (rv.units[r] ?? 0);
1554
+ const out = [];
1555
+ const depth = colAx.depth[c] ?? 0;
1556
+ for (let x = s; x < e; x++) {
1557
+ const i = rv.order[x];
1558
+ if (c === 0 || ancestor(colAx, colAx.leaf[i], depth) === c)
1559
+ out.push(i);
1560
+ }
1561
+ return out;
1562
+ },
1563
+ expandedPaths(axis, all) {
1564
+ const ax = axis === 'rows' ? rowAx : colAx;
1565
+ const out = [];
1566
+ for (let node = 1; node < ax.parent.length; node++) {
1567
+ if (ax.depth[node] >= ax.D)
1568
+ continue;
1569
+ if (all || isOpen(ax, node))
1570
+ out.push([axis, ...pathOf(ax, node)]);
1571
+ }
1572
+ return out;
1573
+ },
1574
+ };
1575
+ /** Applies a small row delta in place; returns false when a full recompute is needed. */
1576
+ function incremental(prev, next) {
1577
+ if (!view || !rowAx || !prev.length || next.length < prev.length || Object.values(model.filterBy).some((f) => 'value' in f))
1578
+ return false;
1579
+ const changed = [];
1580
+ const limit = Math.max(32, prev.length >> 6);
1581
+ for (let i = 0; i < prev.length; i++)
1582
+ if (prev[i] !== next[i] && changed.push(i) > limit)
1583
+ return false;
1584
+ const appended = next.length - prev.length;
1585
+ if (changed.length + appended > limit)
1586
+ return false;
1587
+ // Older results keep their own profiles, lazy cells and mask (copies, not the whole state).
1588
+ live = null;
1589
+ profiles = profiles.slice();
1590
+ lazy = new Map(lazy);
1591
+ if (mask && !appended)
1592
+ mask = mask.slice();
1593
+ const touchedRows = [...changed];
1594
+ for (let i = prev.length; i < next.length; i++)
1595
+ touchedRows.push(i);
1596
+ // Old contributions, read before any index changes.
1597
+ const old = new Map();
1598
+ for (const i of changed)
1599
+ old.set(i, { r: rowAx.leaf[i], c: colAx.leaf[i], pass: !mask || mask[i] === 1 });
1600
+ const affected = new Set();
1601
+ const adjust = (r) => {
1602
+ for (let x = r; x !== -1; x = rowAx.parent[x]) {
1603
+ const p = profiles[x];
1604
+ lazy.forEach((_, key) => Math.floor(key / Math.max(1, measures.length)) === x && lazy.delete(key));
1605
+ if (p)
1606
+ (profiles[x] = undefined), affected.add(x);
1607
+ }
1608
+ };
1609
+ // Subtract with the old rows' values.
1610
+ const saved = rows;
1611
+ rows = prev;
1612
+ for (const i of changed)
1613
+ if (old.get(i).pass)
1614
+ adjust(old.get(i).r);
1615
+ rows = saved;
1616
+ // Re-encode the touched rows in every cached index.
1617
+ for (const idx of fieldIdx.values()) {
1618
+ if (appended) {
1619
+ const ids = new Int32Array(next.length);
1620
+ ids.set(idx.ids);
1621
+ idx.ids = ids;
1622
+ }
1623
+ for (const i of touchedRows) {
1624
+ if (i < prev.length)
1625
+ idx.counts[idx.ids[i]]--;
1626
+ idx.ids[i] = encodeRow(idx, next, i);
1627
+ }
1628
+ }
1629
+ for (const [f, arr] of numCache) {
1630
+ const get = getterOf(defs.get(f), f);
1631
+ const out = appended ? new Float64Array(next.length) : arr;
1632
+ if (appended)
1633
+ out.set(arr);
1634
+ for (const i of touchedRows)
1635
+ numbersOf(next.slice(i, i + 1), get, out.subarray(i, i + 1));
1636
+ numCache.set(f, out);
1637
+ }
1638
+ // Measures hold their numbers by reference: refresh after the realloc.
1639
+ for (const level of levelCache.values()) {
1640
+ if (!level.remap) {
1641
+ level.of(0);
1642
+ level.ids = level.base.ids;
1643
+ }
1644
+ else {
1645
+ if (appended) {
1646
+ const ids = new Int32Array(next.length);
1647
+ ids.set(level.ids);
1648
+ level.ids = ids;
1649
+ }
1650
+ for (const i of touchedRows)
1651
+ level.ids[i] = level.of(level.base.ids[i]);
1652
+ }
1653
+ }
1654
+ let moved = appended > 0;
1655
+ for (const ax of axisCache.values()) {
1656
+ if (appended) {
1657
+ const leaf = new Int32Array(next.length);
1658
+ leaf.set(ax.leaf);
1659
+ ax.leaf = leaf;
1660
+ }
1661
+ for (const i of touchedRows) {
1662
+ let node = 0;
1663
+ for (let l = 0; l < ax.D; l++)
1664
+ node = childOf(ax, node, ax.levels[l].ids[i], true);
1665
+ if (ax === rowAx || ax === colAx)
1666
+ if (ax.leaf[i] !== node)
1667
+ moved = true;
1668
+ ax.leaf[i] = node;
1669
+ }
1670
+ }
1671
+ setupMeasures();
1672
+ if (mask) {
1673
+ if (appended) {
1674
+ const m2 = new Uint8Array(next.length);
1675
+ m2.set(mask);
1676
+ mask = m2;
1677
+ }
1678
+ for (const i of touchedRows) {
1679
+ const pass = filterLevels.every((f) => f.allowed(f.level.ids[i])) ? 1 : 0;
1680
+ if (i >= prev.length || pass !== mask[i])
1681
+ moved = true;
1682
+ mask[i] = pass;
1683
+ }
1684
+ }
1685
+ for (const i of touchedRows)
1686
+ if (!mask || mask[i])
1687
+ adjust(rowAx.leaf[i]);
1688
+ stats.incremental++;
1689
+ if (moved || units) {
1690
+ // Ranges changed: rebuild the unit views, keep the surviving profiles.
1691
+ drain(buildViews());
1692
+ for (const x of affected)
1693
+ profiles[x] = undefined;
1694
+ for (let x = 0; x < profiles.length; x++) {
1695
+ const p = profiles[x];
1696
+ if (p === EMPTY_PROFILE && (view.rows[x] ?? 0) > 0)
1697
+ profiles[x] = undefined;
1698
+ }
1699
+ }
1700
+ kidsCache = new Map();
1701
+ return true;
1702
+ }
1703
+ return core;
1704
+ }
1705
+ /**
1706
+ * Measure id of the value field at `k` (types.ts "Measure ids"): the field,
1707
+ * `field#aggregate` when another value field uses the same field, and
1708
+ * `field#aggregate#k` when even that repeats.
1709
+ */
1710
+ export function measureId(values, k) {
1711
+ const v = values[k];
1712
+ const same = values.filter((x) => x.field === v.field);
1713
+ if (same.length === 1)
1714
+ return v.field;
1715
+ const id = `${v.field}#${v.aggregate}`;
1716
+ return same.filter((x) => x.aggregate === v.aggregate).length === 1 ? id : `${id}#${k}`;
1717
+ }
1718
+ const safePath = (key) => {
1719
+ const end = key.lastIndexOf(']');
1720
+ try {
1721
+ const v = JSON.parse(end === -1 ? key : key.slice(0, end + 1));
1722
+ return Array.isArray(v) ? v : [];
1723
+ }
1724
+ catch {
1725
+ return [];
1726
+ }
1727
+ };
1728
+ function childOf(ax, parent, member, create) {
1729
+ let id;
1730
+ if (parent === 0) {
1731
+ id = ax.top[member] ?? -1;
1732
+ if (id !== -1 || !create)
1733
+ return id;
1734
+ }
1735
+ else {
1736
+ id = ax.map.get(parent, member);
1737
+ if (id !== -1 || !create)
1738
+ return id;
1739
+ }
1740
+ id = ax.parent.length;
1741
+ ax.parent.push(parent);
1742
+ ax.member.push(member);
1743
+ ax.depth.push(ax.depth[parent] + 1);
1744
+ (ax.kids[parent] ??= []).push(id);
1745
+ if (parent === 0)
1746
+ ax.top[member] = id;
1747
+ else
1748
+ ax.map.put(parent, member, id);
1749
+ return id;
1750
+ }
1751
+ // ---------------------------------------------------------------------------
1752
+ // Public engine.
1753
+ const samePath = (a, b) => a.length === b.length && a.every((x, i) => json(x) === json(b[i]));
1754
+ export function createPivotEngine(options) {
1755
+ const core = createPivotCore(options);
1756
+ const listeners = new Set();
1757
+ let result = drain(core.compute());
1758
+ const commit = () => {
1759
+ const next = drain(core.compute());
1760
+ if (next !== result) {
1761
+ result = next;
1762
+ for (const l of [...listeners])
1763
+ l();
1764
+ }
1765
+ return result;
1766
+ };
1767
+ const setModel = (input) => {
1768
+ const next = normalizePivotModel(typeof input === 'function' ? input(core.model) : input);
1769
+ if (JSON.stringify(next) === JSON.stringify(core.model))
1770
+ return result;
1771
+ core.model = next;
1772
+ return commit();
1773
+ };
1774
+ const expandedOf = (axis) => (core.model.expanded === 'all' ? core.expandedPaths(axis, true) : core.model.expanded.filter((p) => p[0] === axis));
1775
+ const other = (axis) => expandedOf(axis === 'rows' ? 'columns' : 'rows');
1776
+ return {
1777
+ subscribe(listener) {
1778
+ listeners.add(listener);
1779
+ return () => listeners.delete(listener);
1780
+ },
1781
+ getSnapshot: () => result,
1782
+ getModel: () => core.model,
1783
+ getFields: () => core.fields(),
1784
+ getMembers: (field, opts) => core.members(field, opts),
1785
+ setModel,
1786
+ setData(rows) {
1787
+ if (rows === core.rows)
1788
+ return result;
1789
+ core.setRows(rows);
1790
+ return commit();
1791
+ },
1792
+ expand(path) {
1793
+ if (core.model.expanded === 'all')
1794
+ return result;
1795
+ if (core.model.expanded.some((p) => samePath(p, path)))
1796
+ return result;
1797
+ return setModel((m) => ({ ...m, expanded: [...m.expanded, path] }));
1798
+ },
1799
+ collapse(path) {
1800
+ const list = core.model.expanded === 'all' ? [...core.expandedPaths('rows', true), ...core.expandedPaths('columns', true)] : core.model.expanded;
1801
+ return setModel((m) => ({ ...m, expanded: list.filter((p) => !samePath(p, path)) }));
1802
+ },
1803
+ expandAll(axis) {
1804
+ if (!axis)
1805
+ return setModel((m) => ({ ...m, expanded: 'all' }));
1806
+ return setModel((m) => ({ ...m, expanded: [...other(axis), ...core.expandedPaths(axis, true)] }));
1807
+ },
1808
+ collapseAll(axis) {
1809
+ return setModel((m) => ({ ...m, expanded: axis ? other(axis) : [] }));
1810
+ },
1811
+ getRawRows: (indexes) => indexes.map((i) => core.rows[i]),
1812
+ drillThrough: (ri, ci) => result.rowsAt(ri, ci).map((i) => core.rows[i]),
1813
+ refresh() {
1814
+ core.reset();
1815
+ return commit();
1816
+ },
1817
+ destroy() {
1818
+ listeners.clear();
1819
+ },
1820
+ getDiagnostics: () => core.diagnostics(),
1821
+ };
1822
+ }
1823
+ /** One-shot compute (SSR, servers). */
1824
+ export function computePivot(options) {
1825
+ return drain(createPivotCore(options).compute());
1826
+ }
1827
+ /** A resumable compute for time slicing on the main thread or a Worker. */
1828
+ export function createPivotJob(options) {
1829
+ const core = createPivotCore(options);
1830
+ const gen = core.compute();
1831
+ let out = null;
1832
+ return {
1833
+ run(budgetMs) {
1834
+ const end = now() + budgetMs;
1835
+ while (!out) {
1836
+ const step = gen.next();
1837
+ if (step.done)
1838
+ out = step.value;
1839
+ else if (now() >= end)
1840
+ break;
1841
+ }
1842
+ return { done: out !== null, progress: out ? 1 : core.progress };
1843
+ },
1844
+ result() {
1845
+ if (!out)
1846
+ throw new Error('pivot job is not done; call run() until done');
1847
+ return out;
1848
+ },
1849
+ };
1850
+ }
1851
+ //# sourceMappingURL=engine.js.map