@svgrid/enterprise 1.0.1
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 +97 -0
- package/README.md +37 -0
- package/package.json +72 -0
- package/src/ai.test.ts +522 -0
- package/src/ai.ts +782 -0
- package/src/export.ts +512 -0
- package/src/import.test.ts +415 -0
- package/src/import.ts +648 -0
- package/src/index.ts +88 -0
- package/src/install.ts +114 -0
- package/src/license.ts +90 -0
- package/src/pdfmake-shims.d.ts +22 -0
- package/src/pivot.test.ts +308 -0
- package/src/pivot.ts +549 -0
- package/src/print.ts +127 -0
- package/src/revoked.ts +49 -0
- package/src/smart-shim.ts +105 -0
- package/src/smart.export.d.ts +5 -0
- package/src/smart.export.js +7 -0
- package/src/staged-editing.ts +0 -0
- package/src/upgrade-prompt.test.ts +71 -0
- package/src/upgrade-prompt.ts +148 -0
- package/src/watermark.test.ts +97 -0
- package/src/watermark.ts +156 -0
package/src/pivot.ts
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pivot table (@svgrid/enterprise).
|
|
3
|
+
*
|
|
4
|
+
* Turns a flat array of rows + a pivot config into:
|
|
5
|
+
* - `rows`: a flat array of pivot rows (group, subtotal, leaf, grand
|
|
6
|
+
* total) suitable for `<SvGrid data={rows} />`.
|
|
7
|
+
* - `columns`: a nested-header column tree suitable for
|
|
8
|
+
* `<SvGrid columns={columns} />` - one column per (col-axis path
|
|
9
|
+
* × value-measure) plus the row-axis "Header" first column.
|
|
10
|
+
*
|
|
11
|
+
* No DOM, no rendering. The grid renders the result with its
|
|
12
|
+
* `columns: ColumnDef[]` + `data: PivotRow[]` like any other dataset.
|
|
13
|
+
*
|
|
14
|
+
* Usage:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { createPivotModel } from '@svgrid/enterprise'
|
|
18
|
+
*
|
|
19
|
+
* const pivot = createPivotModel(orders, {
|
|
20
|
+
* rows: ['region', 'salesPerson'],
|
|
21
|
+
* cols: ['quarter'],
|
|
22
|
+
* values: [
|
|
23
|
+
* { field: 'amount', agg: 'sum', label: 'Total', format: { type: 'currency', currency: 'USD' } },
|
|
24
|
+
* { field: 'amount', agg: 'avg', label: 'Avg' },
|
|
25
|
+
* ],
|
|
26
|
+
* })
|
|
27
|
+
*
|
|
28
|
+
* // then:
|
|
29
|
+
* <SvGrid data={pivot.rows} columns={pivot.columns} features={features} />
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
import type { ColumnDef, CellFormatConfig, RowData, TableFeatures } from '@svgrid/grid'
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------- types
|
|
35
|
+
|
|
36
|
+
export type PivotAggregatorId =
|
|
37
|
+
| 'sum'
|
|
38
|
+
| 'avg'
|
|
39
|
+
| 'min'
|
|
40
|
+
| 'max'
|
|
41
|
+
| 'count'
|
|
42
|
+
| 'countDistinct'
|
|
43
|
+
| 'first'
|
|
44
|
+
| 'last'
|
|
45
|
+
|
|
46
|
+
export type PivotAggregator = (values: ReadonlyArray<unknown>) => unknown
|
|
47
|
+
|
|
48
|
+
export type PivotValueConfig<TData> = {
|
|
49
|
+
/** Row field whose values get aggregated. */
|
|
50
|
+
field: keyof TData & string
|
|
51
|
+
/** Built-in aggregator id, or a custom reducer. */
|
|
52
|
+
agg: PivotAggregatorId | PivotAggregator
|
|
53
|
+
/** Display name in the column header. Defaults to `${field} (${agg})`. */
|
|
54
|
+
label?: string
|
|
55
|
+
/** Optional cell formatter. */
|
|
56
|
+
format?: CellFormatConfig
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type PivotConfig<TData> = {
|
|
60
|
+
/** Outer-most first. Each entry becomes one level of row grouping. */
|
|
61
|
+
rows: ReadonlyArray<keyof TData & string>
|
|
62
|
+
/** Outer-most first. Each entry becomes one level of column grouping. */
|
|
63
|
+
cols: ReadonlyArray<keyof TData & string>
|
|
64
|
+
/** One or more measures aggregated under each column-axis leaf. */
|
|
65
|
+
values: ReadonlyArray<PivotValueConfig<TData>>
|
|
66
|
+
/** Grand-total row at the bottom. Default `true`. */
|
|
67
|
+
grandTotalRow?: boolean
|
|
68
|
+
/** Grand-total column on the right. Default `true`. */
|
|
69
|
+
grandTotalCol?: boolean
|
|
70
|
+
/** Subtotal rows between row groups. Default `true`. */
|
|
71
|
+
rowSubtotals?: boolean
|
|
72
|
+
/** Optional sort for column-axis values per dim level (defaults to alpha). */
|
|
73
|
+
colSort?: (a: unknown, b: unknown, level: number) => number
|
|
74
|
+
/** Optional sort for row-axis values per dim level (defaults to alpha). */
|
|
75
|
+
rowSort?: (a: unknown, b: unknown, level: number) => number
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type PivotRowKind = 'group' | 'subtotal' | 'leaf' | 'grandTotal'
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Shape of one entry in `result.rows`. The first-column label lives at
|
|
82
|
+
* `__pivotLabel`; every value cell lives at the column id matching the
|
|
83
|
+
* leaf column generated for its (col-path × measure).
|
|
84
|
+
*
|
|
85
|
+
* `__pivotParentId` is the `__pivotId` of the row's row-axis parent
|
|
86
|
+
* (or `null` for top-level groups, the grand-total row, and the one
|
|
87
|
+
* synthetic "All" row when no row dims are configured). Use it with
|
|
88
|
+
* `filterCollapsedPivotRows` to hide leaves whose ancestor is
|
|
89
|
+
* collapsed - that's how expandable pivots are built on top of the
|
|
90
|
+
* model.
|
|
91
|
+
*
|
|
92
|
+
* `__pivotExpandable` is `true` for `group` rows that have at least
|
|
93
|
+
* one descendant. A renderer uses this to decide whether to show a
|
|
94
|
+
* chevron next to the label.
|
|
95
|
+
*/
|
|
96
|
+
export type PivotRow = {
|
|
97
|
+
__pivotId: string
|
|
98
|
+
__pivotKind: PivotRowKind
|
|
99
|
+
__pivotDepth: number
|
|
100
|
+
__pivotLabel: string
|
|
101
|
+
__pivotParentId: string | null
|
|
102
|
+
__pivotExpandable: boolean
|
|
103
|
+
/** Aggregated value cells - keyed by leaf column id. */
|
|
104
|
+
[columnId: string]: unknown
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export type PivotResult<TFeatures extends TableFeatures> = {
|
|
108
|
+
rows: PivotRow[]
|
|
109
|
+
columns: Array<ColumnDef<TFeatures, PivotRow>>
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// -------------------------------------------------------- aggregators
|
|
113
|
+
|
|
114
|
+
const numeric = (vs: ReadonlyArray<unknown>): number[] =>
|
|
115
|
+
vs
|
|
116
|
+
.map((v) => (typeof v === 'number' ? v : Number(v)))
|
|
117
|
+
.filter((n): n is number => !Number.isNaN(n))
|
|
118
|
+
|
|
119
|
+
const BUILT_IN_AGGS: Record<PivotAggregatorId, PivotAggregator> = {
|
|
120
|
+
sum: (vs) => numeric(vs).reduce((a, b) => a + b, 0),
|
|
121
|
+
avg: (vs) => {
|
|
122
|
+
const ns = numeric(vs)
|
|
123
|
+
return ns.length === 0 ? null : ns.reduce((a, b) => a + b, 0) / ns.length
|
|
124
|
+
},
|
|
125
|
+
min: (vs) => (numeric(vs).length === 0 ? null : Math.min(...numeric(vs))),
|
|
126
|
+
max: (vs) => (numeric(vs).length === 0 ? null : Math.max(...numeric(vs))),
|
|
127
|
+
count: (vs) => vs.length,
|
|
128
|
+
countDistinct: (vs) => new Set(vs).size,
|
|
129
|
+
first: (vs) => vs[0] ?? null,
|
|
130
|
+
last: (vs) => vs[vs.length - 1] ?? null,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function resolveAgg(agg: PivotAggregatorId | PivotAggregator): PivotAggregator {
|
|
134
|
+
if (typeof agg === 'function') return agg
|
|
135
|
+
const fn = BUILT_IN_AGGS[agg]
|
|
136
|
+
if (!fn) throw new Error(`pivot: unknown aggregator '${String(agg)}'`)
|
|
137
|
+
return fn
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// --------------------------------------------------- axis-tree helpers
|
|
141
|
+
|
|
142
|
+
type AxisNode = {
|
|
143
|
+
/** Dimension level (index into config.cols / config.rows). 0 at root. */
|
|
144
|
+
level: number
|
|
145
|
+
/** Dim value at this node (root has value `null`). */
|
|
146
|
+
value: unknown
|
|
147
|
+
/** Path of values from root to this node (excluding root). */
|
|
148
|
+
path: ReadonlyArray<unknown>
|
|
149
|
+
/** Stable string id for the path. */
|
|
150
|
+
pathKey: string
|
|
151
|
+
/** Direct children, keyed by stringified value. */
|
|
152
|
+
children: Map<string, AxisNode>
|
|
153
|
+
/** Rows reaching this node (leaf or otherwise). */
|
|
154
|
+
rows: unknown[]
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function defaultCompare(a: unknown, b: unknown): number {
|
|
158
|
+
if (a === b) return 0
|
|
159
|
+
if (a == null) return -1
|
|
160
|
+
if (b == null) return 1
|
|
161
|
+
if (typeof a === 'number' && typeof b === 'number') return a - b
|
|
162
|
+
return String(a).localeCompare(String(b), undefined, { numeric: true })
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function buildAxisTree<TData>(
|
|
166
|
+
rows: ReadonlyArray<TData>,
|
|
167
|
+
fields: ReadonlyArray<string>,
|
|
168
|
+
sortBy: ((a: unknown, b: unknown, level: number) => number) | undefined,
|
|
169
|
+
): AxisNode {
|
|
170
|
+
const root: AxisNode = {
|
|
171
|
+
level: 0, value: null, path: [], pathKey: '__root',
|
|
172
|
+
children: new Map(), rows: rows as unknown[],
|
|
173
|
+
}
|
|
174
|
+
for (const row of rows as ReadonlyArray<Record<string, unknown>>) {
|
|
175
|
+
let node = root
|
|
176
|
+
for (let i = 0; i < fields.length; i += 1) {
|
|
177
|
+
const field = fields[i]!
|
|
178
|
+
const value = row[field]
|
|
179
|
+
const key = `${i}:${value === null ? '__null' : String(value)}`
|
|
180
|
+
let child = node.children.get(key)
|
|
181
|
+
if (!child) {
|
|
182
|
+
child = {
|
|
183
|
+
level: i + 1,
|
|
184
|
+
value,
|
|
185
|
+
path: [...node.path, value],
|
|
186
|
+
pathKey: node.pathKey === '__root' ? key : `${node.pathKey}|${key}`,
|
|
187
|
+
children: new Map(),
|
|
188
|
+
rows: [],
|
|
189
|
+
}
|
|
190
|
+
node.children.set(key, child)
|
|
191
|
+
}
|
|
192
|
+
child.rows.push(row)
|
|
193
|
+
node = child
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// Stable, predictable child order at every level.
|
|
197
|
+
sortNode(root, sortBy)
|
|
198
|
+
return root
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function sortNode(
|
|
202
|
+
node: AxisNode,
|
|
203
|
+
sortBy: ((a: unknown, b: unknown, level: number) => number) | undefined,
|
|
204
|
+
): void {
|
|
205
|
+
const entries = Array.from(node.children.entries())
|
|
206
|
+
entries.sort(([, a], [, b]) => (sortBy ?? defaultCompare)(a.value, b.value, a.level - 1))
|
|
207
|
+
node.children = new Map(entries)
|
|
208
|
+
for (const child of node.children.values()) sortNode(child, sortBy)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// --------------------------------------------------- column id helpers
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Generate stable leaf column ids by joining the column-axis path and the
|
|
215
|
+
* measure index. The id is what appears as `data-col-id` and as the key
|
|
216
|
+
* inside each pivot row. Kept short and deterministic.
|
|
217
|
+
*/
|
|
218
|
+
function leafColumnId(colPath: ReadonlyArray<unknown>, measureIndex: number): string {
|
|
219
|
+
const path = colPath.length === 0 ? 'all' : colPath.map((v) => safe(v)).join('__')
|
|
220
|
+
return `pv__${path}__m${measureIndex}`
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function safe(v: unknown): string {
|
|
224
|
+
if (v === null || v === undefined) return 'null'
|
|
225
|
+
return String(v).replace(/[^a-zA-Z0-9_-]/g, '_')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// --------------------------------------------------- column-tree build
|
|
229
|
+
|
|
230
|
+
function buildColumnTree<TFeatures extends TableFeatures>(
|
|
231
|
+
colRoot: AxisNode,
|
|
232
|
+
values: ReadonlyArray<PivotValueConfig<unknown>>,
|
|
233
|
+
config: PivotConfig<unknown>,
|
|
234
|
+
rowHeaderLabel: string,
|
|
235
|
+
): Array<ColumnDef<TFeatures, PivotRow>> {
|
|
236
|
+
// First column: the row-axis tree as a single column. The label per row
|
|
237
|
+
// comes from `__pivotLabel`, with `__pivotDepth` driving the indent.
|
|
238
|
+
const headerCol: ColumnDef<TFeatures, PivotRow> = {
|
|
239
|
+
id: '__pivotRowHeader',
|
|
240
|
+
header: rowHeaderLabel,
|
|
241
|
+
accessorFn: (row) => row.__pivotLabel,
|
|
242
|
+
width: 240,
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function recurse(node: AxisNode): Array<ColumnDef<TFeatures, PivotRow>> {
|
|
246
|
+
// If this is a column-axis leaf (no children), emit one value column
|
|
247
|
+
// per measure.
|
|
248
|
+
if (node.children.size === 0) {
|
|
249
|
+
return values.map((value, i) => {
|
|
250
|
+
const id = leafColumnId(node.path, i)
|
|
251
|
+
const label = value.label ?? `${value.field} (${typeof value.agg === 'function' ? 'custom' : value.agg})`
|
|
252
|
+
return {
|
|
253
|
+
id,
|
|
254
|
+
header: label,
|
|
255
|
+
accessorFn: (row) => row[id],
|
|
256
|
+
format: value.format,
|
|
257
|
+
width: 130,
|
|
258
|
+
} as ColumnDef<TFeatures, PivotRow>
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
// Otherwise emit a header group with this node's value as the label
|
|
262
|
+
// and recurse for its children.
|
|
263
|
+
return Array.from(node.children.values()).map((child) => ({
|
|
264
|
+
id: `pv_group_${child.pathKey}`,
|
|
265
|
+
header: String(child.value ?? '(blank)'),
|
|
266
|
+
columns: recurse(child),
|
|
267
|
+
} as unknown as ColumnDef<TFeatures, PivotRow>))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const valueCols = colRoot.children.size === 0
|
|
271
|
+
// No col dims at all: emit measures as flat columns under no group.
|
|
272
|
+
? recurse(colRoot)
|
|
273
|
+
: recurse(colRoot)
|
|
274
|
+
|
|
275
|
+
const grandTotalCol = config.grandTotalCol !== false
|
|
276
|
+
if (!grandTotalCol) return [headerCol, ...valueCols]
|
|
277
|
+
|
|
278
|
+
// Grand total column: one measure column per value config, with no
|
|
279
|
+
// col-path filter.
|
|
280
|
+
const totalCols: Array<ColumnDef<TFeatures, PivotRow>> = values.map((value, i) => {
|
|
281
|
+
const id = leafColumnId(['__total'], i)
|
|
282
|
+
const label = value.label ?? `${value.field} (${typeof value.agg === 'function' ? 'custom' : value.agg})`
|
|
283
|
+
return {
|
|
284
|
+
id,
|
|
285
|
+
header: label,
|
|
286
|
+
accessorFn: (row) => row[id],
|
|
287
|
+
format: value.format,
|
|
288
|
+
width: 140,
|
|
289
|
+
} as ColumnDef<TFeatures, PivotRow>
|
|
290
|
+
})
|
|
291
|
+
const grandTotal: ColumnDef<TFeatures, PivotRow> = {
|
|
292
|
+
id: 'pv_group__grand_total',
|
|
293
|
+
header: 'Total',
|
|
294
|
+
columns: totalCols,
|
|
295
|
+
} as unknown as ColumnDef<TFeatures, PivotRow>
|
|
296
|
+
|
|
297
|
+
return [headerCol, ...valueCols, grandTotal]
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// --------------------------------------------------- row-axis materialise
|
|
301
|
+
|
|
302
|
+
function collectColLeafPaths(node: AxisNode, into: Array<ReadonlyArray<unknown>>): void {
|
|
303
|
+
if (node.children.size === 0) {
|
|
304
|
+
into.push(node.path)
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
for (const child of node.children.values()) collectColLeafPaths(child, into)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* For one source-row set (a row-axis node) compute the value at each
|
|
312
|
+
* column-axis leaf for each measure. Returns a map keyed by column id.
|
|
313
|
+
*/
|
|
314
|
+
function computeRowValues(
|
|
315
|
+
sourceRows: ReadonlyArray<Record<string, unknown>>,
|
|
316
|
+
colLeafPaths: ReadonlyArray<ReadonlyArray<unknown>>,
|
|
317
|
+
colFields: ReadonlyArray<string>,
|
|
318
|
+
values: ReadonlyArray<PivotValueConfig<unknown>>,
|
|
319
|
+
includeGrandTotalCol: boolean,
|
|
320
|
+
): Record<string, unknown> {
|
|
321
|
+
const result: Record<string, unknown> = {}
|
|
322
|
+
|
|
323
|
+
// For each col-axis leaf path, filter the source rows to those matching
|
|
324
|
+
// every dim value, then run each measure aggregator.
|
|
325
|
+
for (const colPath of colLeafPaths) {
|
|
326
|
+
const matched = colPath.length === 0
|
|
327
|
+
? sourceRows
|
|
328
|
+
: sourceRows.filter((r) =>
|
|
329
|
+
colPath.every((value, i) => r[colFields[i]!] === value),
|
|
330
|
+
)
|
|
331
|
+
for (let i = 0; i < values.length; i += 1) {
|
|
332
|
+
const value = values[i]!
|
|
333
|
+
const fn = resolveAgg(value.agg)
|
|
334
|
+
const id = leafColumnId(colPath, i)
|
|
335
|
+
result[id] = fn(matched.map((r) => r[value.field]))
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Grand-total column: run each measure across the entire source set.
|
|
340
|
+
if (includeGrandTotalCol) {
|
|
341
|
+
for (let i = 0; i < values.length; i += 1) {
|
|
342
|
+
const value = values[i]!
|
|
343
|
+
const fn = resolveAgg(value.agg)
|
|
344
|
+
const id = leafColumnId(['__total'], i)
|
|
345
|
+
result[id] = fn(sourceRows.map((r) => r[value.field]))
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return result
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function walkRowTree(
|
|
353
|
+
node: AxisNode,
|
|
354
|
+
out: PivotRow[],
|
|
355
|
+
colLeafPaths: ReadonlyArray<ReadonlyArray<unknown>>,
|
|
356
|
+
colFields: ReadonlyArray<string>,
|
|
357
|
+
values: ReadonlyArray<PivotValueConfig<unknown>>,
|
|
358
|
+
config: PivotConfig<unknown>,
|
|
359
|
+
rowFields: ReadonlyArray<string>,
|
|
360
|
+
/**
|
|
361
|
+
* The id of the row-axis ancestor that should be reported as
|
|
362
|
+
* `__pivotParentId` on every row emitted under this subtree. `null`
|
|
363
|
+
* at the top level.
|
|
364
|
+
*/
|
|
365
|
+
parentId: string | null,
|
|
366
|
+
): void {
|
|
367
|
+
const includeGrandTotalCol = config.grandTotalCol !== false
|
|
368
|
+
const wantSubtotals = config.rowSubtotals !== false
|
|
369
|
+
|
|
370
|
+
// The "leaf" case: this is a row-axis leaf - no further row dimensions.
|
|
371
|
+
if (node.children.size === 0) {
|
|
372
|
+
out.push({
|
|
373
|
+
__pivotId: `row__${node.pathKey}`,
|
|
374
|
+
__pivotKind: 'leaf',
|
|
375
|
+
__pivotDepth: node.level,
|
|
376
|
+
__pivotLabel: node.value === null ? '(All)' : String(node.value),
|
|
377
|
+
__pivotParentId: parentId,
|
|
378
|
+
__pivotExpandable: false,
|
|
379
|
+
...computeRowValues(
|
|
380
|
+
node.rows as ReadonlyArray<Record<string, unknown>>,
|
|
381
|
+
colLeafPaths,
|
|
382
|
+
colFields,
|
|
383
|
+
values,
|
|
384
|
+
includeGrandTotalCol,
|
|
385
|
+
),
|
|
386
|
+
})
|
|
387
|
+
return
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Group node. Emit a subtotal-style row IF requested AND this node has
|
|
391
|
+
// a real path (not the synthetic root) AND it's not at the deepest level.
|
|
392
|
+
const isRealGroup = node.level > 0 && node.level < rowFields.length
|
|
393
|
+
let nextParentId: string | null = parentId
|
|
394
|
+
if (isRealGroup && wantSubtotals) {
|
|
395
|
+
const id = `group__${node.pathKey}`
|
|
396
|
+
out.push({
|
|
397
|
+
__pivotId: id,
|
|
398
|
+
__pivotKind: 'group',
|
|
399
|
+
__pivotDepth: node.level,
|
|
400
|
+
__pivotLabel: String(node.value ?? '(All)'),
|
|
401
|
+
__pivotParentId: parentId,
|
|
402
|
+
__pivotExpandable: true,
|
|
403
|
+
...computeRowValues(
|
|
404
|
+
node.rows as ReadonlyArray<Record<string, unknown>>,
|
|
405
|
+
colLeafPaths,
|
|
406
|
+
colFields,
|
|
407
|
+
values,
|
|
408
|
+
includeGrandTotalCol,
|
|
409
|
+
),
|
|
410
|
+
})
|
|
411
|
+
// Children of this group point at this row as their parent so a
|
|
412
|
+
// collapse hides the whole subtree, not just the immediate leaves.
|
|
413
|
+
nextParentId = id
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
for (const child of node.children.values()) {
|
|
417
|
+
walkRowTree(
|
|
418
|
+
child, out, colLeafPaths, colFields, values, config, rowFields, nextParentId,
|
|
419
|
+
)
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// ------------------------------------------------------------ public API
|
|
424
|
+
|
|
425
|
+
export function createPivotModel<
|
|
426
|
+
TFeatures extends TableFeatures,
|
|
427
|
+
TData extends RowData,
|
|
428
|
+
>(
|
|
429
|
+
data: ReadonlyArray<TData>,
|
|
430
|
+
config: PivotConfig<TData>,
|
|
431
|
+
): PivotResult<TFeatures> {
|
|
432
|
+
if (config.values.length === 0) {
|
|
433
|
+
throw new Error('pivot: at least one value config is required')
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const rowFields = config.rows as ReadonlyArray<string>
|
|
437
|
+
const colFields = config.cols as ReadonlyArray<string>
|
|
438
|
+
const values = config.values as ReadonlyArray<PivotValueConfig<unknown>>
|
|
439
|
+
|
|
440
|
+
// 1. axis trees
|
|
441
|
+
const rowRoot = buildAxisTree(data, rowFields, config.rowSort)
|
|
442
|
+
const colRoot = buildAxisTree(data, colFields, config.colSort)
|
|
443
|
+
|
|
444
|
+
// 2. collect col-axis leaf paths (one per value column header chain)
|
|
445
|
+
const colLeafPaths: Array<ReadonlyArray<unknown>> = []
|
|
446
|
+
collectColLeafPaths(colRoot, colLeafPaths)
|
|
447
|
+
|
|
448
|
+
// 3. flatten row-axis to pivot rows
|
|
449
|
+
const rows: PivotRow[] = []
|
|
450
|
+
if (rowFields.length === 0) {
|
|
451
|
+
// No row dims: one synthetic "All" row.
|
|
452
|
+
rows.push({
|
|
453
|
+
__pivotId: 'row__all',
|
|
454
|
+
__pivotKind: 'leaf',
|
|
455
|
+
__pivotDepth: 0,
|
|
456
|
+
__pivotLabel: '(All)',
|
|
457
|
+
__pivotParentId: null,
|
|
458
|
+
__pivotExpandable: false,
|
|
459
|
+
...computeRowValues(
|
|
460
|
+
data as unknown as ReadonlyArray<Record<string, unknown>>,
|
|
461
|
+
colLeafPaths,
|
|
462
|
+
colFields,
|
|
463
|
+
values,
|
|
464
|
+
config.grandTotalCol !== false,
|
|
465
|
+
),
|
|
466
|
+
})
|
|
467
|
+
} else {
|
|
468
|
+
walkRowTree(
|
|
469
|
+
rowRoot, rows, colLeafPaths, colFields, values,
|
|
470
|
+
config as PivotConfig<unknown>, rowFields, null,
|
|
471
|
+
)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// 4. grand-total row at bottom
|
|
475
|
+
if (config.grandTotalRow !== false) {
|
|
476
|
+
rows.push({
|
|
477
|
+
__pivotId: 'row__grand_total',
|
|
478
|
+
__pivotKind: 'grandTotal',
|
|
479
|
+
__pivotDepth: 0,
|
|
480
|
+
__pivotLabel: 'Grand total',
|
|
481
|
+
__pivotParentId: null,
|
|
482
|
+
__pivotExpandable: false,
|
|
483
|
+
...computeRowValues(
|
|
484
|
+
data as unknown as ReadonlyArray<Record<string, unknown>>,
|
|
485
|
+
colLeafPaths,
|
|
486
|
+
colFields,
|
|
487
|
+
values,
|
|
488
|
+
config.grandTotalCol !== false,
|
|
489
|
+
),
|
|
490
|
+
})
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// 5. column tree
|
|
494
|
+
const columns = buildColumnTree<TFeatures>(
|
|
495
|
+
colRoot,
|
|
496
|
+
values,
|
|
497
|
+
config as PivotConfig<unknown>,
|
|
498
|
+
rowFields.length > 0 ? rowFields.join(' / ') : '',
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
return { rows, columns }
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Public registry of built-in aggregators. Useful for surfacing the
|
|
506
|
+
* available options in a pivot designer UI.
|
|
507
|
+
*/
|
|
508
|
+
export const pivotAggregators: Record<PivotAggregatorId, PivotAggregator> = { ...BUILT_IN_AGGS }
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Filter a `result.rows` array down to only the rows the user should
|
|
512
|
+
* see given the current expansion state. A row stays in the output if
|
|
513
|
+
* its entire ancestor chain (via `__pivotParentId`) is in `expandedIds`.
|
|
514
|
+
*
|
|
515
|
+
* Pass `true` to bypass filtering (everything visible - the default
|
|
516
|
+
* shape `createPivotModel` already returns). Pass an empty array /
|
|
517
|
+
* empty Set to collapse every group to its subtotal row.
|
|
518
|
+
*
|
|
519
|
+
* The result is a new array; the input is not mutated.
|
|
520
|
+
*/
|
|
521
|
+
export function filterCollapsedPivotRows(
|
|
522
|
+
rows: ReadonlyArray<PivotRow>,
|
|
523
|
+
expandedIds: ReadonlyArray<string> | Set<string> | true,
|
|
524
|
+
): PivotRow[] {
|
|
525
|
+
if (expandedIds === true) return rows.slice()
|
|
526
|
+
const expanded =
|
|
527
|
+
expandedIds instanceof Set ? expandedIds : new Set(expandedIds)
|
|
528
|
+
// Parent-of index so the ancestor walk is O(depth) instead of O(rows × depth).
|
|
529
|
+
const parentOf = new Map<string, string | null>()
|
|
530
|
+
for (const r of rows) parentOf.set(r.__pivotId, r.__pivotParentId)
|
|
531
|
+
|
|
532
|
+
const out: PivotRow[] = []
|
|
533
|
+
for (const row of rows) {
|
|
534
|
+
// The grand-total row, top-level groups, and the (All) row are
|
|
535
|
+
// always visible (their parent is null).
|
|
536
|
+
if (row.__pivotParentId === null) {
|
|
537
|
+
out.push(row)
|
|
538
|
+
continue
|
|
539
|
+
}
|
|
540
|
+
let parentId: string | null = row.__pivotParentId
|
|
541
|
+
let visible = true
|
|
542
|
+
while (parentId !== null) {
|
|
543
|
+
if (!expanded.has(parentId)) { visible = false; break }
|
|
544
|
+
parentId = parentOf.get(parentId) ?? null
|
|
545
|
+
}
|
|
546
|
+
if (visible) out.push(row)
|
|
547
|
+
}
|
|
548
|
+
return out
|
|
549
|
+
}
|
package/src/print.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { RowData, TableFeatures, SvGridApi } from '@svgrid/grid'
|
|
2
|
+
import { assertProLicensed } from './license'
|
|
3
|
+
import { installSmartShim } from './smart-shim'
|
|
4
|
+
import type { ExportColumn } from './export'
|
|
5
|
+
|
|
6
|
+
export type PrintOptions<TData> = {
|
|
7
|
+
/** Title placed above the printed grid. Defaults to "Grid". */
|
|
8
|
+
title?: string
|
|
9
|
+
/** Columns to print. If omitted, every key of the first row is printed. */
|
|
10
|
+
columns?: ReadonlyArray<ExportColumn>
|
|
11
|
+
/** Rows to print. If omitted, the api's displayed rows are used. */
|
|
12
|
+
rows?: ReadonlyArray<TData>
|
|
13
|
+
/**
|
|
14
|
+
* Print orientation hint. Browsers honor it via `@page { size: ... }`.
|
|
15
|
+
* Defaults to "portrait".
|
|
16
|
+
*/
|
|
17
|
+
orientation?: 'portrait' | 'landscape'
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type DataExporterCtor = new (
|
|
21
|
+
options: Record<string, unknown>,
|
|
22
|
+
) => {
|
|
23
|
+
exportData(
|
|
24
|
+
data: ReadonlyArray<Record<string, unknown>>,
|
|
25
|
+
format: string,
|
|
26
|
+
filename?: string,
|
|
27
|
+
): unknown
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let exporterCtorPromise: Promise<DataExporterCtor> | null = null
|
|
31
|
+
|
|
32
|
+
async function getDataExporter(): Promise<DataExporterCtor> {
|
|
33
|
+
if (typeof window === 'undefined') {
|
|
34
|
+
throw new Error('@svgrid/enterprise: print requires a browser environment')
|
|
35
|
+
}
|
|
36
|
+
if (!exporterCtorPromise) {
|
|
37
|
+
exporterCtorPromise = (async () => {
|
|
38
|
+
installSmartShim()
|
|
39
|
+
await import('./smart.export.js')
|
|
40
|
+
const Ctor = window.Smart?.Utilities?.DataExporter as DataExporterCtor | undefined
|
|
41
|
+
if (!Ctor) {
|
|
42
|
+
throw new Error('@svgrid/enterprise: failed to load Smart.Utilities.DataExporter')
|
|
43
|
+
}
|
|
44
|
+
return Ctor
|
|
45
|
+
})()
|
|
46
|
+
}
|
|
47
|
+
return exporterCtorPromise
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function printGrid<
|
|
51
|
+
TFeatures extends TableFeatures,
|
|
52
|
+
TData extends RowData,
|
|
53
|
+
>(api: SvGridApi<TFeatures, TData>, opts?: PrintOptions<TData>): Promise<void> {
|
|
54
|
+
assertProLicensed('Print')
|
|
55
|
+
const sourceRows: ReadonlyArray<TData> = opts?.rows ?? api.getDisplayedRows()
|
|
56
|
+
let cols: ReadonlyArray<ExportColumn>
|
|
57
|
+
if (opts?.columns && opts.columns.length > 0) {
|
|
58
|
+
cols = opts.columns
|
|
59
|
+
} else if (sourceRows.length > 0) {
|
|
60
|
+
cols = Object.keys(sourceRows[0] as Record<string, unknown>)
|
|
61
|
+
.filter((k) => !k.startsWith('_'))
|
|
62
|
+
.map((field) => ({ field }))
|
|
63
|
+
} else {
|
|
64
|
+
cols = []
|
|
65
|
+
}
|
|
66
|
+
if (sourceRows.length === 0) {
|
|
67
|
+
throw new Error('@svgrid/enterprise: nothing to print - the grid has no rows')
|
|
68
|
+
}
|
|
69
|
+
const header: Record<string, unknown> = {}
|
|
70
|
+
for (const c of cols) header[c.field] = c.header ?? c.field
|
|
71
|
+
const projected: Array<Record<string, unknown>> = [header]
|
|
72
|
+
for (const r of sourceRows) {
|
|
73
|
+
const out: Record<string, unknown> = {}
|
|
74
|
+
const src = r as unknown as Record<string, unknown>
|
|
75
|
+
for (const c of cols) out[c.field] = src[c.field]
|
|
76
|
+
projected.push(out)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const Ctor = await getDataExporter()
|
|
80
|
+
const exporter = new Ctor({ exportHeader: true })
|
|
81
|
+
// No filename means exportData returns the HTML string instead of triggering
|
|
82
|
+
// a download (see downloadFile in smart.export.js: when filename is falsy it
|
|
83
|
+
// returns the raw content unchanged).
|
|
84
|
+
const html = exporter.exportData(projected, 'html') as string
|
|
85
|
+
|
|
86
|
+
const title = (opts?.title ?? 'Grid').replace(/[<>]/g, '')
|
|
87
|
+
const orientation = opts?.orientation ?? 'portrait'
|
|
88
|
+
const wrapped = `<!DOCTYPE html>
|
|
89
|
+
<html><head><meta charset="utf-8"><title>${title}</title>
|
|
90
|
+
<style>
|
|
91
|
+
@page { size: ${orientation}; margin: 14mm; }
|
|
92
|
+
@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
|
|
93
|
+
body { font-family: -apple-system, "Segoe UI", Roboto, sans-serif; color: #111; }
|
|
94
|
+
h1 { font-size: 16pt; margin: 0 0 8mm 0; }
|
|
95
|
+
table { border-collapse: collapse; width: 100%; font-size: 9pt; }
|
|
96
|
+
th, td { border: 1px solid #444; padding: 4px 6px; text-align: left; }
|
|
97
|
+
thead { background: #eee; }
|
|
98
|
+
</style></head>
|
|
99
|
+
<body>
|
|
100
|
+
<h1>${title}</h1>
|
|
101
|
+
${html.replace(/^[\s\S]*?<body>/i, '').replace(/<\/body>[\s\S]*$/i, '')}
|
|
102
|
+
</body></html>`
|
|
103
|
+
|
|
104
|
+
const w = window.open('', '_blank', 'width=900,height=700')
|
|
105
|
+
if (!w) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
'@svgrid/enterprise: print() could not open a window - the browser blocked the popup',
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
w.document.open()
|
|
111
|
+
w.document.write(wrapped)
|
|
112
|
+
w.document.close()
|
|
113
|
+
// Give the new window one tick to paint before invoking print.
|
|
114
|
+
w.focus()
|
|
115
|
+
w.addEventListener('load', () => {
|
|
116
|
+
setTimeout(() => w.print(), 50)
|
|
117
|
+
})
|
|
118
|
+
// Some browsers fire 'load' before the listener attaches if document was
|
|
119
|
+
// already complete. Fall back: try a print after a short delay regardless.
|
|
120
|
+
setTimeout(() => {
|
|
121
|
+
try {
|
|
122
|
+
w.print()
|
|
123
|
+
} catch {
|
|
124
|
+
// ignore - listener path will have fired
|
|
125
|
+
}
|
|
126
|
+
}, 300)
|
|
127
|
+
}
|