@gridkitjs/core 0.0.0-dev-20261112193051 → 0.0.0-dev-20261112194323

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.
@@ -0,0 +1,3408 @@
1
+ // src/util/grid.ts
2
+ function isNested(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
4
+ }
5
+ function getType(value) {
6
+ if (value instanceof Date) return "dateTime";
7
+ if (typeof value === "string") return "string";
8
+ if (typeof value === "number") return "number";
9
+ if (typeof value === "boolean") return "boolean";
10
+ if (typeof value === "bigint") return "number";
11
+ if (typeof value === "symbol") return "string";
12
+ return "string";
13
+ }
14
+ function alignmentForType(type) {
15
+ switch (type) {
16
+ case "number":
17
+ case "decimal":
18
+ case "currency":
19
+ case "percent":
20
+ return "right";
21
+ default:
22
+ return "left";
23
+ }
24
+ }
25
+ function getAlignment(value) {
26
+ return alignmentForType(getType(value));
27
+ }
28
+ function defineColumnsFromRows(rows) {
29
+ const columns = [];
30
+ const seen = /* @__PURE__ */ new Set();
31
+ function add(field, value) {
32
+ if (seen.has(field)) {
33
+ return;
34
+ }
35
+ seen.add(field);
36
+ columns.push({
37
+ field,
38
+ type: getType(value),
39
+ alignment: getAlignment(value)
40
+ });
41
+ }
42
+ for (const row of rows) {
43
+ if (!isNested(row)) {
44
+ continue;
45
+ }
46
+ for (const [key, value] of Object.entries(row)) {
47
+ if (!isNested(value)) {
48
+ add(key, value);
49
+ continue;
50
+ }
51
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
52
+ if (!isNested(nestedValue)) {
53
+ add(`${key}.${nestedKey}`, nestedValue);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ return columns;
59
+ }
60
+ function getColumnId(column) {
61
+ return column.id ?? column.field;
62
+ }
63
+ function resolveRowId(row, index, getRowId) {
64
+ return getRowId?.(row, index) ?? String(index);
65
+ }
66
+ function labelFromField(field) {
67
+ return field.split(".").join(" ");
68
+ }
69
+ function resolveColumnLabel(column) {
70
+ const { headerTemplate } = column;
71
+ if (headerTemplate === void 0) {
72
+ return column.header ?? labelFromField(column.field);
73
+ }
74
+ return typeof headerTemplate === "function" ? headerTemplate() : headerTemplate;
75
+ }
76
+ function resolveColumnHeaderText(column) {
77
+ if (column.header !== void 0) {
78
+ return column.header;
79
+ }
80
+ const label = resolveColumnLabel(column);
81
+ return typeof label === "string" ? label : labelFromField(column.field);
82
+ }
83
+ function buildKeyShortcuts(capabilities) {
84
+ return [
85
+ capabilities.reorderable ? "Control+ArrowLeft Control+ArrowRight" : "",
86
+ // Alt+Enter is the keyboard equivalent of double-clicking the resize
87
+ // handle to size the column to its content — same gate as the nudge
88
+ // shortcuts, since both are resize actions.
89
+ capabilities.resizable ? "Alt+ArrowLeft Alt+ArrowRight Alt+Enter" : "",
90
+ capabilities.sortable ? "Alt+ArrowUp" : "",
91
+ // Down rather than reusing Up: it reads as "drill into groups", and Up is
92
+ // already sort's own mnemonic on the same header.
93
+ capabilities.groupable ? "Alt+ArrowDown" : "",
94
+ // Excel's own key for its filter dropdown is Alt+ArrowDown, which
95
+ // grouping already holds here; Shift sets the filter apart from it.
96
+ capabilities.filterable === true ? "Alt+Shift+ArrowDown" : "",
97
+ // The ContextMenu key needs no mention: it says what it does on its face.
98
+ capabilities.contextMenu === true ? "Shift+F10" : ""
99
+ ].filter(Boolean).join(" ");
100
+ }
101
+ function accessDotted(obj, path) {
102
+ return path.split(".").reduce((value, key) => isNested(value) ? value[key] : void 0, obj);
103
+ }
104
+
105
+ // src/util/position.ts
106
+ function renumberRows(entries) {
107
+ return entries.map(
108
+ (entry, index) => entry.rowIndex === index && entry.datasetIndex === index ? entry : { ...entry, rowIndex: index, datasetIndex: index }
109
+ );
110
+ }
111
+
112
+ // src/util/sorting.ts
113
+ function isEmpty(value) {
114
+ return value === null || value === void 0;
115
+ }
116
+ function toTime(value) {
117
+ return value instanceof Date ? value.getTime() : new Date(String(value)).getTime();
118
+ }
119
+ function isFiniteNumber(value) {
120
+ return typeof value === "number" && Number.isFinite(value);
121
+ }
122
+ function isValidDate(value) {
123
+ return value instanceof Date && !Number.isNaN(value.getTime());
124
+ }
125
+ function compareUntyped(a, b) {
126
+ if (isFiniteNumber(a) && isFiniteNumber(b)) {
127
+ return a - b;
128
+ }
129
+ if (isValidDate(a) && isValidDate(b)) {
130
+ return a.getTime() - b.getTime();
131
+ }
132
+ return String(a).localeCompare(String(b));
133
+ }
134
+ function compareValues(a, b, type) {
135
+ if (isEmpty(a)) {
136
+ return isEmpty(b) ? 0 : 1;
137
+ }
138
+ if (isEmpty(b)) {
139
+ return -1;
140
+ }
141
+ switch (type) {
142
+ case "number":
143
+ case "decimal":
144
+ case "currency":
145
+ case "percent":
146
+ return Number(a) - Number(b);
147
+ case "boolean":
148
+ return Number(Boolean(a)) - Number(Boolean(b));
149
+ case "date":
150
+ case "dateTime":
151
+ case "time":
152
+ return toTime(a) - toTime(b);
153
+ case void 0:
154
+ return compareUntyped(a, b);
155
+ default:
156
+ return String(a).localeCompare(String(b));
157
+ }
158
+ }
159
+ function sortDirectionFor(sort, columnId) {
160
+ return sort.find((entry) => entry.columnId === columnId)?.direction ?? null;
161
+ }
162
+ function sortPriorityFor(sort, columnId) {
163
+ const index = sort.findIndex((entry) => entry.columnId === columnId);
164
+ return index === -1 ? null : index + 1;
165
+ }
166
+ function toggleColumnSort(sort, columnId, options) {
167
+ const index = sort.findIndex((entry) => entry.columnId === columnId);
168
+ const isSoleEntry = sort.length === 1 && index === 0;
169
+ if (!options.stack && !isSoleEntry) {
170
+ return [{ columnId, direction: "asc" }];
171
+ }
172
+ const current = index === -1 ? void 0 : sort[index]?.direction;
173
+ const next = current === void 0 ? "asc" : current === "asc" ? "desc" : null;
174
+ if (next === null) {
175
+ return sort.filter((entry) => entry.columnId !== columnId);
176
+ }
177
+ if (index === -1) {
178
+ return [...sort, { columnId, direction: next }];
179
+ }
180
+ return sort.map(
181
+ (entry, i) => i === index ? { columnId, direction: next } : entry
182
+ );
183
+ }
184
+ function sortRows(rows, sort, columns) {
185
+ if (sort.length === 0) {
186
+ return rows;
187
+ }
188
+ const byId = new Map(columns.map((entry) => [entry.id, entry.column]));
189
+ const active = sort.filter((entry) => byId.has(entry.columnId));
190
+ if (active.length === 0) {
191
+ return rows;
192
+ }
193
+ const sorted = [...rows].sort((a, b) => {
194
+ for (const { columnId, direction } of active) {
195
+ const column = byId.get(columnId);
196
+ if (column === void 0) {
197
+ continue;
198
+ }
199
+ const left = accessDotted(a.row, column.field);
200
+ const right = accessDotted(b.row, column.field);
201
+ const leftEmpty = isEmpty(left);
202
+ const rightEmpty = isEmpty(right);
203
+ if (leftEmpty || rightEmpty) {
204
+ if (leftEmpty && rightEmpty) {
205
+ continue;
206
+ }
207
+ return leftEmpty ? 1 : -1;
208
+ }
209
+ const result = compareValues(left, right, column.type);
210
+ if (result !== 0) {
211
+ return direction === "asc" ? result : -result;
212
+ }
213
+ }
214
+ return 0;
215
+ });
216
+ return renumberRows(sorted);
217
+ }
218
+
219
+ // src/util/grouping.ts
220
+ function groupRowId(path) {
221
+ return JSON.stringify(path);
222
+ }
223
+ function bucketKey(value) {
224
+ if (value === null || value === void 0) {
225
+ return "\0empty";
226
+ }
227
+ if (value instanceof Date) {
228
+ return `\0date:${String(value.getTime())}`;
229
+ }
230
+ switch (typeof value) {
231
+ case "string":
232
+ case "number":
233
+ case "boolean":
234
+ case "bigint":
235
+ case "symbol":
236
+ return `\0${typeof value}:${String(value)}`;
237
+ case "function":
238
+ return "\0function";
239
+ default:
240
+ return `\0object:${JSON.stringify(value)}`;
241
+ }
242
+ }
243
+ function partitionByValue(rows, column, direction) {
244
+ const buckets = /* @__PURE__ */ new Map();
245
+ for (const row of rows) {
246
+ const value = accessDotted(row.row, column.field);
247
+ const key = bucketKey(value);
248
+ const bucket = buckets.get(key);
249
+ if (bucket === void 0) {
250
+ buckets.set(key, { value, rows: [row] });
251
+ } else {
252
+ bucket.rows.push(row);
253
+ }
254
+ }
255
+ const groups = [...buckets.values()];
256
+ groups.sort((a, b) => {
257
+ const result = compareValues(a.value, b.value, column.type);
258
+ return direction === "asc" ? result : -result;
259
+ });
260
+ return groups;
261
+ }
262
+ function buildLevel(rows, levels, parentPath, expansion, byId, out) {
263
+ const level = levels[0];
264
+ if (level === void 0) {
265
+ out.push(...rows);
266
+ return;
267
+ }
268
+ const column = byId.get(level.columnId);
269
+ if (column === void 0) {
270
+ out.push(...rows);
271
+ return;
272
+ }
273
+ const rest = levels.slice(1);
274
+ const groups = partitionByValue(rows, column, level.direction ?? "asc");
275
+ for (const group of groups) {
276
+ const path = [...parentPath, group.value];
277
+ const groupId = groupRowId(path);
278
+ const expanded = isGroupExpanded(expansion, groupId);
279
+ const header = {
280
+ kind: "group",
281
+ groupId,
282
+ level: parentPath.length,
283
+ columnId: level.columnId,
284
+ value: group.value,
285
+ path,
286
+ expanded,
287
+ count: group.rows.length,
288
+ // Both set by `groupRows` once it has the whole flattened array.
289
+ rowIndex: -1,
290
+ datasetIndex: -1,
291
+ // Set by `withGroupAggregates`, downstream of grouping — empty here
292
+ // since `groupRows` itself never knows about `AggregateState`.
293
+ aggregates: /* @__PURE__ */ new Map()
294
+ };
295
+ out.push(header);
296
+ if (expanded) {
297
+ buildLevel(group.rows, rest, path, expansion, byId, out);
298
+ }
299
+ }
300
+ }
301
+ function groupRows(rows, groupBy, expansion, columns) {
302
+ if (groupBy.length === 0) {
303
+ return rows;
304
+ }
305
+ const byId = new Map(columns.map((entry) => [entry.id, entry.column]));
306
+ const active = groupBy.filter((entry) => byId.has(entry.columnId));
307
+ if (active.length === 0) {
308
+ return rows;
309
+ }
310
+ const out = [];
311
+ buildLevel(rows, active, [], expansion, byId, out);
312
+ return renumberRows(out);
313
+ }
314
+ var ALL_EXPANDED = {
315
+ mode: "allExpanded",
316
+ except: []
317
+ };
318
+ var ALL_COLLAPSED = {
319
+ mode: "allCollapsed",
320
+ except: []
321
+ };
322
+ function isGroupExpanded(expansion, groupId) {
323
+ const excepted = expansion.except.includes(groupId);
324
+ return expansion.mode === "allExpanded" ? !excepted : excepted;
325
+ }
326
+ function toggleGroupExpansion(expansion, groupId) {
327
+ const except = expansion.except.includes(groupId) ? expansion.except.filter((id) => id !== groupId) : [...expansion.except, groupId];
328
+ return { mode: expansion.mode, except };
329
+ }
330
+ function expandAllGroups(expansion) {
331
+ return isWithoutExceptions(expansion, "allExpanded") ? expansion : ALL_EXPANDED;
332
+ }
333
+ function collapseAllGroups(expansion) {
334
+ return isWithoutExceptions(expansion, "allCollapsed") ? expansion : ALL_COLLAPSED;
335
+ }
336
+ function isWithoutExceptions(expansion, mode) {
337
+ return expansion.mode === mode && expansion.except.length === 0;
338
+ }
339
+ function moveGroupByBefore(groupBy, columnId, beforeColumnId) {
340
+ if (columnId === beforeColumnId) {
341
+ return groupBy;
342
+ }
343
+ const without = groupBy.filter((entry) => entry.columnId !== columnId);
344
+ const moved = groupBy.find((entry) => entry.columnId === columnId) ?? {
345
+ columnId
346
+ };
347
+ const target = beforeColumnId === null ? without.length : without.findIndex((entry) => entry.columnId === beforeColumnId);
348
+ if (target === -1) {
349
+ return groupBy;
350
+ }
351
+ const next = [...without];
352
+ next.splice(target, 0, moved);
353
+ return next.length === groupBy.length && next.every((entry, index) => entry === groupBy[index]) ? groupBy : next;
354
+ }
355
+ function movesGroupBy(groupBy, columnId, beforeColumnId) {
356
+ return moveGroupByBefore(groupBy, columnId, beforeColumnId) !== groupBy;
357
+ }
358
+
359
+ // src/util/ordering.ts
360
+ function applyColumnOrder(columns, order) {
361
+ if (order.length === 0) {
362
+ return columns;
363
+ }
364
+ const byId = new Map(columns.map((column) => [getColumnId(column), column]));
365
+ const listed = order.map((id) => byId.get(id)).filter((column) => column !== void 0);
366
+ const taken = new Set(listed.map((column) => getColumnId(column)));
367
+ return [
368
+ ...listed,
369
+ ...columns.filter((column) => !taken.has(getColumnId(column)))
370
+ ];
371
+ }
372
+ function resolveDataColumns(columns, order) {
373
+ return applyColumnOrder(columns, order).map((column) => ({
374
+ id: getColumnId(column),
375
+ column
376
+ }));
377
+ }
378
+ function moveColumnBefore(orderedIds, movedId, beforeId) {
379
+ if (movedId === beforeId || !orderedIds.includes(movedId)) {
380
+ return orderedIds;
381
+ }
382
+ const without = orderedIds.filter((id) => id !== movedId);
383
+ const target = beforeId === null ? without.length : without.indexOf(beforeId);
384
+ if (target === -1) {
385
+ return orderedIds;
386
+ }
387
+ const next = [...without];
388
+ next.splice(target, 0, movedId);
389
+ return next.every((id, index) => id === orderedIds[index]) ? orderedIds : next;
390
+ }
391
+ function movesColumn(orderedIds, movedId, beforeId) {
392
+ return moveColumnBefore(orderedIds, movedId, beforeId) !== orderedIds;
393
+ }
394
+ function resolveDropBefore(orderedIds, targetId, side) {
395
+ if (side === "before") {
396
+ return targetId;
397
+ }
398
+ const index = orderedIds.indexOf(targetId);
399
+ return index === -1 ? null : orderedIds[index + 1] ?? null;
400
+ }
401
+ function resolveKeyboardDropTarget(orderedIds, columnId, direction) {
402
+ const index = orderedIds.indexOf(columnId);
403
+ if (index === -1) {
404
+ return void 0;
405
+ }
406
+ const targetIndex = direction === -1 ? index - 1 : index + 2;
407
+ if (targetIndex < 0) {
408
+ return void 0;
409
+ }
410
+ return orderedIds[targetIndex] ?? null;
411
+ }
412
+
413
+ // src/util/filterOperators.ts
414
+ var matchNothing = () => false;
415
+ function kindOf(type) {
416
+ switch (type) {
417
+ case "number":
418
+ case "decimal":
419
+ case "currency":
420
+ case "percent":
421
+ return "number";
422
+ case "boolean":
423
+ return "boolean";
424
+ case "date":
425
+ case "dateTime":
426
+ case "time":
427
+ return "date";
428
+ default:
429
+ return "text";
430
+ }
431
+ }
432
+ function isDateType(type) {
433
+ return kindOf(type) === "date";
434
+ }
435
+ function isEmptyCell(value) {
436
+ return value === null || value === void 0 || value === "";
437
+ }
438
+ function toDate(value) {
439
+ const date = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
440
+ return date === void 0 || Number.isNaN(date.getTime()) ? void 0 : date;
441
+ }
442
+ function comparable(value, kind) {
443
+ switch (kind) {
444
+ case "number":
445
+ return typeof value === "number" && !Number.isNaN(value) ? value : void 0;
446
+ case "boolean":
447
+ return typeof value === "boolean" ? value : void 0;
448
+ case "date":
449
+ return toDate(value);
450
+ case "text":
451
+ return String(value).toLowerCase();
452
+ }
453
+ }
454
+ function isOperandOfKind(operand, kind) {
455
+ if (kind !== "text") {
456
+ return comparable(operand, kind) !== void 0;
457
+ }
458
+ return typeof operand === "string" || typeof operand === "number" || typeof operand === "boolean";
459
+ }
460
+ function compileComparison(operand, type) {
461
+ const kind = kindOf(type);
462
+ if (!isOperandOfKind(operand, kind)) {
463
+ return void 0;
464
+ }
465
+ const target = comparable(operand, kind);
466
+ return (value) => {
467
+ if (isEmptyCell(value)) {
468
+ return void 0;
469
+ }
470
+ const cell = comparable(value, kind);
471
+ return cell === void 0 ? void 0 : compareValues(cell, target, type);
472
+ };
473
+ }
474
+ function isScalarList(operand) {
475
+ return Array.isArray(operand);
476
+ }
477
+ function compileOrdering(operator, operand, type) {
478
+ const compare = compileComparison(operand, type);
479
+ if (compare === void 0) {
480
+ return matchNothing;
481
+ }
482
+ const where = (holds) => (value) => {
483
+ const result = compare(value);
484
+ return result !== void 0 && holds(result);
485
+ };
486
+ switch (operator) {
487
+ case "eq":
488
+ return where((result) => result === 0);
489
+ case "ne": {
490
+ const equals = where((result) => result === 0);
491
+ return (value) => !equals(value);
492
+ }
493
+ case "gt":
494
+ return where((result) => result > 0);
495
+ case "gte":
496
+ return where((result) => result >= 0);
497
+ case "lt":
498
+ return where((result) => result < 0);
499
+ case "lte":
500
+ return where((result) => result <= 0);
501
+ }
502
+ }
503
+ function compileBetween(operand, type) {
504
+ if (!isScalarList(operand) || operand.length !== 2) {
505
+ return matchNothing;
506
+ }
507
+ const [low, high] = operand;
508
+ const fromLow = compileComparison(low, type);
509
+ const fromHigh = compileComparison(high, type);
510
+ if (fromLow === void 0 || fromHigh === void 0) {
511
+ return matchNothing;
512
+ }
513
+ return (value) => {
514
+ const aboveLow = fromLow(value);
515
+ const belowHigh = fromHigh(value);
516
+ return aboveLow !== void 0 && belowHigh !== void 0 && aboveLow >= 0 && belowHigh <= 0;
517
+ };
518
+ }
519
+ function filterValueKey(value, type) {
520
+ return bucketKey(isDateType(type) ? toDate(value) ?? value : value);
521
+ }
522
+ function compileIn(operand, type) {
523
+ if (!isScalarList(operand)) {
524
+ return matchNothing;
525
+ }
526
+ const keys = new Set(
527
+ operand.filter((scalar) => !isEmptyCell(scalar)).map((scalar) => filterValueKey(scalar, type))
528
+ );
529
+ return (value) => !isEmptyCell(value) && keys.has(filterValueKey(value, type));
530
+ }
531
+ function compileText(operator, operand) {
532
+ if (!isOperandOfKind(operand, "text")) {
533
+ return matchNothing;
534
+ }
535
+ const text = String(operand).toLowerCase();
536
+ const read = (value) => String(value).toLowerCase();
537
+ switch (operator) {
538
+ case "contains":
539
+ return (value) => !isEmptyCell(value) && read(value).includes(text);
540
+ case "notContains":
541
+ return (value) => isEmptyCell(value) || !read(value).includes(text);
542
+ case "startsWith":
543
+ return (value) => !isEmptyCell(value) && read(value).startsWith(text);
544
+ case "endsWith":
545
+ return (value) => !isEmptyCell(value) && read(value).endsWith(text);
546
+ }
547
+ }
548
+ function compileOperatorEntry(entry, type) {
549
+ const { operator, value } = entry;
550
+ switch (operator) {
551
+ case "isEmpty":
552
+ return isEmptyCell;
553
+ case "isNotEmpty":
554
+ return (cell) => !isEmptyCell(cell);
555
+ case "contains":
556
+ case "notContains":
557
+ case "startsWith":
558
+ case "endsWith":
559
+ return compileText(operator, value);
560
+ case "between":
561
+ return compileBetween(value, type);
562
+ case "in":
563
+ return compileIn(value, type);
564
+ case "eq":
565
+ case "ne":
566
+ case "gt":
567
+ case "gte":
568
+ case "lt":
569
+ case "lte":
570
+ return compileOrdering(operator, value, type);
571
+ }
572
+ }
573
+
574
+ // src/util/filtering.ts
575
+ function parseFilterPattern(query) {
576
+ const start = query.startsWith("%");
577
+ const end = query.endsWith("%");
578
+ let text = query;
579
+ if (start) {
580
+ text = text.slice(1);
581
+ }
582
+ if (end) {
583
+ text = text.slice(0, -1);
584
+ }
585
+ text = text.toLowerCase();
586
+ if (start && end) {
587
+ return { mode: "contains", text };
588
+ }
589
+ if (start) {
590
+ return { mode: "endsWith", text };
591
+ }
592
+ if (end) {
593
+ return { mode: "startsWith", text };
594
+ }
595
+ return { mode: "exact", text };
596
+ }
597
+ function isEmptyValue(value) {
598
+ return value === null || value === void 0;
599
+ }
600
+ function compileFilterQuery(query) {
601
+ const { mode, text } = parseFilterPattern(query);
602
+ return (value) => {
603
+ const candidate = (isEmptyValue(value) ? "" : String(value)).toLowerCase();
604
+ switch (mode) {
605
+ case "exact":
606
+ return candidate === text;
607
+ case "contains":
608
+ return candidate.includes(text);
609
+ case "startsWith":
610
+ return candidate.startsWith(text);
611
+ case "endsWith":
612
+ return candidate.endsWith(text);
613
+ }
614
+ };
615
+ }
616
+ function matchesTypedValue(value, target, type) {
617
+ if (typeof target === "number") {
618
+ if (type !== "number" && type !== "decimal" && type !== "currency" && type !== "percent") {
619
+ return false;
620
+ }
621
+ return typeof value === "number" && value === target;
622
+ }
623
+ if (typeof target === "boolean") {
624
+ if (type !== "boolean") {
625
+ return false;
626
+ }
627
+ return typeof value === "boolean" && value === target;
628
+ }
629
+ if (type !== "date" && type !== "dateTime" && type !== "time") {
630
+ return false;
631
+ }
632
+ return value instanceof Date && value.getTime() === target.getTime();
633
+ }
634
+ function isEntryUsable(entry, byId) {
635
+ if (entry.kind === "group") {
636
+ return true;
637
+ }
638
+ return entry.columnId === void 0 || byId.has(entry.columnId);
639
+ }
640
+ function unknownFilterEntry(entry) {
641
+ const { kind } = entry;
642
+ throw new TypeError(
643
+ `GridKit: \`${String(kind)}\` is not a filter entry kind.`
644
+ );
645
+ }
646
+ function compileCellTest(columnId, byId, columns, test) {
647
+ if (columnId === void 0) {
648
+ return (row) => columns.some(
649
+ (entry) => test(accessDotted(row, entry.column.field), entry.column.type)
650
+ );
651
+ }
652
+ const column = byId.get(columnId);
653
+ if (column === void 0) {
654
+ return () => false;
655
+ }
656
+ return (row) => test(accessDotted(row, column.field), column.type);
657
+ }
658
+ function compileFilterEntry(entry, byId, columns) {
659
+ switch (entry.kind) {
660
+ case "group": {
661
+ const tests = entry.entries.filter((nested) => isEntryUsable(nested, byId)).map((nested) => compileFilterEntry(nested, byId, columns));
662
+ return entry.combinator === "and" ? (row) => tests.every((test) => test(row)) : (row) => tests.some((test) => test(row));
663
+ }
664
+ case "predicate": {
665
+ const { columnId, predicate } = entry;
666
+ const column = columnId === void 0 ? void 0 : byId.get(columnId);
667
+ return (row) => predicate(
668
+ column === void 0 ? void 0 : accessDotted(row, column.field),
669
+ row
670
+ );
671
+ }
672
+ case "operator": {
673
+ const column = byId.get(entry.columnId);
674
+ if (column === void 0) {
675
+ return () => false;
676
+ }
677
+ const test = compileOperatorEntry(entry, column.type);
678
+ return (row) => test(accessDotted(row, column.field));
679
+ }
680
+ case "value": {
681
+ const { value } = entry;
682
+ return compileCellTest(
683
+ entry.columnId,
684
+ byId,
685
+ columns,
686
+ (cell, type) => matchesTypedValue(cell, value, type)
687
+ );
688
+ }
689
+ case "text": {
690
+ const test = compileFilterQuery(entry.query);
691
+ return compileCellTest(entry.columnId, byId, columns, test);
692
+ }
693
+ default:
694
+ return unknownFilterEntry(entry);
695
+ }
696
+ }
697
+ function compileFilter(filter, columns) {
698
+ const byId = new Map(columns.map((entry) => [entry.id, entry.column]));
699
+ const compiled = filter.filter((entry) => isEntryUsable(entry, byId)).map((entry) => compileFilterEntry(entry, byId, columns));
700
+ return compiled.length === 0 ? void 0 : (row) => compiled.every((test) => test(row));
701
+ }
702
+ function matchesQuery(value, query) {
703
+ return compileFilterQuery(query)(value);
704
+ }
705
+ function filterQueryFor(filter, columnId) {
706
+ const entry = filter.find(
707
+ (candidate) => candidate.kind === "text" && candidate.columnId === columnId
708
+ );
709
+ return entry?.query ?? null;
710
+ }
711
+ function setColumnFilter(filter, columnId, query) {
712
+ const index = filter.findIndex(
713
+ (entry) => entry.kind !== "group" && entry.columnId === columnId
714
+ );
715
+ if (query === "") {
716
+ return index === -1 ? filter : filter.filter((_entry, i) => i !== index);
717
+ }
718
+ const next = columnId === void 0 ? { kind: "text", query } : { kind: "text", columnId, query };
719
+ if (index === -1) {
720
+ return [...filter, next];
721
+ }
722
+ const existing = filter[index];
723
+ if (existing?.kind === "text" && existing.query === query) {
724
+ return filter;
725
+ }
726
+ return filter.map((entry, i) => i === index ? next : entry);
727
+ }
728
+ function clearAllFilters(filter) {
729
+ return filter.length === 0 ? filter : [];
730
+ }
731
+ function filterRows(rows, filter, columns) {
732
+ if (filter.length === 0) {
733
+ return rows;
734
+ }
735
+ const test = compileFilter(filter, columns);
736
+ if (test === void 0) {
737
+ return rows;
738
+ }
739
+ const filtered = rows.filter((row) => test(row.row));
740
+ return renumberRows(filtered);
741
+ }
742
+
743
+ // src/util/rows.ts
744
+ function resolveShownRows(rows, filter, sort, columns) {
745
+ return sortRows(filterRows(rows, filter, columns), sort, columns);
746
+ }
747
+ function unknownDisplayRow(entry) {
748
+ const { kind } = entry;
749
+ throw new TypeError(
750
+ `GridKit: \`${String(kind)}\` is not a display row kind.`
751
+ );
752
+ }
753
+ function resolveRows(rowsById, ids) {
754
+ return ids.map((id) => rowsById.get(id)).filter((row) => row !== void 0);
755
+ }
756
+ function resolveColumns(columns, ids) {
757
+ return ids.map((id) => {
758
+ const columnIndex = columns.findIndex((entry) => entry.id === id);
759
+ const column = columns[columnIndex];
760
+ return column === void 0 ? void 0 : { columnId: id, column, columnIndex };
761
+ }).filter((column) => column !== void 0);
762
+ }
763
+ function resolveCell(rowsById, columns, cell) {
764
+ if (cell === null) {
765
+ return null;
766
+ }
767
+ const entry = rowsById.get(cell.rowId);
768
+ const columnIndex = columns.findIndex(
769
+ (candidate) => candidate.id === cell.columnId
770
+ );
771
+ const column = columns[columnIndex];
772
+ if (entry === void 0 || column === void 0) {
773
+ return null;
774
+ }
775
+ return {
776
+ rowId: cell.rowId,
777
+ columnId: cell.columnId,
778
+ row: entry.row,
779
+ column,
780
+ rowIndex: entry.rowIndex,
781
+ columnIndex,
782
+ value: accessDotted(entry.row, column.column.field)
783
+ };
784
+ }
785
+
786
+ // src/util/sizing.ts
787
+ var DEFAULT_COLUMN_SIZES = {
788
+ width: 150,
789
+ minWidth: 40,
790
+ maxWidth: Number.POSITIVE_INFINITY
791
+ };
792
+ var KEYBOARD_STEP = 10;
793
+ function withDefaults(defaults) {
794
+ return { ...DEFAULT_COLUMN_SIZES, ...defaults };
795
+ }
796
+ function resolveColumnConstraints(column, defaults) {
797
+ const resolved = withDefaults(defaults);
798
+ return {
799
+ minWidth: column.minWidth ?? resolved.minWidth,
800
+ maxWidth: column.maxWidth ?? resolved.maxWidth
801
+ };
802
+ }
803
+ function clampColumnWidth(width, constraints) {
804
+ return Math.min(Math.max(width, constraints.minWidth), constraints.maxWidth);
805
+ }
806
+ function resolveColumnWidths(columns, sizing, options) {
807
+ const resolved = withDefaults(options?.sizes);
808
+ return columns.map((column) => {
809
+ const id = getColumnId(column);
810
+ const stored = sizing[id];
811
+ return {
812
+ column,
813
+ id,
814
+ sized: stored !== void 0,
815
+ width: clampColumnWidth(
816
+ stored ?? column.width ?? resolved.width,
817
+ resolveColumnConstraints(column, resolved)
818
+ ),
819
+ label: resolveColumnLabel(column),
820
+ resizable: column.resizable ?? options?.resizable ?? false,
821
+ reorderable: column.reorderable ?? options?.reorderable ?? false,
822
+ groupByDraggable: column.groupByDraggable ?? options?.groupByDraggable ?? false,
823
+ alignment: column.alignment ?? alignmentForType(column.type ?? "string")
824
+ };
825
+ });
826
+ }
827
+ function totalColumnWidth(resolved) {
828
+ return resolved.reduce((total, entry) => total + entry.width, 0);
829
+ }
830
+ function beginColumnResize(column, startWidth, startPosition, defaults) {
831
+ return {
832
+ columnId: getColumnId(column),
833
+ startWidth,
834
+ startPosition,
835
+ constraints: resolveColumnConstraints(column, defaults)
836
+ };
837
+ }
838
+ function applyColumnResize(session, position) {
839
+ return clampColumnWidth(
840
+ session.startWidth + (position - session.startPosition),
841
+ session.constraints
842
+ );
843
+ }
844
+ function reachedBound(width, item) {
845
+ return item.bound > item.width ? width >= item.bound : width <= item.bound;
846
+ }
847
+ function redistribute(entries, remaining) {
848
+ for (; ; ) {
849
+ const movable = entries.filter(
850
+ (item) => item.adjustable && !reachedBound(item.width, item)
851
+ );
852
+ const left = remaining(entries.reduce((t, i) => t + i.width, 0));
853
+ if (left <= 0 || movable.length === 0) {
854
+ break;
855
+ }
856
+ const base = movable.reduce((total, item) => total + item.width, 0);
857
+ let clamped = false;
858
+ for (const item of movable) {
859
+ const share = base === 0 ? left / movable.length : left * item.width / base;
860
+ const next = item.width + (item.bound > item.width ? share : -share);
861
+ if (reachedBound(next, item)) {
862
+ item.width = item.bound;
863
+ clamped = true;
864
+ } else {
865
+ item.width = next;
866
+ }
867
+ }
868
+ if (!clamped) {
869
+ break;
870
+ }
871
+ }
872
+ }
873
+ function fitColumnsToWidth(resolved, availableWidth, defaults) {
874
+ const target = Math.floor(availableWidth);
875
+ const total = totalColumnWidth(resolved);
876
+ if (resolved.length === 0 || total === target) {
877
+ return resolved;
878
+ }
879
+ const growing = total < target;
880
+ const entries = resolved.map((entry) => {
881
+ const constraints = resolveColumnConstraints(entry.column, defaults);
882
+ return {
883
+ entry,
884
+ width: entry.width,
885
+ bound: growing ? constraints.maxWidth : constraints.minWidth,
886
+ adjustable: !entry.sized
887
+ };
888
+ });
889
+ if (!growing) {
890
+ const floor = entries.reduce(
891
+ (sum, item) => sum + (item.adjustable ? item.bound : item.width),
892
+ 0
893
+ );
894
+ if (floor > target) {
895
+ return resolved;
896
+ }
897
+ }
898
+ redistribute(entries, (sum) => growing ? target - sum : sum - target);
899
+ const rounded = entries.map(
900
+ (item) => growing ? Math.floor(item.width) : Math.ceil(item.width)
901
+ );
902
+ let remainder = target - rounded.reduce((total2, width) => total2 + width, 0);
903
+ return entries.map((item, index) => {
904
+ let width = rounded[index] ?? item.width;
905
+ const hasRoom = growing ? width < item.bound : width > item.bound;
906
+ if (remainder !== 0 && item.adjustable && hasRoom) {
907
+ width += growing ? 1 : -1;
908
+ remainder += growing ? -1 : 1;
909
+ }
910
+ return { ...item.entry, width };
911
+ });
912
+ }
913
+ function sizeColumnToContent(measuredWidth, constraints, padding = 2) {
914
+ return clampColumnWidth(Math.ceil(measuredWidth + padding), constraints);
915
+ }
916
+ function revertColumnSize(current, base, columnId) {
917
+ const next = Object.fromEntries(
918
+ Object.entries(current).filter(([id]) => id !== columnId)
919
+ );
920
+ if (columnId in base) {
921
+ next[columnId] = base[columnId];
922
+ }
923
+ return next;
924
+ }
925
+
926
+ // src/util/aggregation.ts
927
+ function isEmpty2(value) {
928
+ return value === null || value === void 0;
929
+ }
930
+ function toNumber(value) {
931
+ return Number(value);
932
+ }
933
+ function distinctKey(value) {
934
+ if (isEmpty2(value)) {
935
+ return "\0empty";
936
+ }
937
+ if (value instanceof Date) {
938
+ return `\0date:${String(value.getTime())}`;
939
+ }
940
+ switch (typeof value) {
941
+ case "string":
942
+ case "number":
943
+ case "boolean":
944
+ case "bigint":
945
+ case "symbol":
946
+ return `\0${typeof value}:${String(value)}`;
947
+ case "function":
948
+ return "\0function";
949
+ default:
950
+ return `\0object:${JSON.stringify(value)}`;
951
+ }
952
+ }
953
+ function reduceBuiltIn(rows, fn, column) {
954
+ if (fn === "count") {
955
+ return rows.length;
956
+ }
957
+ const field = column?.column.field;
958
+ const values = field === void 0 ? [] : rows.map((row) => accessDotted(row, field));
959
+ switch (fn) {
960
+ case "sum": {
961
+ let total = 0;
962
+ for (const value of values) {
963
+ if (isEmpty2(value)) continue;
964
+ total += toNumber(value);
965
+ }
966
+ return total;
967
+ }
968
+ case "avg": {
969
+ const present = values.filter((value) => !isEmpty2(value));
970
+ if (present.length === 0) return void 0;
971
+ const total = present.reduce(
972
+ (acc, value) => acc + toNumber(value),
973
+ 0
974
+ );
975
+ return total / present.length;
976
+ }
977
+ case "min":
978
+ case "max": {
979
+ const type = column?.column.type;
980
+ let result;
981
+ for (const value of values) {
982
+ if (isEmpty2(value)) continue;
983
+ if (result === void 0) {
984
+ result = value;
985
+ continue;
986
+ }
987
+ const comparison = compareValues(value, result, type);
988
+ if (fn === "min" ? comparison < 0 : comparison > 0) {
989
+ result = value;
990
+ }
991
+ }
992
+ return result;
993
+ }
994
+ case "countDistinct": {
995
+ const seen = /* @__PURE__ */ new Set();
996
+ for (const value of values) {
997
+ if (isEmpty2(value)) continue;
998
+ seen.add(distinctKey(value));
999
+ }
1000
+ return seen.size;
1001
+ }
1002
+ }
1003
+ }
1004
+ function keyOf(spec) {
1005
+ return spec.id ?? spec.columnId;
1006
+ }
1007
+ function computeAggregates(rows, specs, columns) {
1008
+ const results = /* @__PURE__ */ new Map();
1009
+ if (specs.length === 0) {
1010
+ return results;
1011
+ }
1012
+ const byId = new Map(columns.map((entry) => [entry.id, entry]));
1013
+ for (const spec of specs) {
1014
+ const value = typeof spec.fn === "function" ? spec.fn(rows) : reduceBuiltIn(rows, spec.fn, byId.get(spec.columnId));
1015
+ results.set(keyOf(spec), value);
1016
+ }
1017
+ return results;
1018
+ }
1019
+ function leafDescendantsOf(flatRows, path, groupBy, byId) {
1020
+ const keys = path.map((value) => bucketKey(value));
1021
+ return flatRows.filter(
1022
+ (row) => keys.every((key, level) => {
1023
+ const columnId = groupBy[level]?.columnId;
1024
+ const column = columnId === void 0 ? void 0 : byId.get(columnId);
1025
+ if (column === void 0) return false;
1026
+ return bucketKey(accessDotted(row.row, column.field)) === key;
1027
+ })
1028
+ ).map((row) => row.row);
1029
+ }
1030
+ function appendAggregatedSpan(displayRows, start, levelFloor, flatRows, groupBy, byId, specs, columns, display, out) {
1031
+ let index = start;
1032
+ while (index < displayRows.length) {
1033
+ const entry = displayRows[index];
1034
+ if (entry === void 0) {
1035
+ index++;
1036
+ continue;
1037
+ }
1038
+ if (levelFloor !== null && entry.kind === "group" && entry.level <= levelFloor) {
1039
+ break;
1040
+ }
1041
+ index++;
1042
+ if (entry.kind !== "group") {
1043
+ out.push(entry);
1044
+ continue;
1045
+ }
1046
+ const leaves = leafDescendantsOf(flatRows, entry.path, groupBy, byId);
1047
+ const aggregates = computeAggregates(leaves, specs, columns);
1048
+ const withAggregates = { ...entry, aggregates };
1049
+ out.push(withAggregates);
1050
+ index = appendAggregatedSpan(
1051
+ displayRows,
1052
+ index,
1053
+ entry.level,
1054
+ flatRows,
1055
+ groupBy,
1056
+ byId,
1057
+ specs,
1058
+ columns,
1059
+ display,
1060
+ out
1061
+ );
1062
+ if (display === "row") {
1063
+ const summary = {
1064
+ kind: "group-summary",
1065
+ groupId: entry.groupId,
1066
+ level: entry.level,
1067
+ rowIndex: -1,
1068
+ datasetIndex: -1,
1069
+ aggregates
1070
+ };
1071
+ out.push(summary);
1072
+ }
1073
+ }
1074
+ return index;
1075
+ }
1076
+ function withGroupAggregates(displayRows, flatRows, groupBy, specs, columns, display = "inline") {
1077
+ if (specs.length === 0) {
1078
+ return displayRows;
1079
+ }
1080
+ const byId = new Map(columns.map((entry) => [entry.id, entry.column]));
1081
+ const out = [];
1082
+ appendAggregatedSpan(
1083
+ displayRows,
1084
+ 0,
1085
+ null,
1086
+ flatRows,
1087
+ groupBy,
1088
+ byId,
1089
+ specs,
1090
+ columns,
1091
+ display,
1092
+ out
1093
+ );
1094
+ return renumberRows(out);
1095
+ }
1096
+
1097
+ // src/util/visibility.ts
1098
+ function isColumnVisible(column, visibility) {
1099
+ return visibility[getColumnId(column)] ?? column.hidden !== true;
1100
+ }
1101
+ function applyColumnVisibility(columns, visibility) {
1102
+ const visible = columns.filter(
1103
+ (entry) => isColumnVisible(entry.column, visibility)
1104
+ );
1105
+ return visible.length === columns.length ? columns : visible;
1106
+ }
1107
+ function setColumnVisibility(columns, visibility, columnIds, visible) {
1108
+ const requested = new Set(columnIds);
1109
+ const changed = columns.filter(
1110
+ (entry) => requested.has(entry.id) && isColumnVisible(entry.column, visibility) !== visible
1111
+ );
1112
+ if (changed.length === 0) {
1113
+ return visibility;
1114
+ }
1115
+ return {
1116
+ ...visibility,
1117
+ ...Object.fromEntries(changed.map((entry) => [entry.id, visible]))
1118
+ };
1119
+ }
1120
+
1121
+ // src/util/selection.ts
1122
+ var NO_CHANGE = { added: [], removed: [] };
1123
+ function sameSelection(a, b) {
1124
+ return a.length === b.length && a.every((id, index) => id === b[index]);
1125
+ }
1126
+ function toggleSelection(selection, id, mode) {
1127
+ if (mode === false) {
1128
+ return selection;
1129
+ }
1130
+ if (selection.includes(id)) {
1131
+ return selection.filter((selectedId) => selectedId !== id);
1132
+ }
1133
+ return mode === "single" ? [id] : [...selection, id];
1134
+ }
1135
+ function selectOnly(selection, id, mode) {
1136
+ if (mode === false) {
1137
+ return selection;
1138
+ }
1139
+ return selection.length === 1 && selection[0] === id ? selection : [id];
1140
+ }
1141
+ function selectRange(selection, orderedIds, anchorId, focusId, mode) {
1142
+ if (mode !== "multiple") {
1143
+ return selectOnly(selection, focusId, mode);
1144
+ }
1145
+ const anchor = orderedIds.indexOf(anchorId);
1146
+ const focus = orderedIds.indexOf(focusId);
1147
+ if (anchor === -1 || focus === -1) {
1148
+ return selection;
1149
+ }
1150
+ const next = orderedIds.slice(
1151
+ Math.min(anchor, focus),
1152
+ Math.max(anchor, focus) + 1
1153
+ );
1154
+ return sameSelection(selection, next) ? selection : next;
1155
+ }
1156
+ function selectAll(selection, orderedIds, mode) {
1157
+ if (mode !== "multiple") {
1158
+ return selection;
1159
+ }
1160
+ return sameSelection(selection, orderedIds) ? selection : orderedIds;
1161
+ }
1162
+ function clearSelection(selection) {
1163
+ return selection.length === 0 ? selection : [];
1164
+ }
1165
+ function diffSelection(previous, next) {
1166
+ if (previous === next) {
1167
+ return NO_CHANGE;
1168
+ }
1169
+ const before = new Set(previous);
1170
+ const after = new Set(next);
1171
+ return {
1172
+ added: next.filter((id) => !before.has(id)),
1173
+ removed: previous.filter((id) => !after.has(id))
1174
+ };
1175
+ }
1176
+ function isSameCell(a, b) {
1177
+ if (a === null || b === null) {
1178
+ return a === b;
1179
+ }
1180
+ return a.rowId === b.rowId && a.columnId === b.columnId;
1181
+ }
1182
+ function selectCell(selection, cell, mode) {
1183
+ if (mode === false || isSameCell(selection, cell)) {
1184
+ return selection;
1185
+ }
1186
+ return cell;
1187
+ }
1188
+ function toggleCellSelection(selection, cell, mode) {
1189
+ if (mode === false) {
1190
+ return selection;
1191
+ }
1192
+ return isSameCell(selection, cell) ? null : cell;
1193
+ }
1194
+ function intentOf(event, options) {
1195
+ if (event.shiftKey) {
1196
+ return "range";
1197
+ }
1198
+ if (event.ctrlKey || event.metaKey) {
1199
+ return "toggle";
1200
+ }
1201
+ return options?.toggleOnClick === true ? "toggle" : "replace";
1202
+ }
1203
+ function applySelectionIntent(selection, orderedIds, anchorId, id, intent, mode) {
1204
+ switch (intent) {
1205
+ case "toggle":
1206
+ return toggleSelection(selection, id, mode);
1207
+ // A range with no anchor yet spans from the id to itself, which is the
1208
+ // plain click a first Shift-click may as well be.
1209
+ case "range":
1210
+ return selectRange(selection, orderedIds, anchorId ?? id, id, mode);
1211
+ default:
1212
+ return selectOnly(selection, id, mode);
1213
+ }
1214
+ }
1215
+
1216
+ // src/util/format.ts
1217
+ var DATE_FIELDS = {
1218
+ year: "numeric",
1219
+ month: "numeric",
1220
+ day: "numeric"
1221
+ };
1222
+ var TIME_FIELDS = {
1223
+ hour: "numeric",
1224
+ minute: "numeric",
1225
+ second: "numeric"
1226
+ };
1227
+ var DATE_TIME_FIELDS = {
1228
+ ...DATE_FIELDS,
1229
+ ...TIME_FIELDS
1230
+ };
1231
+ var CURRENCY_DIGITS = {
1232
+ minimumFractionDigits: 2,
1233
+ maximumFractionDigits: 2
1234
+ };
1235
+ var NO_FORMAT = {};
1236
+ var formatters = /* @__PURE__ */ new WeakMap();
1237
+ function cached(format, key, create) {
1238
+ const owner = format ?? NO_FORMAT;
1239
+ let byKey = formatters.get(owner);
1240
+ if (byKey === void 0) {
1241
+ byKey = /* @__PURE__ */ new Map();
1242
+ formatters.set(owner, byKey);
1243
+ }
1244
+ const existing = byKey.get(key);
1245
+ if (existing !== void 0) {
1246
+ return existing;
1247
+ }
1248
+ const formatter = create();
1249
+ byKey.set(key, formatter);
1250
+ return formatter;
1251
+ }
1252
+ function localeKey(locale) {
1253
+ return typeof locale === "string" ? locale : locale?.join(",") ?? "";
1254
+ }
1255
+ function isNumericType(type) {
1256
+ return type === "number" || type === "decimal" || type === "currency" || type === "percent";
1257
+ }
1258
+ function numberOptions(type, format) {
1259
+ switch (type) {
1260
+ case "currency":
1261
+ return format?.currency === void 0 ? { ...CURRENCY_DIGITS, ...format } : { style: "currency", ...format };
1262
+ case "percent":
1263
+ return { style: "percent", ...format };
1264
+ default:
1265
+ return format ?? {};
1266
+ }
1267
+ }
1268
+ function dateOptions(type, format) {
1269
+ if (format !== void 0) {
1270
+ return format;
1271
+ }
1272
+ if (type === "date") return DATE_FIELDS;
1273
+ if (type === "time") return TIME_FIELDS;
1274
+ return DATE_TIME_FIELDS;
1275
+ }
1276
+ function formatNumber(value, type, format, locale) {
1277
+ const formatter = cached(
1278
+ format,
1279
+ `number|${type ?? ""}|${localeKey(locale)}`,
1280
+ () => new Intl.NumberFormat(
1281
+ locale,
1282
+ numberOptions(type, format)
1283
+ )
1284
+ );
1285
+ return formatter.format(value);
1286
+ }
1287
+ function formatDate(value, type, format, locale) {
1288
+ if (Number.isNaN(value.getTime())) {
1289
+ return String(value);
1290
+ }
1291
+ const formatter = cached(
1292
+ format,
1293
+ `date|${type ?? ""}|${localeKey(locale)}`,
1294
+ () => new Intl.DateTimeFormat(
1295
+ locale,
1296
+ dateOptions(type, format)
1297
+ )
1298
+ );
1299
+ return formatter.format(value);
1300
+ }
1301
+ function formatOther(value) {
1302
+ if (typeof value === "function") {
1303
+ return "(function)";
1304
+ }
1305
+ if (typeof value === "object" && value !== null) {
1306
+ try {
1307
+ return JSON.stringify(value);
1308
+ } catch {
1309
+ return Object.prototype.toString.call(value);
1310
+ }
1311
+ }
1312
+ return String(value);
1313
+ }
1314
+ function formatCellValue(value, column, locale, row, messages) {
1315
+ if (column.valueFormatter !== void 0) {
1316
+ return column.valueFormatter(value, row);
1317
+ }
1318
+ if (value === null || value === void 0) {
1319
+ return "";
1320
+ }
1321
+ if (typeof value === "boolean" && messages !== void 0) {
1322
+ return value ? messages.booleanTrue : messages.booleanFalse;
1323
+ }
1324
+ const { type, format } = column;
1325
+ const formatted = format !== void 0 || locale !== void 0;
1326
+ if (value instanceof Date) {
1327
+ return formatted ? formatDate(value, type, format, locale) : value.toLocaleString();
1328
+ }
1329
+ if (formatted && (typeof value === "number" || typeof value === "bigint") && isNumericType(type)) {
1330
+ return formatNumber(value, type, format, locale);
1331
+ }
1332
+ if (typeof value === "string") {
1333
+ return value;
1334
+ }
1335
+ return formatOther(value);
1336
+ }
1337
+ function aggregateFormatColumn(value, spec, column) {
1338
+ const plain = {
1339
+ field: spec.columnId,
1340
+ type: "number"
1341
+ };
1342
+ if (column === void 0 || spec.fn === "count" || spec.fn === "countDistinct") {
1343
+ return plain;
1344
+ }
1345
+ const numeric = typeof value === "number" || typeof value === "bigint";
1346
+ return column.valueFormatter === void 0 && numeric && !isNumericType(column.type) ? plain : column;
1347
+ }
1348
+ function formatAggregateValue(value, spec, column, locale) {
1349
+ const target = aggregateFormatColumn(value, spec, column);
1350
+ if (typeof value === "number" && target.valueFormatter === void 0 && target.format === void 0 && locale === void 0) {
1351
+ return value.toLocaleString();
1352
+ }
1353
+ return formatCellValue(value, target, locale);
1354
+ }
1355
+ function formatGroupValue(value, column, locale, messages) {
1356
+ return value === null || value === void 0 ? messages.blankGroupValue : formatCellValue(value, column, locale, void 0, messages);
1357
+ }
1358
+
1359
+ // src/export/buildExportTable.ts
1360
+ var EMPTY_CELL = { value: null, text: "" };
1361
+ function isDataRow(entry) {
1362
+ return entry.kind === "data";
1363
+ }
1364
+ function pickColumns(view, selection) {
1365
+ let picked;
1366
+ if (selection === "visible") {
1367
+ picked = view.columns;
1368
+ } else if (selection === "all") {
1369
+ picked = view.dataColumns;
1370
+ } else {
1371
+ const byId = new Map(view.dataColumns.map((entry) => [entry.id, entry]));
1372
+ picked = [...new Set(selection)].flatMap((id) => byId.get(id) ?? []);
1373
+ }
1374
+ return picked.filter((entry) => entry.column.exportable !== false);
1375
+ }
1376
+ function describeColumns(picked, source) {
1377
+ const shown = new Map(source.view.columns.map((entry) => [entry.id, entry]));
1378
+ const resolved = resolveColumnWidths(
1379
+ picked.map((entry) => entry.column),
1380
+ source.state.columnSizing,
1381
+ { sizes: source.options.columnSizeDefaults }
1382
+ );
1383
+ return resolved.map((entry) => {
1384
+ const rendered = shown.get(entry.id) ?? entry;
1385
+ return {
1386
+ id: rendered.id,
1387
+ header: resolveColumnHeaderText(rendered.column),
1388
+ type: rendered.column.type ?? "string",
1389
+ format: rendered.column.format,
1390
+ alignment: rendered.alignment,
1391
+ width: rendered.width
1392
+ };
1393
+ });
1394
+ }
1395
+ function scopedRows(source, scope) {
1396
+ const { view, state } = source;
1397
+ switch (scope) {
1398
+ case "all":
1399
+ return view.rows;
1400
+ case "page":
1401
+ return view.displayDataRows;
1402
+ case "selection": {
1403
+ const selected = new Set(state.rowSelection);
1404
+ return view.rows.filter((entry) => selected.has(entry.rowId));
1405
+ }
1406
+ }
1407
+ }
1408
+ function typedValue(value, text) {
1409
+ if (value === null || value === void 0) {
1410
+ return null;
1411
+ }
1412
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value instanceof Date ? value : text;
1413
+ }
1414
+ function dataCell(row, column, context) {
1415
+ const raw = accessDotted(row, column.field);
1416
+ const text = formatCellValue(
1417
+ raw,
1418
+ column,
1419
+ context.locale,
1420
+ row,
1421
+ context.messages
1422
+ );
1423
+ return {
1424
+ value: column.exportValue === void 0 ? typedValue(raw, text) : column.exportValue(raw, row),
1425
+ text
1426
+ };
1427
+ }
1428
+ function aggregateCell(results, specs, column, locale) {
1429
+ const parts = specs.flatMap((spec) => {
1430
+ const value = results.get(spec.id ?? spec.columnId);
1431
+ return value === null || value === void 0 ? [] : [{ value, text: formatAggregateValue(value, spec, column, locale) }];
1432
+ });
1433
+ const [only] = parts;
1434
+ if (only === void 0) {
1435
+ return EMPTY_CELL;
1436
+ }
1437
+ if (parts.length === 1) {
1438
+ return { value: typedValue(only.value, only.text), text: only.text };
1439
+ }
1440
+ const text = parts.map((part) => part.text).join(", ");
1441
+ return { value: text, text };
1442
+ }
1443
+ function aggregateCells(results, context) {
1444
+ return context.columns.map((entry) => {
1445
+ const specs = context.specsByColumn.get(entry.id);
1446
+ return specs === void 0 ? EMPTY_CELL : aggregateCell(results, specs, entry.column, context.locale);
1447
+ });
1448
+ }
1449
+ function groupLabel(entry, source) {
1450
+ const column = source.view.dataColumns.find(
1451
+ (candidate) => candidate.id === entry.columnId
1452
+ )?.column ?? { field: entry.columnId };
1453
+ const value = formatGroupValue(
1454
+ entry.value,
1455
+ column,
1456
+ source.options.locale,
1457
+ source.messages
1458
+ );
1459
+ return `${resolveColumnHeaderText(column)}: ${value}`;
1460
+ }
1461
+ function toExportRow(entry, source, context) {
1462
+ switch (entry.kind) {
1463
+ case "data":
1464
+ return {
1465
+ kind: "data",
1466
+ rowId: entry.rowId,
1467
+ cells: context.columns.map(
1468
+ (column) => dataCell(entry.row, column.column, context)
1469
+ )
1470
+ };
1471
+ case "group":
1472
+ return {
1473
+ kind: "group",
1474
+ level: entry.level,
1475
+ groupId: entry.groupId,
1476
+ label: groupLabel(entry, source),
1477
+ count: entry.count,
1478
+ cells: context.display === "inline" ? aggregateCells(entry.aggregates, context) : context.columns.map(() => EMPTY_CELL)
1479
+ };
1480
+ case "group-summary":
1481
+ return {
1482
+ kind: "groupSummary",
1483
+ level: entry.level,
1484
+ cells: aggregateCells(entry.aggregates, context)
1485
+ };
1486
+ default:
1487
+ return unknownDisplayRow(entry);
1488
+ }
1489
+ }
1490
+ function specsByColumnOf(specs) {
1491
+ const byColumn = /* @__PURE__ */ new Map();
1492
+ for (const spec of specs) {
1493
+ const owned = byColumn.get(spec.columnId);
1494
+ if (owned === void 0) {
1495
+ byColumn.set(spec.columnId, [spec]);
1496
+ } else {
1497
+ owned.push(spec);
1498
+ }
1499
+ }
1500
+ return byColumn;
1501
+ }
1502
+ function buildExportTable(source, options = {}) {
1503
+ const { view, state } = source;
1504
+ const specs = options.includeAggregates ?? true ? source.options.aggregates ?? [] : [];
1505
+ const columns = pickColumns(view, options.columns ?? "visible");
1506
+ const context = {
1507
+ columns,
1508
+ specsByColumn: specsByColumnOf(specs),
1509
+ display: source.options.groupAggregateDisplay ?? "inline",
1510
+ locale: source.options.locale,
1511
+ messages: source.messages
1512
+ };
1513
+ const rows = scopedRows(source, options.scope ?? "all");
1514
+ const grouped = groupRows(
1515
+ rows,
1516
+ state.groupBy,
1517
+ ALL_EXPANDED,
1518
+ view.dataColumns
1519
+ );
1520
+ const displayRows = options.includeGroups ?? true ? withGroupAggregates(
1521
+ grouped,
1522
+ rows,
1523
+ state.groupBy,
1524
+ specs,
1525
+ view.dataColumns,
1526
+ context.display
1527
+ ) : grouped.filter(isDataRow);
1528
+ let footer = null;
1529
+ if (specs.length > 0) {
1530
+ const totals = rows === view.rows ? view.grandTotal : computeAggregates(
1531
+ rows.map((entry) => entry.row),
1532
+ specs,
1533
+ view.dataColumns
1534
+ );
1535
+ footer = { kind: "total", cells: aggregateCells(totals, context) };
1536
+ }
1537
+ return {
1538
+ columns: describeColumns(columns, source),
1539
+ header: options.includeHeader ?? true,
1540
+ rows: displayRows.map((entry) => toExportRow(entry, source, context)),
1541
+ footer
1542
+ };
1543
+ }
1544
+
1545
+ // src/export/htmlTable.ts
1546
+ var ENTITIES = {
1547
+ "&": "&amp;",
1548
+ "<": "&lt;",
1549
+ ">": "&gt;",
1550
+ '"': "&quot;",
1551
+ "'": "&#39;"
1552
+ };
1553
+ function escapeHtml(text) {
1554
+ return text.replace(/[&<>"']/g, (char) => ENTITIES[char] ?? char);
1555
+ }
1556
+ function cellHtml(tag, text, column) {
1557
+ const alignment = column?.alignment ?? "left";
1558
+ const style = alignment === "left" ? "" : ` style="text-align:${alignment}"`;
1559
+ return `<${tag}${style}>${escapeHtml(text)}</${tag}>`;
1560
+ }
1561
+ function cellsHtml(cells, columns) {
1562
+ return cells.map((cell, index) => cellHtml("td", cell.text, columns[index])).join("");
1563
+ }
1564
+ function groupRowHtml(row, columns) {
1565
+ const firstAggregate = row.cells.findIndex((cell) => cell.text !== "");
1566
+ const span = Math.max(
1567
+ 1,
1568
+ firstAggregate === -1 ? row.cells.length : firstAggregate
1569
+ );
1570
+ const colspan = span > 1 ? ` colspan="${String(span)}"` : "";
1571
+ const label = `<td${colspan}>${escapeHtml(row.label)}</td>`;
1572
+ const aggregates = row.cells.slice(span).map((cell, index) => cellHtml("td", cell.text, columns[span + index])).join("");
1573
+ return `<tr class="export-group" data-level="${String(row.level)}">${label}${aggregates}</tr>`;
1574
+ }
1575
+ function rowHtml(row, columns) {
1576
+ switch (row.kind) {
1577
+ case "data":
1578
+ return `<tr>${cellsHtml(row.cells, columns)}</tr>`;
1579
+ case "group":
1580
+ return groupRowHtml(row, columns);
1581
+ case "groupSummary":
1582
+ return `<tr class="export-group-summary" data-level="${String(row.level)}">${cellsHtml(row.cells, columns)}</tr>`;
1583
+ }
1584
+ }
1585
+ function toHtmlTable(table, options = {}) {
1586
+ const { columns } = table;
1587
+ const caption = options.caption === void 0 ? "" : `<caption>${escapeHtml(options.caption)}</caption>`;
1588
+ const head = table.header ? `<thead><tr>${columns.map((column) => cellHtml("th", column.header, column)).join("")}</tr></thead>` : "";
1589
+ const body = `<tbody>${table.rows.map((row) => rowHtml(row, columns)).join("")}</tbody>`;
1590
+ const foot = table.footer === null ? "" : `<tfoot><tr>${cellsHtml(table.footer.cells, columns)}</tr></tfoot>`;
1591
+ return `<table class="gridkit-export-table">${caption}${head}${body}${foot}</table>`;
1592
+ }
1593
+
1594
+ // src/export/records.ts
1595
+ function rawText(value) {
1596
+ if (value === null) {
1597
+ return "";
1598
+ }
1599
+ if (value instanceof Date) {
1600
+ return Number.isNaN(value.getTime()) ? "" : value.toISOString();
1601
+ }
1602
+ return String(value);
1603
+ }
1604
+ function cellField(cell, values) {
1605
+ return {
1606
+ text: values === "raw" ? rawText(cell.value) : cell.text,
1607
+ isNumber: typeof cell.value === "number"
1608
+ };
1609
+ }
1610
+ function textField(text) {
1611
+ return { text, isNumber: false };
1612
+ }
1613
+ function textRecords(table, values) {
1614
+ const records = [];
1615
+ if (table.header) {
1616
+ records.push(table.columns.map((column) => textField(column.header)));
1617
+ }
1618
+ for (const row of table.rows) {
1619
+ records.push(
1620
+ row.cells.map(
1621
+ (cell, index) => row.kind === "group" && index === 0 ? textField(row.label) : cellField(cell, values)
1622
+ )
1623
+ );
1624
+ }
1625
+ if (table.footer !== null) {
1626
+ records.push(table.footer.cells.map((cell) => cellField(cell, values)));
1627
+ }
1628
+ return records;
1629
+ }
1630
+
1631
+ // src/export/tsv.ts
1632
+ var SEPARATORS = /\r\n|[\t\r\n]/g;
1633
+ function toTsv(table, options = {}) {
1634
+ return textRecords(table, options.values ?? "text").map(
1635
+ (record) => record.map((field) => field.text.replace(SEPARATORS, " ")).join(" ")
1636
+ ).join("\n");
1637
+ }
1638
+
1639
+ // src/export/copy.ts
1640
+ function isCopyable(column) {
1641
+ return column.column.exportable !== false;
1642
+ }
1643
+ function hasRow(source, rowId) {
1644
+ return source.view.rows.some((entry) => entry.rowId === rowId);
1645
+ }
1646
+ function hasColumn(source, columnId) {
1647
+ return source.view.columns.some(
1648
+ (entry) => entry.id === columnId && isCopyable(entry)
1649
+ );
1650
+ }
1651
+ function selectionCopy(source) {
1652
+ const { state, view } = source;
1653
+ const selectedRows = new Set(state.rowSelection);
1654
+ const count = view.rows.filter(
1655
+ (entry) => selectedRows.has(entry.rowId)
1656
+ ).length;
1657
+ if (count > 0) {
1658
+ return { kind: "rows", count };
1659
+ }
1660
+ const selectedColumns = new Set(state.columnSelection);
1661
+ const columnIds = view.columns.filter((entry) => selectedColumns.has(entry.id) && isCopyable(entry)).map((entry) => entry.id);
1662
+ if (columnIds.length > 0 && view.rows.length > 0) {
1663
+ return { kind: "columns", columnIds };
1664
+ }
1665
+ const cell = state.cellSelection;
1666
+ if (cell !== null && hasRow(source, cell.rowId) && hasColumn(source, cell.columnId)) {
1667
+ return { kind: "cell", rowId: cell.rowId, columnId: cell.columnId };
1668
+ }
1669
+ return null;
1670
+ }
1671
+ function canCopySelection(source) {
1672
+ return selectionCopy(source) !== null;
1673
+ }
1674
+ function withRows(source, rowIds) {
1675
+ return { ...source, state: { ...source.state, rowSelection: rowIds } };
1676
+ }
1677
+ function contentOf(source, { scope, columns, header }, unit) {
1678
+ const table = buildExportTable(source, {
1679
+ scope,
1680
+ columns: columns ?? "visible",
1681
+ includeHeader: header,
1682
+ includeGroups: false,
1683
+ includeAggregates: false
1684
+ });
1685
+ if (table.columns.length === 0 || table.rows.length === 0) {
1686
+ return null;
1687
+ }
1688
+ return {
1689
+ text: toTsv(table),
1690
+ html: toHtmlTable(table),
1691
+ count: unit === "columns" ? table.columns.length : table.rows.length,
1692
+ unit
1693
+ };
1694
+ }
1695
+ function cellContent(source, rowId, columnId) {
1696
+ if (!hasRow(source, rowId) || !hasColumn(source, columnId)) {
1697
+ return null;
1698
+ }
1699
+ return contentOf(
1700
+ withRows(source, [rowId]),
1701
+ { scope: "selection", columns: [columnId], header: false },
1702
+ "cells"
1703
+ );
1704
+ }
1705
+ function rowContent(source, rowId) {
1706
+ if (!hasRow(source, rowId)) {
1707
+ return null;
1708
+ }
1709
+ return contentOf(
1710
+ withRows(source, [rowId]),
1711
+ { scope: "selection", header: false },
1712
+ "rows"
1713
+ );
1714
+ }
1715
+ function selectionContent(source) {
1716
+ const selection = selectionCopy(source);
1717
+ switch (selection?.kind) {
1718
+ case void 0:
1719
+ return null;
1720
+ case "rows":
1721
+ return contentOf(
1722
+ source,
1723
+ { scope: "selection", header: selection.count > 1 },
1724
+ "rows"
1725
+ );
1726
+ case "columns":
1727
+ return contentOf(
1728
+ source,
1729
+ { scope: "all", columns: selection.columnIds, header: true },
1730
+ "columns"
1731
+ );
1732
+ case "cell":
1733
+ return cellContent(source, selection.rowId, selection.columnId);
1734
+ }
1735
+ }
1736
+ function copyContent(source, request) {
1737
+ switch (request.kind) {
1738
+ case "cell":
1739
+ return cellContent(source, request.rowId, request.columnId);
1740
+ case "row":
1741
+ return rowContent(source, request.rowId);
1742
+ case "selection":
1743
+ return selectionContent(source);
1744
+ }
1745
+ }
1746
+
1747
+ // src/util/report.ts
1748
+ function reportError(message) {
1749
+ console.error(`GridKit: ${message}`);
1750
+ }
1751
+
1752
+ // src/export/exportFile.ts
1753
+ function withExtension(fileName, extension) {
1754
+ const suffix = `.${extension}`;
1755
+ return fileName.toLowerCase().endsWith(suffix.toLowerCase()) ? fileName : fileName + suffix;
1756
+ }
1757
+ function writerFor(format, writers) {
1758
+ if (typeof format !== "string") {
1759
+ return format;
1760
+ }
1761
+ const writer = writers.get(format);
1762
+ if (writer === void 0) {
1763
+ reportError(
1764
+ `there is no export writer for \`${format}\` \u2014 register one through \`exportWriters\`.`
1765
+ );
1766
+ return null;
1767
+ }
1768
+ return writer;
1769
+ }
1770
+ function fileNameFor(options, writer) {
1771
+ const { fileName = "export" } = options;
1772
+ const name = typeof fileName === "function" ? fileName(writer.format) : fileName;
1773
+ return withExtension(name, writer.fileExtension);
1774
+ }
1775
+ function exportFile(source, format, options, writers) {
1776
+ const writer = writerFor(format, writers);
1777
+ if (writer === null) {
1778
+ return null;
1779
+ }
1780
+ const content = writer.write(buildExportTable(source, options), {
1781
+ locale: source.options.locale,
1782
+ messages: source.messages,
1783
+ options
1784
+ });
1785
+ const fileName = fileNameFor(options, writer);
1786
+ const { mimeType } = writer;
1787
+ return content instanceof Promise ? content.then((resolved) => ({ fileName, mimeType, content: resolved })) : { fileName, mimeType, content };
1788
+ }
1789
+
1790
+ // src/export/print.ts
1791
+ var PORTRAIT_COLUMN_LIMIT = 6;
1792
+ function resolveOrientation(table, options) {
1793
+ return options.orientation ?? (table.columns.length > PORTRAIT_COLUMN_LIMIT ? "landscape" : "portrait");
1794
+ }
1795
+ function timestampText(timestamp, locale) {
1796
+ const date = timestamp === true ? /* @__PURE__ */ new Date() : timestamp;
1797
+ return new Intl.DateTimeFormat(locale, {
1798
+ dateStyle: "medium",
1799
+ timeStyle: "short"
1800
+ }).format(date);
1801
+ }
1802
+ function line(tag, className, text) {
1803
+ return text === void 0 || text === "" ? "" : `<${tag} class="${className}">${escapeHtml(text)}</${tag}>`;
1804
+ }
1805
+ function headerHtml(options) {
1806
+ const { timestamp = false } = options;
1807
+ const lines = line("h1", "print-title", options.title) + line("p", "print-subtitle", options.subtitle) + (timestamp === false ? "" : line("p", "print-timestamp", timestampText(timestamp, options.locale)));
1808
+ return lines === "" ? "" : `<header class="gridkit-print-header">${lines}</header>`;
1809
+ }
1810
+ function buildPrintDocument(table, options = {}) {
1811
+ const footer = line("footer", "gridkit-print-footer", options.footer);
1812
+ return {
1813
+ title: options.title ?? "",
1814
+ bodyHtml: `${headerHtml(options)}${toHtmlTable(table)}${footer}`,
1815
+ page: {
1816
+ paperSize: options.paperSize ?? "A4",
1817
+ orientation: resolveOrientation(table, options),
1818
+ pageNumbers: options.pageNumbers ?? true,
1819
+ fitToWidth: options.fitToWidth ?? false
1820
+ }
1821
+ };
1822
+ }
1823
+ function exportPrintDocument(source, options = {}) {
1824
+ return buildPrintDocument(buildExportTable(source, options), {
1825
+ ...options,
1826
+ title: options.title ?? source.options.label,
1827
+ locale: options.locale ?? source.options.locale
1828
+ });
1829
+ }
1830
+
1831
+ // src/export/csv.ts
1832
+ var BOM = "\uFEFF";
1833
+ var FORMULA_START = /^[=+\-@\t\r]/;
1834
+ var SIGN_START = /^[+-]/;
1835
+ var NEEDS_QUOTES = /["\r\n]/;
1836
+ function autoDelimiter(locale) {
1837
+ const decimal = new Intl.NumberFormat(locale).formatToParts(1.5).find((part) => part.type === "decimal")?.value;
1838
+ return decimal === "," ? ";" : ",";
1839
+ }
1840
+ function neutralize(field) {
1841
+ const { text } = field;
1842
+ if (!FORMULA_START.test(text) || field.isNumber && SIGN_START.test(text)) {
1843
+ return text;
1844
+ }
1845
+ return `'${text}`;
1846
+ }
1847
+ function quote(text, delimiter) {
1848
+ return text.includes(delimiter) || NEEDS_QUOTES.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
1849
+ }
1850
+ function toCsv(table, options = {}) {
1851
+ const delimiter = options.delimiter === "auto" ? autoDelimiter(options.locale) : options.delimiter ?? ",";
1852
+ const guard = options.neutralizeFormulas ?? true;
1853
+ const lines = textRecords(table, options.values ?? "text").map(
1854
+ (record) => record.map((field) => quote(guard ? neutralize(field) : field.text, delimiter)).join(delimiter)
1855
+ );
1856
+ return (options.bom ?? true ? BOM : "") + lines.join(options.eol ?? "\r\n");
1857
+ }
1858
+
1859
+ // src/export/json.ts
1860
+ function uniqueNames(names) {
1861
+ const used = /* @__PURE__ */ new Set();
1862
+ return names.map((name) => {
1863
+ let unique = name;
1864
+ for (let n = 2; used.has(unique); n += 1) {
1865
+ unique = `${name} (${String(n)})`;
1866
+ }
1867
+ used.add(unique);
1868
+ return unique;
1869
+ });
1870
+ }
1871
+ function toJson(table, options = {}) {
1872
+ const keys = options.keys === "header" ? uniqueNames(table.columns.map((column) => column.header)) : table.columns.map((column) => column.id);
1873
+ const records = table.rows.flatMap(
1874
+ (row) => row.kind === "data" ? [
1875
+ Object.fromEntries(
1876
+ keys.map((key, index) => [key, row.cells[index]?.value ?? null])
1877
+ )
1878
+ ] : []
1879
+ );
1880
+ return JSON.stringify(records, null, options.space);
1881
+ }
1882
+
1883
+ // src/export/writer.ts
1884
+ var csvWriter = {
1885
+ format: "csv",
1886
+ fileExtension: "csv",
1887
+ mimeType: "text/csv;charset=utf-8",
1888
+ write: (table, { locale, options }) => toCsv(table, { locale, ...options.csv })
1889
+ };
1890
+ var jsonWriter = {
1891
+ format: "json",
1892
+ fileExtension: "json",
1893
+ mimeType: "application/json",
1894
+ write: (table, { options }) => toJson(table, options.json)
1895
+ };
1896
+ function resolveExportWriters(writers) {
1897
+ return new Map(
1898
+ [csvWriter, jsonWriter, ...writers ?? []].map((writer) => [
1899
+ writer.format,
1900
+ writer
1901
+ ])
1902
+ );
1903
+ }
1904
+
1905
+ // src/filterMenu/operators.ts
1906
+ function filterOperatorFamily(type) {
1907
+ return kindOf(type);
1908
+ }
1909
+ var familyOperators = {
1910
+ text: [
1911
+ "contains",
1912
+ "notContains",
1913
+ "eq",
1914
+ "ne",
1915
+ "startsWith",
1916
+ "endsWith",
1917
+ "isEmpty",
1918
+ "isNotEmpty"
1919
+ ],
1920
+ number: [
1921
+ "eq",
1922
+ "ne",
1923
+ "gt",
1924
+ "gte",
1925
+ "lt",
1926
+ "lte",
1927
+ "between",
1928
+ "isEmpty",
1929
+ "isNotEmpty"
1930
+ ],
1931
+ date: ["eq", "ne", "lt", "gt", "between", "isEmpty", "isNotEmpty"],
1932
+ boolean: ["eq", "isEmpty", "isNotEmpty"]
1933
+ };
1934
+ var instantOperators = [
1935
+ "lt",
1936
+ "gt",
1937
+ "between",
1938
+ "isEmpty",
1939
+ "isNotEmpty"
1940
+ ];
1941
+ function defaultFilterOperators(type) {
1942
+ return type === "dateTime" || type === "time" ? instantOperators : familyOperators[filterOperatorFamily(type)];
1943
+ }
1944
+ function filterOperandArity(operator) {
1945
+ switch (operator) {
1946
+ case "isEmpty":
1947
+ case "isNotEmpty":
1948
+ return 0;
1949
+ case "between":
1950
+ return 2;
1951
+ case "eq":
1952
+ case "ne":
1953
+ case "contains":
1954
+ case "notContains":
1955
+ case "startsWith":
1956
+ case "endsWith":
1957
+ case "gt":
1958
+ case "gte":
1959
+ case "lt":
1960
+ case "lte":
1961
+ case "in":
1962
+ return 1;
1963
+ }
1964
+ }
1965
+ var NUMBER_INPUT = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
1966
+ var DATE_INPUT = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?)?$/;
1967
+ function parseNumber(text) {
1968
+ const value = Number(text);
1969
+ return NUMBER_INPUT.test(text) && Number.isFinite(value) ? value : void 0;
1970
+ }
1971
+ function parseDate(text) {
1972
+ const match = DATE_INPUT.exec(text);
1973
+ if (match === null) {
1974
+ return void 0;
1975
+ }
1976
+ const [
1977
+ ,
1978
+ year,
1979
+ month,
1980
+ day,
1981
+ hours = "0",
1982
+ minutes = "0",
1983
+ seconds = "0",
1984
+ fraction = ""
1985
+ ] = match;
1986
+ if (Number(hours) > 23 || Number(minutes) > 59 || Number(seconds) > 59) {
1987
+ return void 0;
1988
+ }
1989
+ const date = new Date(
1990
+ Number(year),
1991
+ Number(month) - 1,
1992
+ Number(day),
1993
+ Number(hours),
1994
+ Number(minutes),
1995
+ Number(seconds),
1996
+ Number(fraction.padEnd(3, "0"))
1997
+ );
1998
+ return date.getFullYear() === Number(year) && date.getMonth() === Number(month) - 1 && date.getDate() === Number(day) ? date : void 0;
1999
+ }
2000
+ function parseBoolean(text) {
2001
+ if (text === "true") {
2002
+ return true;
2003
+ }
2004
+ return text === "false" ? false : void 0;
2005
+ }
2006
+ function parseFilterOperand(text, type) {
2007
+ if (text === "") {
2008
+ return void 0;
2009
+ }
2010
+ switch (filterOperatorFamily(type)) {
2011
+ case "text":
2012
+ return text;
2013
+ case "number":
2014
+ return parseNumber(text.trim());
2015
+ case "date":
2016
+ return parseDate(text.trim());
2017
+ case "boolean":
2018
+ return parseBoolean(text.trim());
2019
+ }
2020
+ }
2021
+ function pad(value, width = 2) {
2022
+ return String(value).padStart(width, "0");
2023
+ }
2024
+ function dayInput(date) {
2025
+ return `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
2026
+ }
2027
+ function momentInput(date) {
2028
+ const minute = `${dayInput(date)}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
2029
+ const seconds = date.getSeconds();
2030
+ const milliseconds = date.getMilliseconds();
2031
+ if (seconds === 0 && milliseconds === 0) {
2032
+ return minute;
2033
+ }
2034
+ const second = `${minute}:${pad(seconds)}`;
2035
+ return milliseconds === 0 ? second : `${second}.${pad(milliseconds, 3)}`;
2036
+ }
2037
+ function formatFilterOperand(value, type) {
2038
+ if (value === null || value === void 0) {
2039
+ return "";
2040
+ }
2041
+ const date = filterOperatorFamily(type) === "date" ? toDate(value) : void 0;
2042
+ if (date === void 0) {
2043
+ return String(value);
2044
+ }
2045
+ return type === "date" ? dayInput(date) : momentInput(date);
2046
+ }
2047
+
2048
+ // src/filterMenu/options.ts
2049
+ var DEFAULT_FILTER_VALUE_LIMIT = 1e4;
2050
+ function conditionOperators(operators) {
2051
+ return operators.includes("in") ? operators.filter((operator) => operator !== "in") : operators;
2052
+ }
2053
+ function resolveColumnFilterMenu(options, column) {
2054
+ if (!(column.filterable ?? options.filterableColumns ?? false)) {
2055
+ return null;
2056
+ }
2057
+ const grid = options.filterMenu;
2058
+ const own = column.filterMenu;
2059
+ return {
2060
+ ui: own?.ui ?? grid?.ui ?? "simple",
2061
+ operators: conditionOperators(
2062
+ own?.operators ?? defaultFilterOperators(column.type)
2063
+ ),
2064
+ family: filterOperatorFamily(column.type),
2065
+ showCounts: grid?.showCounts ?? false,
2066
+ valueLimit: grid?.valueLimit ?? DEFAULT_FILTER_VALUE_LIMIT
2067
+ };
2068
+ }
2069
+
2070
+ // src/messages.ts
2071
+ function localeKey2(locale) {
2072
+ return typeof locale === "string" ? locale : locale?.join(",") ?? "";
2073
+ }
2074
+ var countFormats = /* @__PURE__ */ new Map();
2075
+ function countFormat(locale) {
2076
+ const key = localeKey2(locale);
2077
+ let format = countFormats.get(key);
2078
+ if (format === void 0) {
2079
+ const numberFormat = new Intl.NumberFormat(locale, {
2080
+ maximumFractionDigits: 0
2081
+ });
2082
+ format = (count) => numberFormat.format(count);
2083
+ countFormats.set(key, format);
2084
+ }
2085
+ return format;
2086
+ }
2087
+ function columnCount(n, count, change) {
2088
+ return count === 1 ? `1 column ${change}` : `${n(count)} columns ${change}`;
2089
+ }
2090
+ function searchResults(n, count) {
2091
+ if (count === 0) {
2092
+ return "No rows found";
2093
+ }
2094
+ return count === 1 ? "1 row found" : `${n(count)} rows found`;
2095
+ }
2096
+ function selectedCount(n, count, target) {
2097
+ const noun = target === "rows" ? "row" : "column";
2098
+ if (count === 0) {
2099
+ return `No ${noun}s selected`;
2100
+ }
2101
+ return count === 1 ? `1 ${noun} selected` : `${n(count)} ${noun}s selected`;
2102
+ }
2103
+ var operatorLabels = {
2104
+ eq: "Equals",
2105
+ ne: "Does not equal",
2106
+ contains: "Contains",
2107
+ notContains: "Does not contain",
2108
+ startsWith: "Starts with",
2109
+ endsWith: "Ends with",
2110
+ gt: "Greater than",
2111
+ gte: "Greater than or equal to",
2112
+ lt: "Less than",
2113
+ lte: "Less than or equal to",
2114
+ between: "Between",
2115
+ in: "Is one of",
2116
+ isEmpty: "Is blank",
2117
+ isNotEmpty: "Is not blank"
2118
+ };
2119
+ var dateOperatorLabels = {
2120
+ lt: "Before",
2121
+ lte: "On or before",
2122
+ gt: "After",
2123
+ gte: "On or after"
2124
+ };
2125
+ function filterOperatorLabel(operator, family) {
2126
+ return (family === "date" ? dateOperatorLabels[operator] : void 0) ?? operatorLabels[operator];
2127
+ }
2128
+ function filterSearchFirst(n, total) {
2129
+ return total === 1 ? "Type to search 1 value" : `Type to search ${n(total)} values`;
2130
+ }
2131
+ function filterResults(n, shown, total) {
2132
+ return `${n(shown)} of ${n(total)} ${total === 1 ? "row" : "rows"}`;
2133
+ }
2134
+ var filterValueRequests = {
2135
+ text: "Enter a value",
2136
+ number: "Enter a number",
2137
+ date: "Enter a date",
2138
+ boolean: "Choose a value"
2139
+ };
2140
+ var filterOperatorMenus = {
2141
+ text: "Text filters",
2142
+ number: "Number filters",
2143
+ date: "Date filters",
2144
+ boolean: "Boolean filters"
2145
+ };
2146
+ function copied(n, count, unit) {
2147
+ return count === 1 ? `1 ${unit.slice(0, -1)} copied` : `${n(count)} ${unit} copied`;
2148
+ }
2149
+ function createDefaultMessages(locale) {
2150
+ const n = countFormat(locale);
2151
+ return {
2152
+ pagerLabel: "Pagination",
2153
+ firstPage: "First",
2154
+ previousPage: "Previous",
2155
+ nextPage: "Next",
2156
+ lastPage: "Last",
2157
+ pageSizeLabel: "Rows per page",
2158
+ pageButtonLabel: (page) => `Page ${n(page)}`,
2159
+ pageStatus: (page, pageCount) => `Page ${n(page)} of ${n(pageCount)}`,
2160
+ loadingMore: "Loading more\u2026",
2161
+ booleanTrue: "true",
2162
+ booleanFalse: "false",
2163
+ blankGroupValue: "(blank)",
2164
+ groupByBarLabel: "Grouped by",
2165
+ groupByBarPlaceholder: "Drag a column here to group by it",
2166
+ groupByChipLabel: (columnName2, level, levelCount) => levelCount > 1 ? `${columnName2}, level ${n(level)} of ${n(levelCount)}` : columnName2,
2167
+ removeGroupBy: (columnName2) => `Stop grouping by ${columnName2}`,
2168
+ columnResized: (columnName2, width) => `${columnName2}, ${n(width)} pixels wide`,
2169
+ columnMoved: (columnName2, position, columnCount2) => `${columnName2}, column ${n(position)} of ${n(columnCount2)}`,
2170
+ columnSorted: (columnName2, direction, key, keyCount) => {
2171
+ const sorted = `${columnName2} sorted ${direction === "asc" ? "ascending" : "descending"}`;
2172
+ return keyCount > 1 ? `${sorted}, key ${n(key)} of ${n(keyCount)}` : sorted;
2173
+ },
2174
+ sortCleared: (columnName2) => `${columnName2}, sort cleared`,
2175
+ groupedBy: (columnName2, level, levelCount) => levelCount > 1 ? `Grouped by ${columnName2}, level ${n(level)} of ${n(levelCount)}` : `Grouped by ${columnName2}`,
2176
+ groupingRemoved: (columnName2) => `${columnName2}, grouping removed`,
2177
+ groupExpanded: "Group expanded",
2178
+ groupCollapsed: "Group collapsed",
2179
+ allGroupsExpanded: "All groups expanded",
2180
+ allGroupsCollapsed: "All groups collapsed",
2181
+ selectedCount: (count, target) => selectedCount(n, count, target),
2182
+ cellSelected: (columnName2, rowNumber) => `${columnName2}, row ${n(rowNumber)}, selected`,
2183
+ columnHidden: (columnName2) => `${columnName2}, column hidden`,
2184
+ columnShown: (columnName2) => `${columnName2}, column shown`,
2185
+ columnsHidden: (count) => columnCount(n, count, "hidden"),
2186
+ columnsShown: (count) => columnCount(n, count, "shown"),
2187
+ columnsAutoFitted: (count) => columnCount(n, count, "autofitted"),
2188
+ headerMenuLabel: (columnName2) => `${columnName2} column menu`,
2189
+ cellMenuLabel: "Row menu",
2190
+ groupMenuLabel: "Group menu",
2191
+ bodyMenuLabel: "Grid menu",
2192
+ sortAscending: "Sort ascending",
2193
+ sortDescending: "Sort descending",
2194
+ clearSort: "Clear sort",
2195
+ clearAllSorting: "Clear all sorting",
2196
+ groupByColumn: (columnName2) => `Group by ${columnName2}`,
2197
+ ungroupAll: "Ungroup all",
2198
+ expandAllGroups: "Expand all groups",
2199
+ collapseAllGroups: "Collapse all groups",
2200
+ hideColumn: "Hide column",
2201
+ autoFitColumn: "Autofit column",
2202
+ autoFitAllColumns: "Autofit all columns",
2203
+ selectAllRows: "Select all rows",
2204
+ clearSelection: "Clear selection",
2205
+ clearFilters: "Clear filters",
2206
+ chooseColumns: "Choose columns",
2207
+ toolbarLabel: "Grid toolbar",
2208
+ searchLabel: "Search",
2209
+ searchPlaceholder: "Search\u2026",
2210
+ moreToolbarItems: "More",
2211
+ searchResults: (count) => searchResults(n, count),
2212
+ columnChooserLabel: "Columns",
2213
+ columnChooserSearchLabel: "Search columns",
2214
+ showAllColumns: "Show all",
2215
+ noMatchingColumns: "No matching columns",
2216
+ filterOperatorLabel,
2217
+ filterBlanks: "(Blanks)",
2218
+ filterSearchFirst: (total) => filterSearchFirst(n, total),
2219
+ filterMoreValues: (count) => `${n(count)} more, refine the search`,
2220
+ openFilter: "Filter\u2026",
2221
+ clearColumnFilter: "Clear filter",
2222
+ filterMenuLabel: (columnName2) => `${columnName2} filter`,
2223
+ columnFiltered: "Filtered",
2224
+ applyFilter: "OK",
2225
+ cancelFilter: "Cancel",
2226
+ customFilter: "Custom filter",
2227
+ filterResults: (shown, total) => filterResults(n, shown, total),
2228
+ filterConditionLabel: (position) => `Condition ${n(position)}`,
2229
+ filterOperatorFieldLabel: "Operator",
2230
+ filterValueLabel: "Value",
2231
+ filterFromLabel: "From",
2232
+ filterToLabel: "To",
2233
+ filterCombinatorLabel: "Combine conditions",
2234
+ filterAnd: "And",
2235
+ filterOr: "Or",
2236
+ filterValueInvalid: (family) => filterValueRequests[family],
2237
+ filterSearchLabel: "Search values",
2238
+ filterSelectAll: "Select all",
2239
+ filterValuesLabel: "Values",
2240
+ filterByCondition: "Filtered by condition",
2241
+ filterOperatorMenu: (family) => filterOperatorMenus[family],
2242
+ filterBackToValues: "Back to values",
2243
+ exportMenu: "Export",
2244
+ exportCsv: "Export to CSV",
2245
+ exportJson: "Export to JSON",
2246
+ exportXlsx: "Export to Excel",
2247
+ exportPdf: "Export to PDF",
2248
+ exportSelectionCsv: "Export selection to CSV",
2249
+ exportSelectionJson: "Export selection to JSON",
2250
+ exportSelectionXlsx: "Export selection to Excel",
2251
+ exportFailed: "Export failed",
2252
+ copyCell: "Copy cell",
2253
+ copyRow: "Copy row",
2254
+ copySelection: "Copy selection",
2255
+ copied: (count, unit) => copied(n, count, unit),
2256
+ copyFailed: "Copy failed",
2257
+ print: "Print",
2258
+ printFailed: "Print failed"
2259
+ };
2260
+ }
2261
+ var defaultMessages = createDefaultMessages();
2262
+ var localeDefaults = /* @__PURE__ */ new Map();
2263
+ function defaultsFor(locale) {
2264
+ if (locale === void 0) {
2265
+ return defaultMessages;
2266
+ }
2267
+ const key = localeKey2(locale);
2268
+ let defaults = localeDefaults.get(key);
2269
+ if (defaults === void 0) {
2270
+ defaults = createDefaultMessages(locale);
2271
+ localeDefaults.set(key, defaults);
2272
+ }
2273
+ return defaults;
2274
+ }
2275
+ function resolveMessages(messages, locale) {
2276
+ const defaults = defaultsFor(locale);
2277
+ return messages === void 0 ? defaults : { ...defaults, ...messages };
2278
+ }
2279
+
2280
+ // src/util/filterEditor.ts
2281
+ function touchesColumn(entry, columnId) {
2282
+ return entry.kind === "group" ? entry.entries.some((nested) => touchesColumn(nested, columnId)) : entry.columnId === columnId;
2283
+ }
2284
+ function isOperatorOn(entry, columnId) {
2285
+ return entry.kind === "operator" && entry.columnId === columnId;
2286
+ }
2287
+ function isConditionOn(entry, columnId) {
2288
+ return isOperatorOn(entry, columnId) && entry.operator !== "in";
2289
+ }
2290
+ function valuesShape(entry, columnId) {
2291
+ const values = (candidate) => candidate !== void 0 && isOperatorOn(candidate, columnId) && candidate.operator === "in" && isScalarList(candidate.value) ? candidate.value : void 0;
2292
+ const blanks = (candidate) => candidate !== void 0 && isOperatorOn(candidate, columnId) && candidate.operator === "isEmpty";
2293
+ const alone = values(entry);
2294
+ if (alone !== void 0) {
2295
+ return { kind: "values", values: alone, includeBlanks: false };
2296
+ }
2297
+ if (entry.kind !== "group" || entry.combinator !== "or" || entry.entries.length !== 2) {
2298
+ return void 0;
2299
+ }
2300
+ const [first, second] = entry.entries;
2301
+ const listed = blanks(first) ? values(second) : values(first);
2302
+ return listed !== void 0 && (blanks(first) || blanks(second)) ? { kind: "values", values: listed, includeBlanks: true } : void 0;
2303
+ }
2304
+ function conditionsShape(touching, columnId) {
2305
+ const [only] = touching;
2306
+ const grouped = touching.length === 1 && only !== void 0 && only.kind === "group";
2307
+ const entries = grouped ? only.entries : touching;
2308
+ const combinator = grouped ? only.combinator : "and";
2309
+ if (entries.length === 0 || entries.length > 2) {
2310
+ return void 0;
2311
+ }
2312
+ const conditions = entries.filter((entry) => isConditionOn(entry, columnId));
2313
+ return conditions.length === entries.length ? { kind: "conditions", conditions, combinator } : void 0;
2314
+ }
2315
+ function describeColumnFilter(filter, columnId) {
2316
+ const touching = filter.filter((entry) => touchesColumn(entry, columnId));
2317
+ const [only] = touching;
2318
+ if (only === void 0) {
2319
+ return { kind: "none" };
2320
+ }
2321
+ return (touching.length === 1 ? valuesShape(only, columnId) : void 0) ?? conditionsShape(touching, columnId) ?? { kind: "custom" };
2322
+ }
2323
+ function isColumnFiltered(filter, columnId) {
2324
+ return filter.some((entry) => touchesColumn(entry, columnId));
2325
+ }
2326
+ function isOfferable(value) {
2327
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value instanceof Date;
2328
+ }
2329
+ function matchesSearch(label, search) {
2330
+ return label.toLowerCase().includes(search.toLowerCase());
2331
+ }
2332
+ function columnValueOptions(rows, dataColumns, filter, columnId, query = {}) {
2333
+ const column = dataColumns.find((entry) => entry.id === columnId)?.column;
2334
+ if (column === void 0) {
2335
+ return { options: [], total: 0, truncated: false, blanks: 0 };
2336
+ }
2337
+ const keep = compileFilter(
2338
+ filter.filter((entry) => !touchesColumn(entry, columnId)),
2339
+ dataColumns
2340
+ );
2341
+ const buckets = /* @__PURE__ */ new Map();
2342
+ let blanks = 0;
2343
+ for (const row of rows) {
2344
+ if (keep !== void 0 && !keep(row)) {
2345
+ continue;
2346
+ }
2347
+ const value = accessDotted(row, column.field);
2348
+ if (isEmptyCell(value)) {
2349
+ blanks++;
2350
+ } else if (isOfferable(value)) {
2351
+ const key = filterValueKey(value, column.type);
2352
+ const bucket = buckets.get(key);
2353
+ if (bucket === void 0) {
2354
+ buckets.set(key, { value, row, count: 1 });
2355
+ } else {
2356
+ bucket.count++;
2357
+ }
2358
+ }
2359
+ }
2360
+ const { search = "", limit, locale } = query;
2361
+ const messages = resolveMessages(query.messages, locale);
2362
+ const options = [...buckets.values()].sort((a, b) => compareValues(a.value, b.value, column.type)).map(({ value, row, count }) => ({
2363
+ value,
2364
+ label: formatCellValue(value, column, locale, row, messages),
2365
+ count
2366
+ })).filter((option) => matchesSearch(option.label, search));
2367
+ const shown = limit === void 0 ? options : options.slice(0, limit);
2368
+ return {
2369
+ options: shown,
2370
+ total: options.length,
2371
+ truncated: shown.length < options.length,
2372
+ blanks,
2373
+ columnType: column.type
2374
+ };
2375
+ }
2376
+ function keyOf2(draft, value) {
2377
+ return filterValueKey(value, draft.columnType);
2378
+ }
2379
+ function everyOption(draft) {
2380
+ return new Map(
2381
+ draft.options.map((option) => [keyOf2(draft, option.value), option.value])
2382
+ );
2383
+ }
2384
+ function baseOf(draft) {
2385
+ const { options, blanks, search, openedShape, columnType } = draft;
2386
+ return { options, blanks, search, openedShape, columnType };
2387
+ }
2388
+ function openedValues(base) {
2389
+ const shape = base.openedShape;
2390
+ if (shape.kind !== "values") {
2391
+ return {
2392
+ kind: "values",
2393
+ ...base,
2394
+ checked: everyOption(base),
2395
+ includeBlanks: base.blanks > 0
2396
+ };
2397
+ }
2398
+ return {
2399
+ kind: "values",
2400
+ ...base,
2401
+ checked: new Map(
2402
+ shape.values.filter((value) => !isEmptyCell(value)).map((value) => [keyOf2(base, value), value])
2403
+ ),
2404
+ includeBlanks: shape.includeBlanks
2405
+ };
2406
+ }
2407
+ function openedConditions(base) {
2408
+ const shape = base.openedShape;
2409
+ return shape.kind === "conditions" ? {
2410
+ kind: "conditions",
2411
+ ...base,
2412
+ conditions: shape.conditions,
2413
+ combinator: shape.combinator
2414
+ } : { kind: "conditions", ...base, conditions: [], combinator: "and" };
2415
+ }
2416
+ function initialFilterEditorDraft(shape, values) {
2417
+ const base = {
2418
+ options: values.options,
2419
+ blanks: values.blanks,
2420
+ search: "",
2421
+ openedShape: shape,
2422
+ columnType: values.columnType
2423
+ };
2424
+ return shape.kind === "conditions" ? openedConditions(base) : openedValues(base);
2425
+ }
2426
+ function toValuesDraft(draft) {
2427
+ return draft.kind === "values" ? draft : openedValues(baseOf(draft));
2428
+ }
2429
+ function toConditionsDraft(draft) {
2430
+ return draft.kind === "conditions" ? draft : openedConditions(baseOf(draft));
2431
+ }
2432
+ function visibleFilterOptions(draft) {
2433
+ return draft.search === "" ? draft.options : draft.options.filter(
2434
+ (option) => matchesSearch(option.label, draft.search)
2435
+ );
2436
+ }
2437
+ function selectAllCoversBlanks(draft) {
2438
+ return draft.search === "" && draft.blanks > 0;
2439
+ }
2440
+ function selectAllState(draft) {
2441
+ const states = visibleFilterOptions(draft).map(
2442
+ (option) => draft.checked.has(keyOf2(draft, option.value))
2443
+ );
2444
+ if (selectAllCoversBlanks(draft)) {
2445
+ states.push(draft.includeBlanks);
2446
+ }
2447
+ if (states.length > 0 && states.every(Boolean)) {
2448
+ return "checked";
2449
+ }
2450
+ return states.some(Boolean) ? "mixed" : "unchecked";
2451
+ }
2452
+ function toggleValue(draft, value) {
2453
+ const key = keyOf2(draft, value);
2454
+ const checked = new Map(draft.checked);
2455
+ if (checked.has(key)) {
2456
+ checked.delete(key);
2457
+ } else {
2458
+ checked.set(key, value);
2459
+ }
2460
+ return { ...draft, checked };
2461
+ }
2462
+ function toggleAll(draft) {
2463
+ const check = selectAllState(draft) !== "checked";
2464
+ const checked = new Map(draft.checked);
2465
+ for (const option of visibleFilterOptions(draft)) {
2466
+ const key = keyOf2(draft, option.value);
2467
+ if (check) {
2468
+ checked.set(key, option.value);
2469
+ } else {
2470
+ checked.delete(key);
2471
+ }
2472
+ }
2473
+ return {
2474
+ ...draft,
2475
+ checked,
2476
+ includeBlanks: selectAllCoversBlanks(draft) ? check : draft.includeBlanks
2477
+ };
2478
+ }
2479
+ function cleared(draft) {
2480
+ switch (draft.kind) {
2481
+ case "values":
2482
+ return {
2483
+ ...draft,
2484
+ search: "",
2485
+ checked: everyOption(draft),
2486
+ includeBlanks: draft.blanks > 0
2487
+ };
2488
+ case "conditions":
2489
+ return { ...draft, search: "", conditions: [] };
2490
+ }
2491
+ }
2492
+ function filterEditorReducer(draft, action) {
2493
+ switch (action.type) {
2494
+ case "search":
2495
+ return { ...draft, search: action.search };
2496
+ case "toggleValue":
2497
+ return toggleValue(toValuesDraft(draft), action.value);
2498
+ case "toggleAll":
2499
+ return toggleAll(toValuesDraft(draft));
2500
+ case "setIncludeBlanks":
2501
+ return { ...toValuesDraft(draft), includeBlanks: action.includeBlanks };
2502
+ case "setConditions": {
2503
+ const conditions = toConditionsDraft(draft);
2504
+ return {
2505
+ ...conditions,
2506
+ conditions: action.conditions,
2507
+ combinator: action.combinator ?? conditions.combinator
2508
+ };
2509
+ }
2510
+ case "clear":
2511
+ return cleared(draft);
2512
+ }
2513
+ }
2514
+ function checksEverything(draft) {
2515
+ return draft.options.every(
2516
+ (option) => draft.checked.has(keyOf2(draft, option.value))
2517
+ ) && (draft.includeBlanks || draft.blanks === 0);
2518
+ }
2519
+ function valuesEntries(draft, columnId) {
2520
+ if (checksEverything(draft)) {
2521
+ return [];
2522
+ }
2523
+ const picked = {
2524
+ kind: "operator",
2525
+ columnId,
2526
+ operator: "in",
2527
+ value: [...draft.checked.values()]
2528
+ };
2529
+ return draft.includeBlanks ? [
2530
+ {
2531
+ kind: "group",
2532
+ combinator: "or",
2533
+ entries: [
2534
+ picked,
2535
+ { kind: "operator", columnId, operator: "isEmpty" }
2536
+ ]
2537
+ }
2538
+ ] : [picked];
2539
+ }
2540
+ function conditionsEntries(draft, columnId) {
2541
+ const conditions = draft.conditions.map((condition) => ({
2542
+ ...condition,
2543
+ columnId
2544
+ }));
2545
+ return conditions.length > 1 ? [{ kind: "group", combinator: draft.combinator, entries: conditions }] : conditions;
2546
+ }
2547
+ function draftEntries(draft, columnId) {
2548
+ switch (draft.kind) {
2549
+ case "values":
2550
+ return valuesEntries(draft, columnId);
2551
+ case "conditions":
2552
+ return conditionsEntries(draft, columnId);
2553
+ }
2554
+ }
2555
+ function draftToFilter(draft, columnId, current) {
2556
+ const replacement = draftEntries(draft, columnId);
2557
+ const first = current.findIndex((entry) => touchesColumn(entry, columnId));
2558
+ if (first === -1) {
2559
+ return replacement.length === 0 ? current : [...current, ...replacement];
2560
+ }
2561
+ const kept = current.filter((entry) => !touchesColumn(entry, columnId));
2562
+ return [...kept.slice(0, first), ...replacement, ...kept.slice(first)];
2563
+ }
2564
+ function sameValues(a, b) {
2565
+ return a.includeBlanks === b.includeBlanks && a.checked.size === b.checked.size && [...a.checked.keys()].every((key) => b.checked.has(key));
2566
+ }
2567
+ function sameOperand(a, b, type) {
2568
+ if (isScalarList(a) || isScalarList(b)) {
2569
+ return isScalarList(a) && isScalarList(b) && a.length === b.length && a.every((scalar, index) => sameOperand(scalar, b[index], type));
2570
+ }
2571
+ return filterValueKey(a, type) === filterValueKey(b, type);
2572
+ }
2573
+ function sameConditions(a, b) {
2574
+ return a.conditions.length === b.conditions.length && (a.conditions.length < 2 || a.combinator === b.combinator) && a.conditions.every((condition, index) => {
2575
+ const other = b.conditions[index];
2576
+ return other !== void 0 && condition.operator === other.operator && sameOperand(condition.value, other.value, a.columnType);
2577
+ });
2578
+ }
2579
+ function filterDraftChanged(opened, draft) {
2580
+ switch (draft.kind) {
2581
+ case "values":
2582
+ return !sameValues(toValuesDraft(opened), draft);
2583
+ case "conditions":
2584
+ return opened.kind !== "conditions" || !sameConditions(opened, draft);
2585
+ }
2586
+ }
2587
+
2588
+ // src/commands/builtInCommands.ts
2589
+ function isOn(context, areas) {
2590
+ return areas.includes(context.target.area);
2591
+ }
2592
+ function columnOn(context, areas) {
2593
+ return isOn(context, areas) ? context.column : null;
2594
+ }
2595
+ function isGroupedBy(context, columnId) {
2596
+ return context.state.groupBy.some((entry) => entry.columnId === columnId);
2597
+ }
2598
+ function sortableColumn(context) {
2599
+ const column = columnOn(context, ["header"]);
2600
+ return column !== null && (column.column.sortable ?? context.options.sortableColumns ?? false) ? column : null;
2601
+ }
2602
+ function groupableColumn(context) {
2603
+ const column = columnOn(context, ["header"]);
2604
+ return column !== null && (column.column.groupable ?? context.options.groupableColumns ?? false) && !isGroupedBy(context, column.id) ? column : null;
2605
+ }
2606
+ function groupedColumn(context) {
2607
+ const column = columnOn(context, ["header", "group"]);
2608
+ return column !== null && isGroupedBy(context, column.id) ? column : null;
2609
+ }
2610
+ function filterableColumn(context) {
2611
+ const column = columnOn(context, ["header"]);
2612
+ return column !== null && resolveColumnFilterMenu(context.options, column.column) !== null ? column : null;
2613
+ }
2614
+ function hideableColumn(context) {
2615
+ const column = columnOn(context, ["header"]);
2616
+ return column !== null && column.column.hideable !== false ? column : null;
2617
+ }
2618
+ function resizableColumn(context) {
2619
+ const column = columnOn(context, ["header"]);
2620
+ if (column === null) {
2621
+ return null;
2622
+ }
2623
+ return context.view.columns.find(
2624
+ (entry) => entry.id === column.id && entry.resizable
2625
+ ) ?? null;
2626
+ }
2627
+ function resizableColumnIds(context) {
2628
+ return context.view.columns.filter((entry) => entry.resizable).map((entry) => entry.id);
2629
+ }
2630
+ function isAnythingSelectable(selectable) {
2631
+ return [selectable?.rows, selectable?.columns, selectable?.cells].some(
2632
+ (mode) => mode !== void 0 && mode !== false
2633
+ );
2634
+ }
2635
+ function columnName(context) {
2636
+ return context.column === null ? "" : resolveColumnHeaderText(context.column.column);
2637
+ }
2638
+ function columnCommand({
2639
+ id,
2640
+ label,
2641
+ icon,
2642
+ find,
2643
+ isEnabled,
2644
+ isChecked,
2645
+ execute
2646
+ }) {
2647
+ function test(predicate) {
2648
+ return (context) => {
2649
+ const column = find(context);
2650
+ return column !== null && predicate(column, context);
2651
+ };
2652
+ }
2653
+ return {
2654
+ id,
2655
+ label,
2656
+ icon,
2657
+ isVisible: (context) => find(context) !== null,
2658
+ isEnabled: isEnabled === void 0 ? void 0 : test(isEnabled),
2659
+ isChecked: isChecked === void 0 ? void 0 : test(isChecked),
2660
+ execute: (context) => {
2661
+ const column = find(context);
2662
+ if (column !== null) {
2663
+ execute(column, context);
2664
+ }
2665
+ }
2666
+ };
2667
+ }
2668
+ var EXPORT_AREAS = ["grid", "toolbar", "body", "cell"];
2669
+ function exportCommand({
2670
+ id,
2671
+ format,
2672
+ label,
2673
+ selection = false
2674
+ }) {
2675
+ return {
2676
+ id,
2677
+ label: ({ messages }) => label(messages),
2678
+ isVisible: (context) => isOn(context, EXPORT_AREAS) && resolveExportWriters(context.options.exportWriters).has(format) && (!selection || context.state.rowSelection.length > 0),
2679
+ isEnabled: (context) => (selection ? context.selectedRows() : context.view.rows).length > 0,
2680
+ execute: (context) => {
2681
+ if (context.host.canSave?.() === false) {
2682
+ return false;
2683
+ }
2684
+ const { export: defaults = {}, exportWriters } = context.options;
2685
+ const file = exportFile(
2686
+ context,
2687
+ format,
2688
+ selection ? { ...defaults, scope: "selection" } : defaults,
2689
+ resolveExportWriters(exportWriters)
2690
+ );
2691
+ if (file === null) {
2692
+ return;
2693
+ }
2694
+ return context.host.saveFile(file) !== false;
2695
+ }
2696
+ };
2697
+ }
2698
+ function cellRequest(context, kind) {
2699
+ const { target } = context;
2700
+ if (target.area !== "cell") {
2701
+ return null;
2702
+ }
2703
+ return kind === "cell" ? { kind, rowId: target.rowId, columnId: target.columnId } : { kind, rowId: target.rowId };
2704
+ }
2705
+ function copyCommand({
2706
+ id,
2707
+ label,
2708
+ request,
2709
+ isEnabled
2710
+ }) {
2711
+ function contentFor(context) {
2712
+ const asked = request(context);
2713
+ return asked === null ? null : copyContent(context, asked);
2714
+ }
2715
+ return {
2716
+ id,
2717
+ label: ({ messages }) => label(messages),
2718
+ icon: "copy",
2719
+ isVisible: (context) => request(context) !== null,
2720
+ isEnabled: isEnabled ?? ((context) => contentFor(context) !== null),
2721
+ execute: (context) => {
2722
+ const content = contentFor(context);
2723
+ if (content !== null) {
2724
+ context.host.writeClipboard(content);
2725
+ }
2726
+ }
2727
+ };
2728
+ }
2729
+ function sortCommand(direction) {
2730
+ return columnCommand({
2731
+ id: direction === "asc" ? "sort.ascending" : "sort.descending",
2732
+ label: ({ messages }) => direction === "asc" ? messages.sortAscending : messages.sortDescending,
2733
+ icon: direction === "asc" ? "sortAscending" : "sortDescending",
2734
+ find: sortableColumn,
2735
+ isChecked: (column, { state }) => sortDirectionFor(state.columnSort, column.id) === direction,
2736
+ execute: (column, { actions }) => {
2737
+ actions.setColumnSort([{ columnId: column.id, direction }]);
2738
+ }
2739
+ });
2740
+ }
2741
+ function builtInCommands() {
2742
+ return [
2743
+ sortCommand("asc"),
2744
+ sortCommand("desc"),
2745
+ // Cleared rather than set, so the change reports this column — the one
2746
+ // the announcement names — rather than a key that moved up past it.
2747
+ columnCommand({
2748
+ id: "sort.clear",
2749
+ label: ({ messages }) => messages.clearSort,
2750
+ find: sortableColumn,
2751
+ isEnabled: (column, { state }) => sortDirectionFor(state.columnSort, column.id) !== null,
2752
+ execute: (column, { actions }) => {
2753
+ actions.clearColumnSort(column.id);
2754
+ }
2755
+ }),
2756
+ {
2757
+ id: "sort.clearAll",
2758
+ label: ({ messages }) => messages.clearAllSorting,
2759
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "header"]),
2760
+ isEnabled: ({ state }) => state.columnSort.length > 0,
2761
+ execute: ({ actions }) => {
2762
+ actions.setColumnSort([]);
2763
+ }
2764
+ },
2765
+ columnCommand({
2766
+ id: "group.add",
2767
+ label: (context) => context.messages.groupByColumn(columnName(context)),
2768
+ icon: "group",
2769
+ find: groupableColumn,
2770
+ execute: (column, { actions }) => {
2771
+ actions.toggleGroupBy(column.id);
2772
+ }
2773
+ }),
2774
+ // Toggled rather than set, so the change reports this column — the one
2775
+ // the announcement names — rather than the level that moved up.
2776
+ columnCommand({
2777
+ id: "group.remove",
2778
+ label: (context) => context.messages.removeGroupBy(columnName(context)),
2779
+ icon: "group",
2780
+ find: groupedColumn,
2781
+ execute: (column, { actions }) => {
2782
+ actions.toggleGroupBy(column.id);
2783
+ }
2784
+ }),
2785
+ {
2786
+ id: "group.clearAll",
2787
+ label: ({ messages }) => messages.ungroupAll,
2788
+ isVisible: (context) => isOn(context, ["grid", "toolbar"]) && context.state.groupBy.length > 0,
2789
+ execute: ({ actions }) => {
2790
+ actions.setGroupBy([]);
2791
+ }
2792
+ },
2793
+ {
2794
+ id: "group.expandAll",
2795
+ label: ({ messages }) => messages.expandAllGroups,
2796
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "group", "cell"]) && context.state.groupBy.length > 0,
2797
+ execute: ({ actions }) => {
2798
+ actions.expandAllGroups();
2799
+ }
2800
+ },
2801
+ {
2802
+ id: "group.collapseAll",
2803
+ label: ({ messages }) => messages.collapseAllGroups,
2804
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "group", "cell"]) && context.state.groupBy.length > 0,
2805
+ execute: ({ actions }) => {
2806
+ actions.collapseAllGroups();
2807
+ }
2808
+ },
2809
+ columnCommand({
2810
+ id: "column.hide",
2811
+ label: ({ messages }) => messages.hideColumn,
2812
+ icon: "hide",
2813
+ find: hideableColumn,
2814
+ // The last column shown stays: a grid with none has no header left to
2815
+ // bring one back from.
2816
+ isEnabled: (column, { view }) => view.columns.some((entry) => entry.id !== column.id),
2817
+ execute: (column, { actions }) => {
2818
+ actions.hideColumns([column.id]);
2819
+ }
2820
+ }),
2821
+ columnCommand({
2822
+ id: "column.autoFit",
2823
+ label: ({ messages }) => messages.autoFitColumn,
2824
+ icon: "autoFit",
2825
+ find: resizableColumn,
2826
+ execute: (column, { host }) => {
2827
+ host.autoFitColumns([column.id]);
2828
+ }
2829
+ }),
2830
+ {
2831
+ id: "column.autoFitAll",
2832
+ label: ({ messages }) => messages.autoFitAllColumns,
2833
+ icon: "autoFit",
2834
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "header"]) && resizableColumnIds(context).length > 0,
2835
+ execute: (context) => {
2836
+ context.host.autoFitColumns(resizableColumnIds(context));
2837
+ }
2838
+ },
2839
+ // The target goes along, so the renderer opens the chooser where it was
2840
+ // asked for: beside the toolbar button, below the header, or at the
2841
+ // grid's corner for a call from nowhere in particular.
2842
+ {
2843
+ id: "column.choose",
2844
+ label: ({ messages }) => messages.chooseColumns,
2845
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "header"]),
2846
+ execute: ({ host, target }) => {
2847
+ host.openPanel("columnChooser", target);
2848
+ }
2849
+ },
2850
+ // Opened below the header it was asked for, as the chooser is.
2851
+ columnCommand({
2852
+ id: "filter.open",
2853
+ label: ({ messages }) => messages.openFilter,
2854
+ find: filterableColumn,
2855
+ execute: (_column, { host, target }) => {
2856
+ host.openPanel("filter", target);
2857
+ }
2858
+ }),
2859
+ // Every entry about the column goes, whichever editor wrote it — or
2860
+ // none did, as with a predicate set in code — as applying an editor
2861
+ // replaces them all.
2862
+ columnCommand({
2863
+ id: "filter.clear",
2864
+ label: ({ messages }) => messages.clearColumnFilter,
2865
+ find: filterableColumn,
2866
+ isEnabled: (column, { state }) => isColumnFiltered(state.filter, column.id),
2867
+ execute: (column, { actions, state }) => {
2868
+ actions.setFilter(
2869
+ state.filter.filter((entry) => !touchesColumn(entry, column.id))
2870
+ );
2871
+ }
2872
+ }),
2873
+ {
2874
+ id: "selection.selectAllRows",
2875
+ label: ({ messages }) => messages.selectAllRows,
2876
+ isVisible: (context) => isOn(context, ["grid", "cell"]) && context.options.selectable?.rows === "multiple",
2877
+ isEnabled: ({ view }) => view.displayDataRows.length > 0,
2878
+ execute: ({ actions }) => {
2879
+ actions.selectAllRows();
2880
+ }
2881
+ },
2882
+ {
2883
+ id: "selection.clear",
2884
+ label: ({ messages }) => messages.clearSelection,
2885
+ isVisible: (context) => isOn(context, ["grid", "cell", "header"]) && isAnythingSelectable(context.options.selectable),
2886
+ isEnabled: ({ state }) => state.rowSelection.length > 0 || state.columnSelection.length > 0 || state.cellSelection !== null,
2887
+ execute: ({ actions }) => {
2888
+ actions.clearSelection();
2889
+ }
2890
+ },
2891
+ {
2892
+ id: "filter.clearAll",
2893
+ label: ({ messages }) => messages.clearFilters,
2894
+ isVisible: (context) => isOn(context, ["grid", "toolbar", "header"]),
2895
+ isEnabled: ({ state }) => state.filter.length > 0,
2896
+ execute: ({ actions }) => {
2897
+ actions.setFilter([]);
2898
+ }
2899
+ },
2900
+ exportCommand({
2901
+ id: "export.csv",
2902
+ format: "csv",
2903
+ label: ({ exportCsv }) => exportCsv
2904
+ }),
2905
+ exportCommand({
2906
+ id: "export.json",
2907
+ format: "json",
2908
+ label: ({ exportJson }) => exportJson
2909
+ }),
2910
+ exportCommand({
2911
+ id: "export.xlsx",
2912
+ format: "xlsx",
2913
+ label: ({ exportXlsx }) => exportXlsx
2914
+ }),
2915
+ exportCommand({
2916
+ id: "export.pdf",
2917
+ format: "pdf",
2918
+ label: ({ exportPdf }) => exportPdf
2919
+ }),
2920
+ exportCommand({
2921
+ id: "exportSelection.csv",
2922
+ format: "csv",
2923
+ label: ({ exportSelectionCsv }) => exportSelectionCsv,
2924
+ selection: true
2925
+ }),
2926
+ exportCommand({
2927
+ id: "exportSelection.json",
2928
+ format: "json",
2929
+ label: ({ exportSelectionJson }) => exportSelectionJson,
2930
+ selection: true
2931
+ }),
2932
+ exportCommand({
2933
+ id: "exportSelection.xlsx",
2934
+ format: "xlsx",
2935
+ label: ({ exportSelectionXlsx }) => exportSelectionXlsx,
2936
+ selection: true
2937
+ }),
2938
+ copyCommand({
2939
+ id: "copy.cell",
2940
+ label: ({ copyCell }) => copyCell,
2941
+ request: (context) => cellRequest(context, "cell")
2942
+ }),
2943
+ copyCommand({
2944
+ id: "copy.row",
2945
+ label: ({ copyRow }) => copyRow,
2946
+ request: (context) => cellRequest(context, "row")
2947
+ }),
2948
+ // Shown wherever the grid as a whole is asked for, as the exports are,
2949
+ // once anything can be selected; enabled once something is.
2950
+ copyCommand({
2951
+ id: "copy.selection",
2952
+ label: ({ copySelection }) => copySelection,
2953
+ request: (context) => isOn(context, EXPORT_AREAS) && isAnythingSelectable(context.options.selectable) ? { kind: "selection" } : null,
2954
+ isEnabled: canCopySelection
2955
+ }),
2956
+ // Shown where the exports are, under the grid's `print` defaults. A grid
2957
+ // with no rows still prints its header; one with no columns, nothing.
2958
+ {
2959
+ id: "print",
2960
+ label: ({ messages }) => messages.print,
2961
+ icon: "print",
2962
+ isVisible: (context) => isOn(context, EXPORT_AREAS),
2963
+ isEnabled: ({ view }) => view.columns.length > 0,
2964
+ execute: (context) => {
2965
+ const { print: options = {} } = context.options;
2966
+ context.host.print(exportPrintDocument(context, options), options);
2967
+ }
2968
+ }
2969
+ ];
2970
+ }
2971
+
2972
+ // src/commands/registry.ts
2973
+ function isCommandVisible(command, context) {
2974
+ return command.isVisible?.(context) ?? true;
2975
+ }
2976
+ function isCommandEnabled(command, context) {
2977
+ return command.isEnabled?.(context) ?? true;
2978
+ }
2979
+ function resolveCommands(commands) {
2980
+ const registry = new Map(
2981
+ builtInCommands().map((command) => [command.id, command])
2982
+ );
2983
+ for (const command of commands ?? []) {
2984
+ if (command.id === "separator") {
2985
+ reportError(
2986
+ "a command cannot have the id `separator`, which a menu reads as a separator, so it is left out."
2987
+ );
2988
+ continue;
2989
+ }
2990
+ registry.set(command.id, command);
2991
+ }
2992
+ return registry;
2993
+ }
2994
+ function runCommand(command, context) {
2995
+ if (!isCommandVisible(command, context) || !isCommandEnabled(command, context)) {
2996
+ return false;
2997
+ }
2998
+ return command.execute(context) !== false;
2999
+ }
3000
+
3001
+ // src/menu/resolveMenu.ts
3002
+ var reportedUnknownIds = /* @__PURE__ */ new WeakMap();
3003
+ function reportUnknownId(commands, id) {
3004
+ let reported = reportedUnknownIds.get(commands);
3005
+ if (reported === void 0) {
3006
+ reported = /* @__PURE__ */ new Set();
3007
+ reportedUnknownIds.set(commands, reported);
3008
+ }
3009
+ if (reported.has(id)) {
3010
+ return;
3011
+ }
3012
+ reported.add(id);
3013
+ reportError(
3014
+ `the menu or toolbar entry \`${id}\` names no command, so it is left out.`
3015
+ );
3016
+ }
3017
+ function evaluate(value, context) {
3018
+ return typeof value === "function" ? value(context) : value;
3019
+ }
3020
+ function commandItem(command, context) {
3021
+ if (!isCommandVisible(command, context)) {
3022
+ return null;
3023
+ }
3024
+ return {
3025
+ type: "item",
3026
+ id: command.id,
3027
+ label: evaluate(command.label, context),
3028
+ icon: command.icon,
3029
+ shortcut: command.shortcut,
3030
+ disabled: !isCommandEnabled(command, context),
3031
+ checked: command.isChecked?.(context),
3032
+ run: () => runCommand(command, context)
3033
+ };
3034
+ }
3035
+ function inlineItem(entry, context) {
3036
+ if (evaluate(entry.hidden ?? false, context)) {
3037
+ return null;
3038
+ }
3039
+ const disabled = evaluate(entry.disabled ?? false, context);
3040
+ return {
3041
+ type: "item",
3042
+ id: entry.id,
3043
+ label: evaluate(entry.label, context),
3044
+ icon: entry.icon,
3045
+ shortcut: entry.shortcut,
3046
+ disabled,
3047
+ checked: entry.checked === void 0 ? void 0 : evaluate(entry.checked, context),
3048
+ run: () => {
3049
+ if (disabled) {
3050
+ return false;
3051
+ }
3052
+ entry.onSelect(context);
3053
+ return true;
3054
+ }
3055
+ };
3056
+ }
3057
+ function collapseSeparators(entries, isEdge = () => false) {
3058
+ const collapsed = [];
3059
+ for (const entry of entries) {
3060
+ const previous = collapsed.at(-1);
3061
+ if (entry.type !== "separator") {
3062
+ if (isEdge(entry) && previous?.type === "separator") {
3063
+ collapsed.pop();
3064
+ }
3065
+ collapsed.push(entry);
3066
+ } else if (previous !== void 0 && previous.type !== "separator" && !isEdge(previous)) {
3067
+ collapsed.push(entry);
3068
+ }
3069
+ }
3070
+ if (collapsed.at(-1)?.type === "separator") {
3071
+ collapsed.pop();
3072
+ }
3073
+ return collapsed;
3074
+ }
3075
+ function resolveMenuEntry(entry, index, options) {
3076
+ const { commands, context } = options;
3077
+ if (entry === "separator") {
3078
+ return { type: "separator", key: `separator-${String(index)}` };
3079
+ }
3080
+ if (typeof entry === "string") {
3081
+ const command = commands.get(entry);
3082
+ if (command === void 0) {
3083
+ reportUnknownId(commands, entry);
3084
+ return null;
3085
+ }
3086
+ return commandItem(command, context);
3087
+ }
3088
+ return entry.type === "item" ? inlineItem(entry, context) : resolveSubmenu(entry, options);
3089
+ }
3090
+ function resolveSubmenu(entry, options) {
3091
+ const items = resolveMenu(entry.items, options);
3092
+ return items.length === 0 ? null : {
3093
+ type: "submenu",
3094
+ id: entry.id,
3095
+ label: evaluate(entry.label, options.context),
3096
+ icon: entry.icon,
3097
+ items
3098
+ };
3099
+ }
3100
+ function resolveMenu(entries, options) {
3101
+ return collapseSeparators(
3102
+ entries.map((entry, index) => resolveMenuEntry(entry, index, options)).filter((entry) => entry !== null)
3103
+ );
3104
+ }
3105
+
3106
+ // src/menu/contextMenu.ts
3107
+ var defaultContextMenu = {
3108
+ header: [
3109
+ "sort.ascending",
3110
+ "sort.descending",
3111
+ "sort.clear",
3112
+ "separator",
3113
+ "filter.open",
3114
+ "filter.clear",
3115
+ "separator",
3116
+ "group.add",
3117
+ "group.remove",
3118
+ "separator",
3119
+ "column.autoFit",
3120
+ "column.autoFitAll",
3121
+ "separator",
3122
+ "column.hide",
3123
+ "column.choose"
3124
+ ],
3125
+ cell: [
3126
+ "copy.cell",
3127
+ "copy.row",
3128
+ "copy.selection",
3129
+ "separator",
3130
+ "selection.selectAllRows",
3131
+ "selection.clear",
3132
+ "separator",
3133
+ "group.expandAll",
3134
+ "group.collapseAll"
3135
+ ],
3136
+ group: ["group.expandAll", "group.collapseAll", "separator", "group.remove"],
3137
+ body: []
3138
+ };
3139
+ function hasContextMenu(contextMenu, area) {
3140
+ if (contextMenu === void 0 || contextMenu === false) {
3141
+ return false;
3142
+ }
3143
+ const entries = (contextMenu === true ? void 0 : contextMenu[area]) ?? defaultContextMenu[area];
3144
+ return typeof entries === "function" || entries.length > 0;
3145
+ }
3146
+ function entriesFor(given, request) {
3147
+ if (given === void 0) {
3148
+ return request.defaults;
3149
+ }
3150
+ return typeof given === "function" ? given(request) ?? [] : given;
3151
+ }
3152
+ function contextMenuEntries(contextMenu, context) {
3153
+ if (contextMenu === void 0 || contextMenu === false) {
3154
+ return [];
3155
+ }
3156
+ const options = contextMenu === true ? {} : contextMenu;
3157
+ const { target } = context;
3158
+ switch (target.area) {
3159
+ case "header":
3160
+ return entriesFor(options.header, {
3161
+ target,
3162
+ defaults: defaultContextMenu.header,
3163
+ context
3164
+ });
3165
+ case "cell":
3166
+ return entriesFor(options.cell, {
3167
+ target,
3168
+ defaults: defaultContextMenu.cell,
3169
+ context
3170
+ });
3171
+ case "group":
3172
+ return entriesFor(options.group, {
3173
+ target,
3174
+ defaults: defaultContextMenu.group,
3175
+ context
3176
+ });
3177
+ case "body":
3178
+ return entriesFor(options.body, {
3179
+ target,
3180
+ defaults: defaultContextMenu.body,
3181
+ context
3182
+ });
3183
+ default:
3184
+ return [];
3185
+ }
3186
+ }
3187
+
3188
+ // src/util/navigation.ts
3189
+ function headerFocus(columnIndex) {
3190
+ return { area: "header", columnIndex };
3191
+ }
3192
+ function bodyFocus(rowIndex, columnIndex) {
3193
+ return { area: "body", rowIndex, columnIndex };
3194
+ }
3195
+ function clampFocus(focus, rowCount, columnCount2) {
3196
+ const columnIndex = Math.min(
3197
+ Math.max(focus.columnIndex, 0),
3198
+ Math.max(columnCount2 - 1, 0)
3199
+ );
3200
+ switch (focus.area) {
3201
+ case "header":
3202
+ return headerFocus(columnIndex);
3203
+ case "body": {
3204
+ const rowIndex = Math.min(focus.rowIndex, rowCount - 1);
3205
+ return rowIndex < 0 ? headerFocus(columnIndex) : bodyFocus(rowIndex, columnIndex);
3206
+ }
3207
+ }
3208
+ }
3209
+ function noRowsSkippable() {
3210
+ return false;
3211
+ }
3212
+ function linePosition(focus) {
3213
+ return focus.area === "header" ? -1 : focus.rowIndex;
3214
+ }
3215
+ function focusAtLine(line2, columnIndex) {
3216
+ return line2 < 0 ? headerFocus(columnIndex) : bodyFocus(line2, columnIndex);
3217
+ }
3218
+ function skipSkippableRows(target, direction, rowCount, isSkippableRow, fallback) {
3219
+ if (target.area === "header") {
3220
+ return target;
3221
+ }
3222
+ let rowIndex = target.rowIndex;
3223
+ while (rowIndex < rowCount && isSkippableRow(rowIndex)) {
3224
+ const stepped = rowIndex + direction;
3225
+ if (stepped >= rowCount) {
3226
+ return fallback;
3227
+ }
3228
+ if (stepped < 0) {
3229
+ return headerFocus(target.columnIndex);
3230
+ }
3231
+ rowIndex = stepped;
3232
+ }
3233
+ return bodyFocus(rowIndex, target.columnIndex);
3234
+ }
3235
+ function nextFocusForKey(key, modifiers, focus, rowCount, columnCount2, pageSize, isSkippableRow = noRowsSkippable) {
3236
+ if (modifiers.altKey) {
3237
+ return null;
3238
+ }
3239
+ const { columnIndex } = focus;
3240
+ function moveRows(rows) {
3241
+ return skipSkippableRows(
3242
+ focusAtLine(linePosition(focus) + rows, columnIndex),
3243
+ rows < 0 ? -1 : 1,
3244
+ rowCount,
3245
+ isSkippableRow,
3246
+ focus
3247
+ );
3248
+ }
3249
+ switch (key) {
3250
+ case "ArrowLeft":
3251
+ if (modifiers.ctrlKey) return null;
3252
+ return { ...focus, columnIndex: columnIndex - 1 };
3253
+ case "ArrowRight":
3254
+ if (modifiers.ctrlKey) return null;
3255
+ return { ...focus, columnIndex: columnIndex + 1 };
3256
+ case "ArrowUp":
3257
+ return moveRows(-1);
3258
+ case "ArrowDown":
3259
+ return moveRows(1);
3260
+ // Ctrl takes Home and End to the grid's ends rather than the row's, which
3261
+ // is the one place Ctrl is navigation rather than reorder.
3262
+ case "Home":
3263
+ return modifiers.ctrlKey ? headerFocus(0) : { ...focus, columnIndex: 0 };
3264
+ case "End": {
3265
+ const rowEnd = { ...focus, columnIndex: columnCount2 - 1 };
3266
+ return modifiers.ctrlKey ? skipSkippableRows(
3267
+ focusAtLine(rowCount - 1, columnCount2 - 1),
3268
+ -1,
3269
+ rowCount,
3270
+ isSkippableRow,
3271
+ rowEnd
3272
+ ) : rowEnd;
3273
+ }
3274
+ case "PageUp":
3275
+ return moveRows(-pageSize);
3276
+ case "PageDown":
3277
+ return moveRows(pageSize);
3278
+ default:
3279
+ return null;
3280
+ }
3281
+ }
3282
+
3283
+ export {
3284
+ alignmentForType,
3285
+ defineColumnsFromRows,
3286
+ getColumnId,
3287
+ resolveRowId,
3288
+ resolveColumnLabel,
3289
+ resolveColumnHeaderText,
3290
+ buildKeyShortcuts,
3291
+ accessDotted,
3292
+ compareValues,
3293
+ sortDirectionFor,
3294
+ sortPriorityFor,
3295
+ toggleColumnSort,
3296
+ sortRows,
3297
+ groupRowId,
3298
+ groupRows,
3299
+ ALL_EXPANDED,
3300
+ ALL_COLLAPSED,
3301
+ isGroupExpanded,
3302
+ toggleGroupExpansion,
3303
+ expandAllGroups,
3304
+ collapseAllGroups,
3305
+ moveGroupByBefore,
3306
+ movesGroupBy,
3307
+ applyColumnOrder,
3308
+ resolveDataColumns,
3309
+ moveColumnBefore,
3310
+ movesColumn,
3311
+ resolveDropBefore,
3312
+ resolveKeyboardDropTarget,
3313
+ isDateType,
3314
+ toDate,
3315
+ isScalarList,
3316
+ unknownFilterEntry,
3317
+ matchesQuery,
3318
+ filterQueryFor,
3319
+ setColumnFilter,
3320
+ clearAllFilters,
3321
+ filterRows,
3322
+ resolveShownRows,
3323
+ unknownDisplayRow,
3324
+ resolveRows,
3325
+ resolveColumns,
3326
+ resolveCell,
3327
+ reportError,
3328
+ DEFAULT_COLUMN_SIZES,
3329
+ KEYBOARD_STEP,
3330
+ resolveColumnConstraints,
3331
+ clampColumnWidth,
3332
+ resolveColumnWidths,
3333
+ totalColumnWidth,
3334
+ beginColumnResize,
3335
+ applyColumnResize,
3336
+ fitColumnsToWidth,
3337
+ sizeColumnToContent,
3338
+ revertColumnSize,
3339
+ computeAggregates,
3340
+ withGroupAggregates,
3341
+ isColumnVisible,
3342
+ applyColumnVisibility,
3343
+ setColumnVisibility,
3344
+ toggleSelection,
3345
+ selectOnly,
3346
+ selectRange,
3347
+ selectAll,
3348
+ clearSelection,
3349
+ diffSelection,
3350
+ isSameCell,
3351
+ selectCell,
3352
+ toggleCellSelection,
3353
+ intentOf,
3354
+ applySelectionIntent,
3355
+ formatCellValue,
3356
+ formatAggregateValue,
3357
+ formatGroupValue,
3358
+ buildExportTable,
3359
+ toHtmlTable,
3360
+ toTsv,
3361
+ copyContent,
3362
+ exportFile,
3363
+ buildPrintDocument,
3364
+ exportPrintDocument,
3365
+ toCsv,
3366
+ toJson,
3367
+ csvWriter,
3368
+ jsonWriter,
3369
+ resolveExportWriters,
3370
+ filterOperatorFamily,
3371
+ defaultFilterOperators,
3372
+ filterOperandArity,
3373
+ parseFilterOperand,
3374
+ formatFilterOperand,
3375
+ DEFAULT_FILTER_VALUE_LIMIT,
3376
+ resolveColumnFilterMenu,
3377
+ createDefaultMessages,
3378
+ defaultMessages,
3379
+ resolveMessages,
3380
+ touchesColumn,
3381
+ describeColumnFilter,
3382
+ isColumnFiltered,
3383
+ columnValueOptions,
3384
+ keyOf2 as keyOf,
3385
+ initialFilterEditorDraft,
3386
+ toValuesDraft,
3387
+ toConditionsDraft,
3388
+ visibleFilterOptions,
3389
+ selectAllCoversBlanks,
3390
+ selectAllState,
3391
+ filterEditorReducer,
3392
+ draftToFilter,
3393
+ filterDraftChanged,
3394
+ builtInCommands,
3395
+ resolveCommands,
3396
+ runCommand,
3397
+ collapseSeparators,
3398
+ resolveMenuEntry,
3399
+ resolveMenu,
3400
+ defaultContextMenu,
3401
+ hasContextMenu,
3402
+ contextMenuEntries,
3403
+ headerFocus,
3404
+ bodyFocus,
3405
+ clampFocus,
3406
+ nextFocusForKey
3407
+ };
3408
+ //# sourceMappingURL=chunk-4CBB53YJ.js.map