@vuu-ui/vuu-table 0.7.0-debug → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js CHANGED
@@ -1,2803 +1,2 @@
1
- // src/Table.tsx
2
- import { ContextMenuProvider } from "@vuu-ui/vuu-popups";
3
- import { Button, useIdMemo } from "@salt-ds/core";
4
-
5
- // src/context-menu/buildContextMenuDescriptors.ts
6
- import { isNumericColumn } from "@vuu-ui/vuu-utils";
7
- var buildContextMenuDescriptors = (dataSource) => (location, options) => {
8
- const descriptors = [];
9
- if (dataSource === void 0) {
10
- return descriptors;
11
- }
12
- if (location === "header") {
13
- descriptors.push(
14
- ...buildSortMenuItems(options, dataSource)
15
- );
16
- descriptors.push(
17
- ...buildGroupMenuItems(options, dataSource)
18
- );
19
- descriptors.push(
20
- ...buildAggregationMenuItems(options, dataSource)
21
- );
22
- descriptors.push(...buildColumnDisplayMenuItems(options));
23
- } else if (location === "filter") {
24
- const { column, filter } = options;
25
- const colIsOnlyFilter = (filter == null ? void 0 : filter.column) === (column == null ? void 0 : column.name);
26
- descriptors.push({
27
- label: "Edit filter",
28
- action: "filter-edit",
29
- options
30
- });
31
- descriptors.push({
32
- label: "Remove filter",
33
- action: "filter-remove-column",
34
- options
35
- });
36
- if (column && !colIsOnlyFilter) {
37
- descriptors.push({
38
- label: `Remove all filters`,
39
- action: "remove-filters",
40
- options
41
- });
42
- }
43
- }
44
- return descriptors;
45
- };
46
- function buildSortMenuItems(options, { sort: { sortDefs } }) {
47
- const { column } = options;
48
- const menuItems = [];
49
- if (column === void 0) {
50
- return menuItems;
51
- }
52
- const hasSort = sortDefs.length > 0;
53
- if (column.sorted === "A") {
54
- menuItems.push({
55
- label: "Reverse Sort (DSC)",
56
- action: "sort-dsc",
57
- options
58
- });
59
- } else if (column.sorted === "D") {
60
- menuItems.push({
61
- label: "Reverse Sort (ASC)",
62
- action: "sort-asc",
63
- options
64
- });
65
- } else if (typeof column.sorted === "number") {
66
- if (column.sorted > 0) {
67
- menuItems.push({
68
- label: "Reverse Sort (DSC)",
69
- action: "sort-add-dsc",
70
- options
71
- });
72
- } else {
73
- menuItems.push({
74
- label: "Reverse Sort (ASC)",
75
- action: "sort-add-asc",
76
- options
77
- });
78
- }
79
- if (hasSort && Math.abs(column.sorted) < sortDefs.length) {
80
- menuItems.push({
81
- label: "Remove from sort",
82
- action: "sort-remove",
83
- options
84
- });
85
- }
86
- menuItems.push({
87
- label: "New Sort",
88
- children: [
89
- { label: "Ascending", action: "sort-asc", options },
90
- { label: "Descending", action: "sort-dsc", options }
91
- ]
92
- });
93
- } else if (hasSort) {
94
- menuItems.push({
95
- label: "Add to sort",
96
- children: [
97
- { label: "Ascending", action: "sort-add-asc", options },
98
- { label: "Descending", action: "sort-add-dsc", options }
99
- ]
100
- });
101
- menuItems.push({
102
- label: "New Sort",
103
- children: [
104
- { label: "Ascending", action: "sort-asc", options },
105
- { label: "Descending", action: "sort-dsc", options }
106
- ]
107
- });
108
- } else {
109
- menuItems.push({
110
- label: "Sort",
111
- children: [
112
- { label: "Ascending", action: "sort-asc", options },
113
- { label: "Descending", action: "sort-dsc", options }
114
- ]
115
- });
116
- }
117
- return menuItems;
118
- }
119
- function buildAggregationMenuItems(options, dataSource) {
120
- const { column } = options;
121
- if (column === void 0 || dataSource.groupBy.length === 0) {
122
- return [];
123
- }
124
- const { name, label = name } = column;
125
- return [
126
- {
127
- label: `Aggregate ${label}`,
128
- children: [{ label: "Count", action: "agg-count", options }].concat(
129
- isNumericColumn(column) ? [
130
- { label: "Sum", action: "agg-sum", options },
131
- { label: "Avg", action: "agg-avg", options },
132
- { label: "High", action: "agg-high", options },
133
- { label: "Low", action: "agg-low", options }
134
- ] : []
135
- )
136
- }
137
- ];
138
- }
139
- var pinColumn = (options, pinLocation) => ({
140
- label: `Pin ${pinLocation}`,
141
- action: `column-pin-${pinLocation}`,
142
- options
143
- });
144
- var pinLeft = (options) => pinColumn(options, "left");
145
- var pinFloating = (options) => pinColumn(options, "floating");
146
- var pinRight = (options) => pinColumn(options, "right");
147
- function buildColumnDisplayMenuItems(options) {
148
- const { column } = options;
149
- if (column === void 0) {
150
- return [];
151
- }
152
- const { pin } = column;
153
- const menuItems = [
154
- {
155
- label: `Hide column`,
156
- action: "column-hide",
157
- options
158
- },
159
- {
160
- label: `Remove column`,
161
- action: "column-remove",
162
- options
163
- }
164
- ];
165
- if (pin === void 0) {
166
- menuItems.push({
167
- label: `Pin column`,
168
- children: [pinLeft(options), pinFloating(options), pinRight(options)]
169
- });
170
- } else if (pin === "left") {
171
- menuItems.push(
172
- { label: "Unpin column", action: "column-unpin", options },
173
- {
174
- label: `Pin column`,
175
- children: [pinFloating(options), pinRight(options)]
176
- }
177
- );
178
- } else if (pin === "right") {
179
- menuItems.push(
180
- { label: "Unpin column", action: "column-unpin", options },
181
- {
182
- label: `Pin column`,
183
- children: [pinLeft(options), pinFloating(options)]
184
- }
185
- );
186
- } else if (pin === "floating") {
187
- menuItems.push(
188
- { label: "Unpin column", action: "column-unpin", options },
189
- {
190
- label: `Pin column`,
191
- children: [pinLeft(options), pinRight(options)]
192
- }
193
- );
194
- }
195
- return menuItems;
196
- }
197
- function buildGroupMenuItems(options, { groupBy }) {
198
- const { column } = options;
199
- const menuItems = [];
200
- if (column === void 0) {
201
- return menuItems;
202
- }
203
- const { name, label = name } = column;
204
- if (groupBy.length === 0) {
205
- menuItems.push({
206
- label: `Group by ${label}`,
207
- action: "group",
208
- options
209
- });
210
- } else {
211
- menuItems.push({
212
- label: `Add ${label} to group by`,
213
- action: "group-add",
214
- options
215
- });
216
- }
217
- return menuItems;
218
- }
219
-
220
- // src/context-menu/useContextMenu.ts
221
- import { removeColumnFromFilter } from "@vuu-ui/vuu-filters";
222
- import {
223
- addGroupColumn,
224
- addSortColumn,
225
- AggregationType,
226
- setAggregations,
227
- setSortColumn
228
- } from "@vuu-ui/vuu-utils";
229
- var removeFilterColumn = (dataSourceFilter, column) => {
230
- if (dataSourceFilter.filterStruct && column) {
231
- const [filterStruct, filter] = removeColumnFromFilter(
232
- column,
233
- dataSourceFilter.filterStruct
234
- );
235
- return {
236
- filter,
237
- filterStruct
238
- };
239
- } else {
240
- return dataSourceFilter;
241
- }
242
- };
243
- var { Average, Count, High, Low, Sum } = AggregationType;
244
- var useContextMenu = ({
245
- dataSource,
246
- onPersistentColumnOperation
247
- }) => {
248
- const handleContextMenuAction = (type, options) => {
249
- const gridOptions = options;
250
- if (gridOptions.column && dataSource) {
251
- const { column } = gridOptions;
252
- switch (type) {
253
- case "sort-asc":
254
- return dataSource.sort = setSortColumn(dataSource.sort, column, "A"), true;
255
- case "sort-dsc":
256
- return dataSource.sort = setSortColumn(dataSource.sort, column, "D"), true;
257
- case "sort-add-asc":
258
- return dataSource.sort = addSortColumn(dataSource.sort, column, "A"), true;
259
- case "sort-add-dsc":
260
- return dataSource.sort = addSortColumn(dataSource.sort, column, "D"), true;
261
- case "group":
262
- return dataSource.groupBy = addGroupColumn(dataSource.groupBy, column), true;
263
- case "group-add":
264
- return dataSource.groupBy = addGroupColumn(dataSource.groupBy, column), true;
265
- case "column-hide":
266
- return onPersistentColumnOperation({ type: "hideColumns", columns: [column] }), true;
267
- case "column-remove":
268
- return dataSource.columns = dataSource.columns.filter((name) => name !== column.name), true;
269
- case "filter-remove-column":
270
- return dataSource.filter = removeFilterColumn(dataSource.filter, column), true;
271
- case "remove-filters":
272
- return dataSource.filter = { filter: "" }, true;
273
- case "agg-avg":
274
- return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Average), true;
275
- case "agg-high":
276
- return dataSource.aggregations = setAggregations(dataSource.aggregations, column, High), true;
277
- case "agg-low":
278
- return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Low), true;
279
- case "agg-count":
280
- return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Count), true;
281
- case "agg-sum":
282
- return dataSource.aggregations = setAggregations(dataSource.aggregations, column, Sum), true;
283
- case "column-pin-floating":
284
- return onPersistentColumnOperation({ type: "pinColumn", column, pin: "floating" }), true;
285
- case "column-pin-left":
286
- return onPersistentColumnOperation({ type: "pinColumn", column, pin: "left" }), true;
287
- case "column-pin-right":
288
- return onPersistentColumnOperation({ type: "pinColumn", column, pin: "right" }), true;
289
- case "column-unpin":
290
- return onPersistentColumnOperation({ type: "pinColumn", column, pin: void 0 }), true;
291
- default:
292
- }
293
- }
294
- return false;
295
- };
296
- return handleContextMenuAction;
297
- };
298
-
299
- // src/RowBasedTable.tsx
300
- import {
301
- buildColumnMap,
302
- getColumnStyle as getColumnStyle3,
303
- isGroupColumn as isGroupColumn2,
304
- metadataKeys as metadataKeys4,
305
- notHidden as notHidden2,
306
- visibleColumnAtIndex
307
- } from "@vuu-ui/vuu-utils";
308
- import { useCallback as useCallback8, useMemo } from "react";
309
-
310
- // src/TableRow.tsx
311
- import {
312
- isGroupColumn,
313
- isJsonColumn,
314
- isJsonGroup,
315
- metadataKeys as metadataKeys3,
316
- notHidden
317
- } from "@vuu-ui/vuu-utils";
318
- import cx2 from "classnames";
319
- import { memo as memo2, useCallback as useCallback3 } from "react";
320
-
321
- // src/TableCell.tsx
322
- import { getColumnStyle, metadataKeys } from "@vuu-ui/vuu-utils";
323
- import { EditableLabel } from "@heswell/salt-lab";
324
- import cx from "classnames";
325
- import { memo, useCallback, useRef, useState } from "react";
326
- import { jsx } from "react/jsx-runtime";
327
- var { KEY } = metadataKeys;
328
- var TableCell = memo(
329
- ({
330
- className: classNameProp,
331
- column,
332
- columnMap,
333
- onClick,
334
- row
335
- }) => {
336
- const labelFieldRef = useRef(null);
337
- const {
338
- align,
339
- CellRenderer,
340
- key,
341
- pin,
342
- editable,
343
- resizing,
344
- valueFormatter
345
- } = column;
346
- const [editing, setEditing] = useState(false);
347
- const value = valueFormatter(row[key]);
348
- const [editableValue, setEditableValue] = useState(value);
349
- const handleTitleMouseDown = () => {
350
- var _a;
351
- (_a = labelFieldRef.current) == null ? void 0 : _a.focus();
352
- };
353
- const handleTitleKeyDown = (evt) => {
354
- if (evt.key === "Enter") {
355
- setEditing(true);
356
- }
357
- };
358
- const handleClick = useCallback(() => {
359
- onClick == null ? void 0 : onClick(column);
360
- }, [column, onClick]);
361
- const handleEnterEditMode = () => {
362
- setEditing(true);
363
- };
364
- const handleExitEditMode = (originalValue = "", finalValue = "", allowDeactivation = true, editCancelled = false) => {
365
- var _a;
366
- setEditing(false);
367
- if (editCancelled) {
368
- setEditableValue(originalValue);
369
- } else if (finalValue !== originalValue) {
370
- setEditableValue(finalValue);
371
- }
372
- if (allowDeactivation === false) {
373
- (_a = labelFieldRef.current) == null ? void 0 : _a.focus();
374
- }
375
- };
376
- const className = cx(classNameProp, {
377
- vuuAlignRight: align === "right",
378
- vuuPinFloating: pin === "floating",
379
- vuuPinLeft: pin === "left",
380
- vuuPinRight: pin === "right",
381
- "vuuTableCell-resizing": resizing
382
- }) || void 0;
383
- const style = getColumnStyle(column);
384
- return editable ? /* @__PURE__ */ jsx(
385
- "div",
386
- {
387
- className,
388
- "data-editable": true,
389
- role: "cell",
390
- style,
391
- onKeyDown: handleTitleKeyDown,
392
- children: /* @__PURE__ */ jsx(
393
- EditableLabel,
394
- {
395
- editing,
396
- value: editableValue,
397
- onChange: setEditableValue,
398
- onMouseDownCapture: handleTitleMouseDown,
399
- onEnterEditMode: handleEnterEditMode,
400
- onExitEditMode: handleExitEditMode,
401
- onKeyDown: handleTitleKeyDown,
402
- ref: labelFieldRef,
403
- tabIndex: 0
404
- },
405
- "title"
406
- )
407
- }
408
- ) : /* @__PURE__ */ jsx(
409
- "div",
410
- {
411
- className,
412
- role: "cell",
413
- style,
414
- onClick: handleClick,
415
- children: CellRenderer ? /* @__PURE__ */ jsx(CellRenderer, { column, columnMap, row }) : value
416
- }
417
- );
418
- },
419
- cellValuesAreEqual
420
- );
421
- TableCell.displayName = "TableCell";
422
- function cellValuesAreEqual(prev, next) {
423
- return prev.column === next.column && prev.onClick === next.onClick && prev.row[KEY] === next.row[KEY] && prev.row[prev.column.key] === next.row[next.column.key];
424
- }
425
-
426
- // src/TableGroupCell.tsx
427
- import { getColumnStyle as getColumnStyle2, metadataKeys as metadataKeys2 } from "@vuu-ui/vuu-utils";
428
- import { useCallback as useCallback2 } from "react";
429
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
430
- var { DEPTH, IS_LEAF } = metadataKeys2;
431
- var getGroupValueAndOffset = (columns, row) => {
432
- const { [DEPTH]: depth, [IS_LEAF]: isLeaf } = row;
433
- if (isLeaf || depth > columns.length) {
434
- return [null, depth === null ? 0 : depth - 1];
435
- } else if (depth === 0) {
436
- return ["$root", 0];
437
- } else {
438
- const { key, valueFormatter } = columns[depth - 1];
439
- const value = valueFormatter(row[key]);
440
- return [value, depth - 1];
441
- }
442
- };
443
- var TableGroupCell = ({ column, onClick, row }) => {
444
- const { columns } = column;
445
- const [value, offset] = getGroupValueAndOffset(columns, row);
446
- const handleClick = useCallback2(() => {
447
- onClick == null ? void 0 : onClick(column);
448
- }, [column, onClick]);
449
- const style = getColumnStyle2(column);
450
- const isLeaf = row[IS_LEAF];
451
- const spacers = Array(offset).fill(0).map((n, i) => /* @__PURE__ */ jsx2("span", { className: "vuuTableGroupCell-spacer" }, i));
452
- return /* @__PURE__ */ jsxs(
453
- "div",
454
- {
455
- className: "vuuTableGroupCell vuuPinLeft",
456
- onClick: isLeaf ? void 0 : handleClick,
457
- role: "cell",
458
- style,
459
- children: [
460
- spacers,
461
- isLeaf ? null : /* @__PURE__ */ jsx2("span", { className: "vuuTableGroupCell-toggle", "data-icon": "triangle-right" }),
462
- /* @__PURE__ */ jsx2("span", { children: value })
463
- ]
464
- }
465
- );
466
- };
467
-
468
- // src/TableRow.tsx
469
- import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
470
- var { IDX, IS_EXPANDED, SELECTED } = metadataKeys3;
471
- var classBase = "vuuTableRow";
472
- var TableRow = memo2(function Row({
473
- columnMap,
474
- columns,
475
- offset,
476
- onClick,
477
- onToggleGroup,
478
- virtualColSpan = 0,
479
- row
480
- }) {
481
- const {
482
- [IDX]: rowIndex,
483
- [IS_EXPANDED]: isExpanded,
484
- [SELECTED]: isSelected
485
- } = row;
486
- const className = cx2(classBase, {
487
- [`${classBase}-even`]: rowIndex % 2 === 0,
488
- [`${classBase}-expanded`]: isExpanded,
489
- [`${classBase}-preSelected`]: isSelected === 2
490
- });
491
- const handleRowClick = useCallback3(
492
- (evt) => {
493
- const rangeSelect = evt.shiftKey;
494
- const keepExistingSelection = evt.ctrlKey || evt.metaKey;
495
- onClick == null ? void 0 : onClick(row, rangeSelect, keepExistingSelection);
496
- },
497
- [onClick, row]
498
- );
499
- const handleGroupCellClick = useCallback3(
500
- (column) => {
501
- if (isGroupColumn(column) || isJsonGroup(column, row)) {
502
- onToggleGroup == null ? void 0 : onToggleGroup(row, column);
503
- }
504
- },
505
- [onToggleGroup, row]
506
- );
507
- return /* @__PURE__ */ jsxs2(
508
- "div",
509
- {
510
- "aria-selected": isSelected === 1 ? true : void 0,
511
- "aria-rowindex": rowIndex,
512
- className,
513
- onClick: handleRowClick,
514
- role: "row",
515
- style: {
516
- transform: `translate3d(0px, ${offset}px, 0px)`
517
- },
518
- children: [
519
- virtualColSpan > 0 ? /* @__PURE__ */ jsx3("div", { role: "cell", style: { width: virtualColSpan } }) : null,
520
- columns.filter(notHidden).map((column) => {
521
- const isGroup = isGroupColumn(column);
522
- const isJsonCell = isJsonColumn(column);
523
- const Cell = isGroup ? TableGroupCell : TableCell;
524
- return /* @__PURE__ */ jsx3(
525
- Cell,
526
- {
527
- column,
528
- columnMap,
529
- onClick: isGroup || isJsonCell ? handleGroupCellClick : void 0,
530
- row
531
- },
532
- column.name
533
- );
534
- })
535
- ]
536
- }
537
- );
538
- });
539
-
540
- // src/TableGroupHeaderCell.tsx
541
- import cx3 from "classnames";
542
- import { useRef as useRef4 } from "react";
543
-
544
- // src/ColumnResizer.tsx
545
- import { useCallback as useCallback4, useRef as useRef2 } from "react";
546
- import { jsx as jsx4 } from "react/jsx-runtime";
547
- var NOOP = () => void 0;
548
- var baseClass = "vuuColumnResizer";
549
- var ColumnResizer = ({
550
- onDrag,
551
- onDragEnd = NOOP,
552
- onDragStart = NOOP
553
- }) => {
554
- const position = useRef2(0);
555
- const onMouseMove = useCallback4(
556
- (e) => {
557
- if (e.stopPropagation) {
558
- e.stopPropagation();
559
- }
560
- if (e.preventDefault) {
561
- e.preventDefault();
562
- }
563
- const x = Math.round(e.clientX);
564
- const moveBy = x - position.current;
565
- position.current = x;
566
- if (moveBy !== 0) {
567
- onDrag(e, moveBy);
568
- }
569
- },
570
- [onDrag]
571
- );
572
- const onMouseUp = useCallback4(
573
- (e) => {
574
- window.removeEventListener("mouseup", onMouseUp);
575
- window.removeEventListener("mousemove", onMouseMove);
576
- onDragEnd(e);
577
- },
578
- [onDragEnd, onMouseMove]
579
- );
580
- const handleMouseDown = useCallback4(
581
- (e) => {
582
- onDragStart(e);
583
- position.current = Math.round(e.clientX);
584
- window.addEventListener("mouseup", onMouseUp);
585
- window.addEventListener("mousemove", onMouseMove);
586
- if (e.stopPropagation) {
587
- e.stopPropagation();
588
- }
589
- if (e.preventDefault) {
590
- e.preventDefault();
591
- }
592
- },
593
- [onDragStart, onMouseMove, onMouseUp]
594
- );
595
- return /* @__PURE__ */ jsx4("div", { className: baseClass, "data-align": "end", onMouseDown: handleMouseDown });
596
- };
597
-
598
- // src/useTableColumnResize.tsx
599
- import { useCallback as useCallback5, useRef as useRef3 } from "react";
600
- var useTableColumnResize = ({
601
- column,
602
- onResize,
603
- rootRef
604
- }) => {
605
- const widthRef = useRef3(0);
606
- const isResizing = useRef3(false);
607
- const { name } = column;
608
- const handleResizeStart = useCallback5(() => {
609
- if (onResize && rootRef.current) {
610
- const { width } = rootRef.current.getBoundingClientRect();
611
- widthRef.current = Math.round(width);
612
- isResizing.current = true;
613
- onResize == null ? void 0 : onResize("begin", name);
614
- }
615
- }, [name, onResize, rootRef]);
616
- const handleResize = useCallback5(
617
- (_evt, moveBy) => {
618
- if (rootRef.current) {
619
- if (onResize) {
620
- const { width } = rootRef.current.getBoundingClientRect();
621
- const newWidth = Math.round(width) + moveBy;
622
- if (newWidth !== widthRef.current && newWidth > 0) {
623
- onResize("resize", name, newWidth);
624
- widthRef.current = newWidth;
625
- }
626
- }
627
- }
628
- },
629
- [name, onResize, rootRef]
630
- );
631
- const handleResizeEnd = useCallback5(() => {
632
- if (onResize) {
633
- onResize("end", name, widthRef.current);
634
- setTimeout(() => {
635
- isResizing.current = false;
636
- }, 100);
637
- }
638
- }, [name, onResize]);
639
- return {
640
- isResizing: isResizing.current,
641
- onDrag: handleResize,
642
- onDragStart: handleResizeStart,
643
- onDragEnd: handleResizeEnd
644
- };
645
- };
646
-
647
- // src/TableGroupHeaderCell.tsx
648
- import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
649
- var classBase2 = "vuuTable-groupHeaderCell";
650
- var RemoveButton = ({
651
- column,
652
- onClick,
653
- ...htmlAttributes
654
- }) => {
655
- return /* @__PURE__ */ jsx5(
656
- "span",
657
- {
658
- ...htmlAttributes,
659
- className: `${classBase2}-close`,
660
- "data-icon": "close-circle",
661
- onClick: () => onClick == null ? void 0 : onClick(column)
662
- }
663
- );
664
- };
665
- var ColHeader = (props) => {
666
- const { children, column, className } = props;
667
- return /* @__PURE__ */ jsxs3("div", { className: cx3(`${classBase2}-col`, className), role: "columnheader", children: [
668
- /* @__PURE__ */ jsx5("span", { className: `${classBase2}-label`, children: column.name }),
669
- children
670
- ] });
671
- };
672
- var TableGroupHeaderCell = ({
673
- column: groupColumn,
674
- className: classNameProp,
675
- onRemoveColumn,
676
- onResize,
677
- ...props
678
- }) => {
679
- const rootRef = useRef4(null);
680
- const { isResizing, ...resizeProps } = useTableColumnResize({
681
- column: groupColumn,
682
- onResize,
683
- rootRef
684
- });
685
- const className = cx3(classBase2, classNameProp, {
686
- vuuPinLeft: groupColumn.pin === "left",
687
- [`${classBase2}-right`]: groupColumn.align === "right",
688
- [`${classBase2}-resizing`]: groupColumn.resizing,
689
- [`${classBase2}-pending`]: groupColumn.groupConfirmed === false
690
- });
691
- const { columns } = groupColumn;
692
- return /* @__PURE__ */ jsx5("div", { className, ref: rootRef, ...props, children: /* @__PURE__ */ jsxs3("div", { className: `${classBase2}-inner`, children: [
693
- columns.map((column) => /* @__PURE__ */ jsx5(ColHeader, { column, children: columns.length > 1 ? /* @__PURE__ */ jsx5(RemoveButton, { column, onClick: onRemoveColumn }) : null }, column.key)),
694
- /* @__PURE__ */ jsx5(RemoveButton, { "data-align": "end", onClick: onRemoveColumn }),
695
- groupColumn.resizeable !== false ? /* @__PURE__ */ jsx5(ColumnResizer, { ...resizeProps }) : null
696
- ] }) });
697
- };
698
-
699
- // src/TableHeaderCell.tsx
700
- import cx6 from "classnames";
701
- import { useCallback as useCallback7, useRef as useRef5 } from "react";
702
-
703
- // src/SortIndicator.tsx
704
- import cx4 from "classnames";
705
- import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
706
- var classBase3 = "vuuSortIndicator";
707
- var SortIndicator = ({ sorted }) => {
708
- if (!sorted) {
709
- return null;
710
- }
711
- const direction = typeof sorted === "number" ? sorted < 0 ? "dsc" : "asc" : sorted === "A" ? "asc" : "dsc";
712
- return typeof sorted === "number" ? /* @__PURE__ */ jsxs4("div", { className: cx4(classBase3, "multi-col", direction), children: [
713
- /* @__PURE__ */ jsx6("span", { "data-icon": `sorted-${direction}` }),
714
- /* @__PURE__ */ jsx6("span", { className: "vuuSortPosition", children: Math.abs(sorted) })
715
- ] }) : /* @__PURE__ */ jsx6("div", { className: cx4(classBase3, "single-col"), children: /* @__PURE__ */ jsx6("span", { "data-icon": `sorted-${direction}` }) });
716
- };
717
-
718
- // src/TableHeaderCell.tsx
719
- import { useContextMenu as useContextMenu3 } from "@vuu-ui/vuu-popups";
720
-
721
- // src/filter-indicator.tsx
722
- import { useContextMenu as useContextMenu2 } from "@vuu-ui/vuu-popups";
723
- import cx5 from "classnames";
724
- import { useCallback as useCallback6 } from "react";
725
- import { jsx as jsx7 } from "react/jsx-runtime";
726
- var FilterIndicator = ({ column, filter }) => {
727
- const showContextMenu = useContextMenu2();
728
- const handleClick = useCallback6(
729
- (evt) => {
730
- evt.stopPropagation();
731
- showContextMenu(evt, "filter", { column, filter });
732
- },
733
- [column, filter, showContextMenu]
734
- );
735
- if (!column.filter) {
736
- return null;
737
- }
738
- return /* @__PURE__ */ jsx7(
739
- "div",
740
- {
741
- className: cx5("vuuFilterIndicator"),
742
- "data-icon": "filter",
743
- onClick: handleClick
744
- }
745
- );
746
- };
747
-
748
- // src/TableHeaderCell.tsx
749
- import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
750
- var classBase4 = "vuuTable-headerCell";
751
- var TableHeaderCell = ({
752
- column,
753
- className: classNameProp,
754
- onClick,
755
- onDragStart,
756
- onResize,
757
- ...props
758
- }) => {
759
- const rootRef = useRef5(null);
760
- const { isResizing, ...resizeProps } = useTableColumnResize({
761
- column,
762
- onResize,
763
- rootRef
764
- });
765
- const showContextMenu = useContextMenu3();
766
- const dragTimerRef = useRef5(null);
767
- const handleContextMenu = (e) => {
768
- showContextMenu(e, "header", { column });
769
- };
770
- const handleClick = useCallback7(
771
- (evt) => !isResizing && (onClick == null ? void 0 : onClick(evt)),
772
- [isResizing, onClick]
773
- );
774
- const handleMouseDown = useCallback7(
775
- (evt) => {
776
- dragTimerRef.current = window.setTimeout(() => {
777
- onDragStart == null ? void 0 : onDragStart(evt);
778
- dragTimerRef.current = null;
779
- }, 500);
780
- },
781
- [onDragStart]
782
- );
783
- const handleMouseUp = useCallback7(() => {
784
- if (dragTimerRef.current !== null) {
785
- window.clearTimeout(dragTimerRef.current);
786
- dragTimerRef.current = null;
787
- }
788
- }, []);
789
- const className = cx6(classBase4, classNameProp, {
790
- vuuPinFloating: column.pin === "floating",
791
- vuuPinLeft: column.pin === "left",
792
- vuuPinRight: column.pin === "right",
793
- vuuEndPin: column.endPin,
794
- [`${classBase4}-resizing`]: column.resizing,
795
- [`${classBase4}-right`]: column.align === "right"
796
- });
797
- return /* @__PURE__ */ jsx8(
798
- "div",
799
- {
800
- className,
801
- ...props,
802
- onClick: handleClick,
803
- onContextMenu: handleContextMenu,
804
- onMouseDown: handleMouseDown,
805
- onMouseUp: handleMouseUp,
806
- ref: rootRef,
807
- children: /* @__PURE__ */ jsxs5("div", { className: `${classBase4}-inner`, children: [
808
- /* @__PURE__ */ jsx8(FilterIndicator, { column }),
809
- /* @__PURE__ */ jsx8("div", { className: `${classBase4}-label`, children: column.label }),
810
- /* @__PURE__ */ jsx8(SortIndicator, { sorted: column.sorted }),
811
- column.resizeable !== false ? /* @__PURE__ */ jsx8(ColumnResizer, { ...resizeProps }) : null
812
- ] })
813
- }
814
- );
815
- };
816
-
817
- // src/RowBasedTable.tsx
818
- import { jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
819
- var classBase5 = "vuuTable";
820
- var { RENDER_IDX } = metadataKeys4;
821
- var RowBasedTable = ({
822
- columns,
823
- columnsWithinViewport,
824
- data,
825
- getRowOffset,
826
- headings,
827
- onColumnResize,
828
- onHeaderCellDragStart,
829
- onContextMenu,
830
- onRemoveColumnFromGroupBy,
831
- onRowClick,
832
- onSort,
833
- onToggleGroup,
834
- tableId,
835
- virtualColSpan = 0,
836
- rowCount
837
- }) => {
838
- const handleDragStart = useCallback8(
839
- (evt) => {
840
- onHeaderCellDragStart == null ? void 0 : onHeaderCellDragStart(evt);
841
- },
842
- [onHeaderCellDragStart]
843
- );
844
- const visibleColumns = useMemo(() => {
845
- return columns.filter(notHidden2);
846
- }, [columns]);
847
- const columnMap = useMemo(() => buildColumnMap(columns), [columns]);
848
- const handleHeaderClick = useCallback8(
849
- (evt) => {
850
- var _a;
851
- const targetElement = evt.target;
852
- const headerCell = targetElement.closest(
853
- ".vuuTable-headerCell"
854
- );
855
- const colIdx = parseInt((_a = headerCell == null ? void 0 : headerCell.dataset.idx) != null ? _a : "-1");
856
- const column = visibleColumnAtIndex(columns, colIdx);
857
- const isAdditive = evt.shiftKey;
858
- column && onSort(column, isAdditive);
859
- },
860
- [columns, onSort]
861
- );
862
- return /* @__PURE__ */ jsxs6("div", { "aria-rowcount": rowCount, className: `${classBase5}-table`, role: "table", children: [
863
- /* @__PURE__ */ jsxs6("div", { className: `${classBase5}-headers`, role: "rowGroup", children: [
864
- headings.map((colHeaders, i) => /* @__PURE__ */ jsx9("div", { className: "vuuTable-heading", children: colHeaders.map(({ label, width }, j) => /* @__PURE__ */ jsx9("div", { className: "vuuTable-headingCell", style: { width }, children: label }, j)) }, i)),
865
- /* @__PURE__ */ jsx9("div", { role: "row", children: visibleColumns.map((column, i) => {
866
- const style = getColumnStyle3(column);
867
- return isGroupColumn2(column) ? /* @__PURE__ */ jsx9(
868
- TableGroupHeaderCell,
869
- {
870
- column,
871
- "data-idx": i,
872
- onRemoveColumn: onRemoveColumnFromGroupBy,
873
- onResize: onColumnResize,
874
- role: "columnHeader",
875
- style
876
- },
877
- i
878
- ) : /* @__PURE__ */ jsx9(
879
- TableHeaderCell,
880
- {
881
- column,
882
- "data-idx": i,
883
- id: `${tableId}-${i}`,
884
- onClick: handleHeaderClick,
885
- onDragStart: handleDragStart,
886
- onResize: onColumnResize,
887
- role: "columnHeader",
888
- style
889
- },
890
- i
891
- );
892
- }) })
893
- ] }),
894
- /* @__PURE__ */ jsx9(
895
- "div",
896
- {
897
- className: `${classBase5}-body`,
898
- onContextMenu,
899
- role: "rowGroup",
900
- children: data == null ? void 0 : data.map((row) => /* @__PURE__ */ jsx9(
901
- TableRow,
902
- {
903
- columnMap,
904
- columns: columnsWithinViewport,
905
- offset: getRowOffset(row),
906
- onClick: onRowClick,
907
- virtualColSpan,
908
- onToggleGroup,
909
- row
910
- },
911
- row[RENDER_IDX]
912
- ))
913
- }
914
- )
915
- ] });
916
- };
917
-
918
- // src/useTable.ts
919
- import { useContextMenu as usePopupContextMenu } from "@vuu-ui/vuu-popups";
920
- import {
921
- applySort,
922
- buildColumnMap as buildColumnMap2,
923
- isJsonGroup as isJsonGroup2,
924
- metadataKeys as metadataKeys8,
925
- moveItem as moveItem2
926
- } from "@vuu-ui/vuu-utils";
927
- import {
928
- useCallback as useCallback18,
929
- useEffect as useEffect5,
930
- useMemo as useMemo6,
931
- useRef as useRef15,
932
- useState as useState5
933
- } from "react";
934
-
935
- // src/useDataSource.ts
936
- import {
937
- isVuuFeatureAction,
938
- isVuuFeatureInvocation
939
- } from "@vuu-ui/vuu-data";
940
- import { getFullRange, metadataKeys as metadataKeys5, WindowRange } from "@vuu-ui/vuu-utils";
941
- import { useCallback as useCallback9, useEffect, useMemo as useMemo2, useRef as useRef6, useState as useState2 } from "react";
942
- var { SELECTED: SELECTED2 } = metadataKeys5;
943
- function useDataSource({
944
- dataSource,
945
- onConfigChange,
946
- onFeatureEnabled,
947
- onFeatureInvocation,
948
- onSizeChange,
949
- onSubscribed,
950
- range = { from: 0, to: 0 },
951
- renderBufferSize = 0,
952
- viewportRowCount
953
- }) {
954
- const [, forceUpdate] = useState2(null);
955
- const isMounted = useRef6(true);
956
- const hasUpdated = useRef6(false);
957
- const rangeRef = useRef6({ from: 0, to: 0 });
958
- const rafHandle = useRef6(null);
959
- const data = useRef6([]);
960
- const dataWindow = useMemo2(
961
- () => new MovingWindow(getFullRange(range)),
962
- // eslint-disable-next-line react-hooks/exhaustive-deps
963
- []
964
- );
965
- const setData = useCallback9(
966
- (updates) => {
967
- for (const row of updates) {
968
- dataWindow.add(row);
969
- }
970
- data.current = dataWindow.data;
971
- hasUpdated.current = true;
972
- },
973
- [dataWindow]
974
- );
975
- const datasourceMessageHandler = useCallback9(
976
- (message) => {
977
- if (message.type === "subscribed") {
978
- onSubscribed == null ? void 0 : onSubscribed(message);
979
- } else if (message.type === "viewport-update") {
980
- if (typeof message.size === "number") {
981
- onSizeChange == null ? void 0 : onSizeChange(message.size);
982
- dataWindow.setRowCount(message.size);
983
- }
984
- if (message.rows) {
985
- setData(message.rows);
986
- } else if (typeof message.size === "number") {
987
- data.current = dataWindow.data;
988
- hasUpdated.current = true;
989
- }
990
- } else if (isVuuFeatureAction(message)) {
991
- onFeatureEnabled == null ? void 0 : onFeatureEnabled(message);
992
- } else if (isVuuFeatureInvocation(message)) {
993
- onFeatureInvocation == null ? void 0 : onFeatureInvocation(message);
994
- } else {
995
- console.log(`useDataSource unexpected message ${message.type}`);
996
- }
997
- },
998
- [
999
- dataWindow,
1000
- onFeatureEnabled,
1001
- onFeatureInvocation,
1002
- onSizeChange,
1003
- onSubscribed,
1004
- setData
1005
- ]
1006
- );
1007
- useEffect(
1008
- () => () => {
1009
- if (rafHandle.current) {
1010
- cancelAnimationFrame(rafHandle.current);
1011
- rafHandle.current = null;
1012
- }
1013
- isMounted.current = false;
1014
- },
1015
- []
1016
- );
1017
- const refreshIfUpdated = useCallback9(() => {
1018
- if (isMounted.current) {
1019
- if (hasUpdated.current) {
1020
- forceUpdate({});
1021
- hasUpdated.current = false;
1022
- }
1023
- rafHandle.current = requestAnimationFrame(refreshIfUpdated);
1024
- }
1025
- }, [forceUpdate]);
1026
- useEffect(() => {
1027
- rafHandle.current = requestAnimationFrame(refreshIfUpdated);
1028
- }, [refreshIfUpdated]);
1029
- const adjustRange = useCallback9(
1030
- (rowCount) => {
1031
- const { from } = dataSource.range;
1032
- const rowRange = { from, to: from + rowCount };
1033
- const fullRange = getFullRange(rowRange, renderBufferSize);
1034
- dataWindow.setRange(fullRange);
1035
- dataSource.range = rangeRef.current = fullRange;
1036
- dataSource.emit("range", rowRange);
1037
- },
1038
- [dataSource, dataWindow, renderBufferSize]
1039
- );
1040
- const setRange = useCallback9(
1041
- (range2) => {
1042
- const fullRange = getFullRange(range2, renderBufferSize);
1043
- dataWindow.setRange(fullRange);
1044
- dataSource.range = rangeRef.current = fullRange;
1045
- dataSource.emit("range", range2);
1046
- },
1047
- [dataSource, dataWindow, renderBufferSize]
1048
- );
1049
- const getSelectedRows = useCallback9(() => {
1050
- return dataWindow.getSelectedRows();
1051
- }, [dataWindow]);
1052
- useEffect(() => {
1053
- dataSource == null ? void 0 : dataSource.subscribe(
1054
- {
1055
- range: rangeRef.current
1056
- },
1057
- datasourceMessageHandler
1058
- );
1059
- }, [dataSource, datasourceMessageHandler, onConfigChange]);
1060
- useEffect(() => {
1061
- adjustRange(viewportRowCount);
1062
- }, [adjustRange, viewportRowCount]);
1063
- return {
1064
- data: data.current,
1065
- getSelectedRows,
1066
- range: rangeRef.current,
1067
- setRange,
1068
- dataSource
1069
- };
1070
- }
1071
- var MovingWindow = class {
1072
- constructor({ from, to }) {
1073
- this.rowCount = 0;
1074
- this.setRowCount = (rowCount) => {
1075
- if (rowCount < this.data.length) {
1076
- this.data.length = rowCount;
1077
- }
1078
- this.rowCount = rowCount;
1079
- };
1080
- this.range = new WindowRange(from, to);
1081
- this.data = new Array(to - from);
1082
- this.rowCount = 0;
1083
- }
1084
- add(data) {
1085
- var _a;
1086
- const [index] = data;
1087
- if (this.isWithinRange(index)) {
1088
- const internalIndex = index - this.range.from;
1089
- this.data[internalIndex] = data;
1090
- const isSelected = data[SELECTED2];
1091
- const preSelected = (_a = this.data[internalIndex - 1]) == null ? void 0 : _a[SELECTED2];
1092
- if (preSelected === 0 && isSelected) {
1093
- this.data[internalIndex - 1][SELECTED2] = 2;
1094
- } else if (preSelected === 2 && !isSelected) {
1095
- this.data[internalIndex - 1][SELECTED2] = 0;
1096
- }
1097
- }
1098
- }
1099
- getAtIndex(index) {
1100
- return this.range.isWithin(index) && this.data[index - this.range.from] != null ? this.data[index - this.range.from] : void 0;
1101
- }
1102
- isWithinRange(index) {
1103
- return this.range.isWithin(index);
1104
- }
1105
- setRange({ from, to }) {
1106
- if (from !== this.range.from || to !== this.range.to) {
1107
- const [overlapFrom, overlapTo] = this.range.overlap(from, to);
1108
- const newData = new Array(Math.max(0, to - from));
1109
- for (let i = overlapFrom; i < overlapTo; i++) {
1110
- const data = this.getAtIndex(i);
1111
- if (data) {
1112
- const index = i - from;
1113
- newData[index] = data;
1114
- }
1115
- }
1116
- this.data = newData;
1117
- this.range.from = from;
1118
- this.range.to = to;
1119
- }
1120
- }
1121
- getSelectedRows() {
1122
- return this.data.filter((row) => row[SELECTED2] === 1);
1123
- }
1124
- };
1125
-
1126
- // src/useDraggableColumn.ts
1127
- import { useDragDrop } from "@heswell/salt-lab";
1128
- import { useCallback as useCallback10, useRef as useRef7 } from "react";
1129
- var useDraggableColumn = ({ onDrop }) => {
1130
- const mousePosRef = useRef7();
1131
- const containerRef = useRef7(null);
1132
- const handleDropSettle = useCallback10(() => {
1133
- console.log(`handleDropSettle`);
1134
- mousePosRef.current = void 0;
1135
- containerRef.current = null;
1136
- }, []);
1137
- const { draggable, draggedItemIndex, onMouseDown } = useDragDrop({
1138
- // allowDragDrop: "drop-indicator",
1139
- allowDragDrop: true,
1140
- draggableClassName: "vuuTable-headerCell",
1141
- orientation: "horizontal",
1142
- containerRef,
1143
- itemQuery: ".vuuTable-headerCell",
1144
- onDrop,
1145
- onDropSettle: handleDropSettle
1146
- });
1147
- const onHeaderCellDragStart = useCallback10(
1148
- (evt) => {
1149
- const { clientX, clientY } = evt;
1150
- console.log(
1151
- `useDraggableColumn handleHeaderCellDragStart means mouseDown fired on a column in RowBasedTable`
1152
- );
1153
- const sourceElement = evt.target;
1154
- const columnHeaderCell = sourceElement.closest(".vuuTable-headerCell");
1155
- containerRef.current = columnHeaderCell == null ? void 0 : columnHeaderCell.closest(
1156
- "[role='row']"
1157
- );
1158
- const {
1159
- dataset: { idx = "-1" }
1160
- } = columnHeaderCell;
1161
- mousePosRef.current = {
1162
- clientX,
1163
- clientY,
1164
- idx
1165
- };
1166
- onMouseDown == null ? void 0 : onMouseDown(evt);
1167
- },
1168
- [onMouseDown]
1169
- );
1170
- return {
1171
- draggable,
1172
- draggedItemIndex,
1173
- onHeaderCellDragStart
1174
- };
1175
- };
1176
-
1177
- // src/useKeyboardNavigation.ts
1178
- import { withinRange } from "@vuu-ui/vuu-utils";
1179
- import {
1180
- useCallback as useCallback11,
1181
- useEffect as useEffect2,
1182
- useLayoutEffect,
1183
- useMemo as useMemo3,
1184
- useRef as useRef8
1185
- } from "react";
1186
-
1187
- // src/keyUtils.ts
1188
- function union(set1, ...sets) {
1189
- const result = new Set(set1);
1190
- for (let set of sets) {
1191
- for (let element of set) {
1192
- result.add(element);
1193
- }
1194
- }
1195
- return result;
1196
- }
1197
- var ArrowUp = "ArrowUp";
1198
- var ArrowDown = "ArrowDown";
1199
- var ArrowLeft = "ArrowLeft";
1200
- var ArrowRight = "ArrowRight";
1201
- var Home = "Home";
1202
- var End = "End";
1203
- var PageUp = "PageUp";
1204
- var PageDown = "PageDown";
1205
- var actionKeys = /* @__PURE__ */ new Set(["Enter", "Delete", " "]);
1206
- var focusKeys = /* @__PURE__ */ new Set(["Tab"]);
1207
- var arrowLeftRightKeys = /* @__PURE__ */ new Set(["ArrowRight", "ArrowLeft"]);
1208
- var navigationKeys = /* @__PURE__ */ new Set([
1209
- Home,
1210
- End,
1211
- PageUp,
1212
- PageDown,
1213
- ArrowDown,
1214
- ArrowLeft,
1215
- ArrowRight,
1216
- ArrowUp
1217
- ]);
1218
- var functionKeys = /* @__PURE__ */ new Set([
1219
- "F1",
1220
- "F2",
1221
- "F3",
1222
- "F4",
1223
- "F5",
1224
- "F6",
1225
- "F7",
1226
- "F8",
1227
- "F9",
1228
- "F10",
1229
- "F11",
1230
- "F12"
1231
- ]);
1232
- var specialKeys = union(
1233
- actionKeys,
1234
- navigationKeys,
1235
- arrowLeftRightKeys,
1236
- functionKeys,
1237
- focusKeys
1238
- );
1239
- var PageKeys = ["Home", "End", "PageUp", "PageDown"];
1240
- var isPagingKey = (key) => PageKeys.includes(key);
1241
- var isNavigationKey = (key) => {
1242
- return navigationKeys.has(key);
1243
- };
1244
-
1245
- // src/useKeyboardNavigation.ts
1246
- var headerCellQuery = (colIdx) => `.vuuTable-headers .vuuTable-headerCell:nth-child(${colIdx + 1})`;
1247
- var dataCellQuery = (rowIdx, colIdx) => `.vuuTable-body > [aria-rowindex='${rowIdx}'] > [role='cell']:nth-child(${colIdx + 1})`;
1248
- var NULL_CELL_POS = [-1, -1];
1249
- function nextCellPos(key, [rowIdx, colIdx], columnCount, rowCount) {
1250
- if (key === ArrowUp) {
1251
- if (rowIdx > -1) {
1252
- return [rowIdx - 1, colIdx];
1253
- } else {
1254
- return [rowIdx, colIdx];
1255
- }
1256
- } else if (key === ArrowDown) {
1257
- if (rowIdx === -1) {
1258
- return [0, colIdx];
1259
- } else if (rowIdx === rowCount - 1) {
1260
- return [rowIdx, colIdx];
1261
- } else {
1262
- return [rowIdx + 1, colIdx];
1263
- }
1264
- } else if (key === ArrowRight) {
1265
- if (colIdx < columnCount - 1) {
1266
- return [rowIdx, colIdx + 1];
1267
- } else {
1268
- return [rowIdx, colIdx];
1269
- }
1270
- } else if (key === ArrowLeft) {
1271
- if (colIdx > 0) {
1272
- return [rowIdx, colIdx - 1];
1273
- } else {
1274
- return [rowIdx, colIdx];
1275
- }
1276
- }
1277
- return [rowIdx, colIdx];
1278
- }
1279
- var useKeyboardNavigation = ({
1280
- columnCount = 0,
1281
- containerRef,
1282
- disableHighlightOnFocus,
1283
- data,
1284
- requestScroll,
1285
- rowCount = 0,
1286
- viewportRange
1287
- }) => {
1288
- var _a;
1289
- const { from: viewportFirstRow, to: viewportLastRow } = viewportRange;
1290
- const focusedCellPos = useRef8([-1, -1]);
1291
- const focusableCell = useRef8();
1292
- const activeCellPos = useRef8([-1, 0]);
1293
- const getTableCell = useCallback11(
1294
- ([rowIdx, colIdx]) => {
1295
- var _a2;
1296
- const cssQuery = rowIdx === -1 ? headerCellQuery(colIdx) : dataCellQuery(rowIdx, colIdx);
1297
- return (_a2 = containerRef.current) == null ? void 0 : _a2.querySelector(
1298
- cssQuery
1299
- );
1300
- },
1301
- [containerRef]
1302
- );
1303
- const getFocusedCell = (element) => element == null ? void 0 : element.closest(
1304
- "[role='columnHeader'],[role='cell']"
1305
- );
1306
- const getTableCellPos = (tableCell) => {
1307
- var _a2, _b;
1308
- if (tableCell.role === "columnHeader") {
1309
- const colIdx = parseInt((_a2 = tableCell.dataset.idx) != null ? _a2 : "-1", 10);
1310
- return [-1, colIdx];
1311
- } else {
1312
- const focusedRow = tableCell.closest("[role='row']");
1313
- if (focusedRow) {
1314
- const rowIdx = parseInt((_b = focusedRow.ariaRowIndex) != null ? _b : "-1", 10);
1315
- const colIdx = Array.from(focusedRow.childNodes).indexOf(tableCell);
1316
- return [rowIdx, colIdx];
1317
- }
1318
- }
1319
- return NULL_CELL_POS;
1320
- };
1321
- const focusCell = useCallback11(
1322
- (cellPos) => {
1323
- var _a2;
1324
- if (containerRef.current) {
1325
- const activeCell = getTableCell(cellPos);
1326
- if (activeCell) {
1327
- if (activeCell !== focusableCell.current) {
1328
- (_a2 = focusableCell.current) == null ? void 0 : _a2.setAttribute("tabindex", "");
1329
- focusableCell.current = activeCell;
1330
- activeCell.setAttribute("tabindex", "0");
1331
- }
1332
- activeCell.focus();
1333
- } else if (!withinRange(cellPos[0], viewportRange)) {
1334
- focusableCell.current = void 0;
1335
- requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "up" });
1336
- }
1337
- }
1338
- },
1339
- // TODO we recreate this function whenever viewportRange changes, which will
1340
- // be often whilst scrolling - store range in a a ref ?
1341
- [containerRef, getTableCell, requestScroll, viewportRange]
1342
- );
1343
- const setActiveCell = useCallback11(
1344
- (rowIdx, colIdx, fromKeyboard = false) => {
1345
- const pos = [rowIdx, colIdx];
1346
- activeCellPos.current = pos;
1347
- focusCell(pos);
1348
- if (fromKeyboard) {
1349
- focusedCellPos.current = pos;
1350
- }
1351
- },
1352
- [focusCell]
1353
- );
1354
- const virtualizeActiveCell = useCallback11(() => {
1355
- var _a2;
1356
- (_a2 = focusableCell.current) == null ? void 0 : _a2.setAttribute("tabindex", "");
1357
- focusableCell.current = void 0;
1358
- }, []);
1359
- const nextPageItemIdx = useCallback11(
1360
- async (key, cellPos) => {
1361
- switch (key) {
1362
- case PageDown:
1363
- requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "down" });
1364
- break;
1365
- case PageUp:
1366
- requestScroll == null ? void 0 : requestScroll({ type: "scroll-page", direction: "up" });
1367
- break;
1368
- case Home:
1369
- requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "home" });
1370
- break;
1371
- case End:
1372
- requestScroll == null ? void 0 : requestScroll({ type: "scroll-end", direction: "end" });
1373
- break;
1374
- }
1375
- return cellPos;
1376
- },
1377
- [requestScroll]
1378
- );
1379
- const handleFocus = useCallback11(() => {
1380
- var _a2;
1381
- if (disableHighlightOnFocus !== true) {
1382
- if ((_a2 = containerRef.current) == null ? void 0 : _a2.contains(document.activeElement)) {
1383
- const focusedCell = getFocusedCell(document.activeElement);
1384
- if (focusedCell) {
1385
- focusedCellPos.current = getTableCellPos(focusedCell);
1386
- }
1387
- }
1388
- }
1389
- }, [disableHighlightOnFocus, containerRef]);
1390
- const navigateChildItems = useCallback11(
1391
- async (key) => {
1392
- const [nextRowIdx, nextColIdx] = isPagingKey(key) ? await nextPageItemIdx(key, activeCellPos.current) : nextCellPos(key, activeCellPos.current, columnCount, rowCount);
1393
- const [rowIdx, colIdx] = activeCellPos.current;
1394
- if (nextRowIdx !== rowIdx || nextColIdx !== colIdx) {
1395
- setActiveCell(nextRowIdx, nextColIdx, true);
1396
- }
1397
- },
1398
- [columnCount, nextPageItemIdx, rowCount, setActiveCell]
1399
- );
1400
- const handleKeyDown = useCallback11(
1401
- (e) => {
1402
- if (data.length > 0 && isNavigationKey(e.key)) {
1403
- e.preventDefault();
1404
- e.stopPropagation();
1405
- void navigateChildItems(e.key);
1406
- }
1407
- },
1408
- [data, navigateChildItems]
1409
- );
1410
- const handleClick = useCallback11(
1411
- // Might not be a cell e.g the Settings button
1412
- (evt) => {
1413
- const target = evt.target;
1414
- const focusedCell = getFocusedCell(target);
1415
- if (focusedCell) {
1416
- const [rowIdx, colIdx] = getTableCellPos(focusedCell);
1417
- setActiveCell(rowIdx, colIdx);
1418
- }
1419
- },
1420
- [setActiveCell]
1421
- );
1422
- const containerProps = useMemo3(() => {
1423
- return {
1424
- onClick: handleClick,
1425
- onFocus: handleFocus,
1426
- onKeyDown: handleKeyDown
1427
- };
1428
- }, [handleClick, handleFocus, handleKeyDown]);
1429
- useLayoutEffect(() => {
1430
- const { current: cellPos } = activeCellPos;
1431
- const withinViewport = cellPos[0] >= viewportFirstRow && cellPos[0] <= viewportLastRow;
1432
- if (focusableCell.current && !withinViewport) {
1433
- virtualizeActiveCell();
1434
- } else if (!focusableCell.current && withinViewport) {
1435
- focusCell(cellPos);
1436
- }
1437
- }, [focusCell, viewportFirstRow, viewportLastRow, virtualizeActiveCell]);
1438
- const fullyRendered = ((_a = containerRef.current) == null ? void 0 : _a.firstChild) != null;
1439
- useEffect2(() => {
1440
- var _a2;
1441
- if (fullyRendered && focusableCell.current === void 0) {
1442
- const headerCell = (_a2 = containerRef.current) == null ? void 0 : _a2.querySelector(
1443
- headerCellQuery(0)
1444
- );
1445
- if (headerCell) {
1446
- headerCell.setAttribute("tabindex", "0");
1447
- focusableCell.current = headerCell;
1448
- }
1449
- }
1450
- }, [containerRef, fullyRendered]);
1451
- return containerProps;
1452
- };
1453
-
1454
- // src/useMeasuredContainer.ts
1455
- import { useCallback as useCallback13, useRef as useRef10, useState as useState3 } from "react";
1456
-
1457
- // src/useResizeObserver.ts
1458
- import { useCallback as useCallback12, useEffect as useEffect3, useRef as useRef9 } from "react";
1459
- var observedMap = /* @__PURE__ */ new Map();
1460
- var getTargetSize = (element, size, dimension) => {
1461
- switch (dimension) {
1462
- case "height":
1463
- return size.height;
1464
- case "clientHeight":
1465
- return element.clientHeight;
1466
- case "clientWidth":
1467
- return element.clientWidth;
1468
- case "contentHeight":
1469
- return size.contentHeight;
1470
- case "contentWidth":
1471
- return size.contentWidth;
1472
- case "scrollHeight":
1473
- return Math.ceil(element.scrollHeight);
1474
- case "scrollWidth":
1475
- return Math.ceil(element.scrollWidth);
1476
- case "width":
1477
- return size.width;
1478
- default:
1479
- return 0;
1480
- }
1481
- };
1482
- var resizeObserver = new ResizeObserver((entries) => {
1483
- for (const entry of entries) {
1484
- const { target, borderBoxSize, contentBoxSize } = entry;
1485
- const observedTarget = observedMap.get(target);
1486
- if (observedTarget) {
1487
- const [{ blockSize: height, inlineSize: width }] = borderBoxSize;
1488
- const [{ blockSize: contentHeight, inlineSize: contentWidth }] = contentBoxSize;
1489
- const { onResize, measurements } = observedTarget;
1490
- let sizeChanged = false;
1491
- for (const [dimension, size] of Object.entries(measurements)) {
1492
- const newSize = getTargetSize(
1493
- target,
1494
- { height, width, contentHeight, contentWidth },
1495
- dimension
1496
- );
1497
- if (newSize !== size) {
1498
- sizeChanged = true;
1499
- measurements[dimension] = newSize;
1500
- }
1501
- }
1502
- if (sizeChanged) {
1503
- onResize && onResize(measurements);
1504
- }
1505
- }
1506
- }
1507
- });
1508
- function useResizeObserver(ref, dimensions, onResize, reportInitialSize = false) {
1509
- const dimensionsRef = useRef9(dimensions);
1510
- const measure = useCallback12((target) => {
1511
- const { width, height } = target.getBoundingClientRect();
1512
- const { clientWidth: contentWidth, clientHeight: contentHeight } = target;
1513
- return dimensionsRef.current.reduce(
1514
- (map, dim) => {
1515
- map[dim] = getTargetSize(
1516
- target,
1517
- { width, height, contentHeight, contentWidth },
1518
- dim
1519
- );
1520
- return map;
1521
- },
1522
- {}
1523
- );
1524
- }, []);
1525
- useEffect3(() => {
1526
- const target = ref.current;
1527
- async function registerObserver() {
1528
- observedMap.set(target, { measurements: {} });
1529
- await document.fonts.ready;
1530
- const observedTarget = observedMap.get(target);
1531
- if (observedTarget) {
1532
- const measurements = measure(target);
1533
- observedTarget.measurements = measurements;
1534
- resizeObserver.observe(target);
1535
- if (reportInitialSize) {
1536
- onResize(measurements);
1537
- }
1538
- } else {
1539
- console.log(
1540
- `%cuseResizeObserver an target expected to be under observation wa snot found. This warrants investigation`,
1541
- "font-weight:bold; color:red;"
1542
- );
1543
- }
1544
- }
1545
- if (target) {
1546
- if (observedMap.has(target)) {
1547
- throw Error(
1548
- "useResizeObserver attemping to observe same element twice"
1549
- );
1550
- }
1551
- registerObserver();
1552
- }
1553
- return () => {
1554
- if (target && observedMap.has(target)) {
1555
- resizeObserver.unobserve(target);
1556
- observedMap.delete(target);
1557
- }
1558
- };
1559
- }, [measure, ref]);
1560
- useEffect3(() => {
1561
- const target = ref.current;
1562
- const record = observedMap.get(target);
1563
- if (record) {
1564
- if (dimensionsRef.current !== dimensions) {
1565
- dimensionsRef.current = dimensions;
1566
- const measurements = measure(target);
1567
- record.measurements = measurements;
1568
- }
1569
- record.onResize = onResize;
1570
- }
1571
- }, [dimensions, measure, ref, onResize]);
1572
- }
1573
-
1574
- // src/useMeasuredContainer.ts
1575
- var ClientWidthHeight = ["clientHeight", "clientWidth"];
1576
- var isNumber = (val) => Number.isFinite(val);
1577
- var useMeasuredContainer = ({
1578
- defaultHeight = 0,
1579
- defaultWidth = 0,
1580
- height,
1581
- width
1582
- }) => {
1583
- const containerRef = useRef10(null);
1584
- const [size, setSize] = useState3({
1585
- outer: {
1586
- height: height != null ? height : "100%",
1587
- width: width != null ? width : "100%"
1588
- }
1589
- });
1590
- const onResize = useCallback13(
1591
- ({ clientWidth, clientHeight }) => {
1592
- console.log(`Resize ${clientHeight}`);
1593
- setSize((currentSize) => {
1594
- const { inner, outer } = currentSize;
1595
- return isNumber(clientHeight) && isNumber(clientWidth) && (clientWidth !== (inner == null ? void 0 : inner.width) || clientHeight !== (inner == null ? void 0 : inner.height)) ? {
1596
- outer,
1597
- inner: {
1598
- width: Math.floor(clientWidth) || defaultWidth,
1599
- height: Math.floor(clientHeight) || defaultHeight
1600
- }
1601
- } : currentSize;
1602
- });
1603
- },
1604
- [defaultHeight, defaultWidth]
1605
- );
1606
- useResizeObserver(containerRef, ClientWidthHeight, onResize, true);
1607
- return {
1608
- containerRef,
1609
- outerSize: size.outer,
1610
- innerSize: size.inner
1611
- };
1612
- };
1613
-
1614
- // src/useSelection.ts
1615
- import { deselectItem, metadataKeys as metadataKeys6, selectItem } from "@vuu-ui/vuu-utils";
1616
- import { useCallback as useCallback14, useRef as useRef11 } from "react";
1617
- var { IDX: IDX2, SELECTED: SELECTED3 } = metadataKeys6;
1618
- var NO_SELECTION = [];
1619
- var useSelection = ({
1620
- selectionModel,
1621
- onSelectionChange
1622
- }) => {
1623
- selectionModel === "extended" || selectionModel === "checkbox";
1624
- const lastActiveRef = useRef11(-1);
1625
- const selectedRef = useRef11(NO_SELECTION);
1626
- const handleSelectionChange = useCallback14(
1627
- (row, rangeSelect, keepExistingSelection) => {
1628
- const { [IDX2]: idx, [SELECTED3]: isSelected } = row;
1629
- const { current: active } = lastActiveRef;
1630
- const { current: selected } = selectedRef;
1631
- const selectOperation = isSelected ? deselectItem : selectItem;
1632
- const newSelected = selectOperation(
1633
- selectionModel,
1634
- selected,
1635
- idx,
1636
- rangeSelect,
1637
- keepExistingSelection,
1638
- active
1639
- );
1640
- selectedRef.current = newSelected;
1641
- lastActiveRef.current = idx;
1642
- if (onSelectionChange) {
1643
- onSelectionChange(newSelected);
1644
- }
1645
- },
1646
- [onSelectionChange, selectionModel]
1647
- );
1648
- return handleSelectionChange;
1649
- };
1650
-
1651
- // src/useTableModel.ts
1652
- import { moveItem } from "@heswell/salt-lab";
1653
- import {
1654
- applyFilterToColumns,
1655
- applyGroupByToColumns,
1656
- applySortToColumns,
1657
- findColumn,
1658
- getCellRenderer,
1659
- getColumnName,
1660
- getTableHeadings,
1661
- getValueFormatter,
1662
- isFilteredColumn,
1663
- isGroupColumn as isGroupColumn3,
1664
- isPinned,
1665
- isTypeDescriptor,
1666
- logger,
1667
- metadataKeys as metadataKeys7,
1668
- sortPinnedColumns,
1669
- stripFilterFromColumns
1670
- } from "@vuu-ui/vuu-utils";
1671
- import { useReducer } from "react";
1672
- var { info } = logger("useTableModel");
1673
- var DEFAULT_COLUMN_WIDTH = 100;
1674
- var KEY_OFFSET = metadataKeys7.count;
1675
- var columnWithoutDataType = ({ serverDataType }) => serverDataType === void 0;
1676
- var getCellRendererForColumn = (column) => {
1677
- var _a;
1678
- if (isTypeDescriptor(column.type)) {
1679
- return getCellRenderer((_a = column.type) == null ? void 0 : _a.renderer);
1680
- }
1681
- };
1682
- var getDataType = (column, columnNames, dataTypes) => {
1683
- var _a;
1684
- const index = columnNames.indexOf(column.name);
1685
- if (index !== -1 && dataTypes[index]) {
1686
- return dataTypes[index];
1687
- } else {
1688
- return (_a = column.serverDataType) != null ? _a : "string";
1689
- }
1690
- };
1691
- var numericTypes = ["int", "long", "double"];
1692
- var getDefaultAlignment = (serverDataType) => serverDataType === void 0 ? void 0 : numericTypes.includes(serverDataType) ? "right" : "left";
1693
- var columnReducer = (state, action) => {
1694
- info == null ? void 0 : info(`GridModelReducer ${action.type}`);
1695
- switch (action.type) {
1696
- case "init":
1697
- return init(action);
1698
- case "moveColumn":
1699
- return moveColumn(state, action);
1700
- case "resizeColumn":
1701
- return resizeColumn(state, action);
1702
- case "setTypes":
1703
- return setTypes(state, action);
1704
- case "hideColumns":
1705
- return hideColumns(state, action);
1706
- case "showColumns":
1707
- return showColumns(state, action);
1708
- case "pinColumn":
1709
- return pinColumn2(state, action);
1710
- case "updateColumnProp":
1711
- return updateColumnProp(state, action);
1712
- case "tableConfig":
1713
- return updateTableConfig(state, action);
1714
- default:
1715
- console.log(`unhandled action ${action.type}`);
1716
- return state;
1717
- }
1718
- };
1719
- var useTableModel = (tableConfig, dataSourceConfig) => {
1720
- const [state, dispatchColumnAction] = useReducer(columnReducer, { tableConfig, dataSourceConfig }, init);
1721
- return {
1722
- columns: state.columns,
1723
- dispatchColumnAction,
1724
- headings: state.headings
1725
- };
1726
- };
1727
- function init({ dataSourceConfig, tableConfig }) {
1728
- const columns = tableConfig.columns.map(
1729
- toKeyedColumWithDefaults(tableConfig)
1730
- );
1731
- const maybePinnedColumns = columns.some(isPinned) ? sortPinnedColumns(columns) : columns;
1732
- const state = {
1733
- columns: maybePinnedColumns,
1734
- headings: getTableHeadings(maybePinnedColumns)
1735
- };
1736
- if (dataSourceConfig) {
1737
- const { columns: columns2, ...rest } = dataSourceConfig;
1738
- return updateTableConfig(state, {
1739
- type: "tableConfig",
1740
- ...rest
1741
- });
1742
- } else {
1743
- return state;
1744
- }
1745
- }
1746
- var getLabel = (label, columnFormatHeader) => {
1747
- if (columnFormatHeader === "uppercase") {
1748
- return label.toUpperCase();
1749
- } else if (columnFormatHeader === "capitalize") {
1750
- return label[0].toUpperCase() + label.slice(1).toLowerCase();
1751
- }
1752
- return label;
1753
- };
1754
- var toKeyedColumWithDefaults = (options) => (column, index) => {
1755
- const { columnDefaultWidth = DEFAULT_COLUMN_WIDTH, columnFormatHeader } = options;
1756
- const {
1757
- align = getDefaultAlignment(column.serverDataType),
1758
- key,
1759
- name,
1760
- label = name,
1761
- width = columnDefaultWidth,
1762
- ...rest
1763
- } = column;
1764
- const keyedColumnWithDefaults = {
1765
- ...rest,
1766
- align,
1767
- CellRenderer: getCellRendererForColumn(column),
1768
- label: getLabel(label, columnFormatHeader),
1769
- key: key != null ? key : index + KEY_OFFSET,
1770
- name,
1771
- originalIdx: index,
1772
- valueFormatter: getValueFormatter(column),
1773
- width
1774
- };
1775
- if (isGroupColumn3(keyedColumnWithDefaults)) {
1776
- keyedColumnWithDefaults.columns = keyedColumnWithDefaults.columns.map(
1777
- (col) => toKeyedColumWithDefaults(options)(col, col.key)
1778
- );
1779
- }
1780
- return keyedColumnWithDefaults;
1781
- };
1782
- function moveColumn(state, { column, moveBy, moveTo }) {
1783
- const { columns } = state;
1784
- if (typeof moveBy === "number") {
1785
- const idx = columns.indexOf(column);
1786
- const newColumns = columns.slice();
1787
- const [movedColumns] = newColumns.splice(idx, 1);
1788
- newColumns.splice(idx + moveBy, 0, movedColumns);
1789
- return {
1790
- ...state,
1791
- columns: newColumns
1792
- };
1793
- } else if (typeof moveTo === "number") {
1794
- const index = columns.indexOf(column);
1795
- return {
1796
- ...state,
1797
- columns: moveItem(columns, index, moveTo)
1798
- };
1799
- }
1800
- return state;
1801
- }
1802
- function hideColumns(state, { columns }) {
1803
- if (columns.some((col) => col.hidden !== true)) {
1804
- return columns.reduce((s, c) => {
1805
- if (c.hidden !== true) {
1806
- return updateColumnProp(s, {
1807
- type: "updateColumnProp",
1808
- column: c,
1809
- hidden: true
1810
- });
1811
- } else {
1812
- return s;
1813
- }
1814
- }, state);
1815
- } else {
1816
- return state;
1817
- }
1818
- }
1819
- function showColumns(state, { columns }) {
1820
- if (columns.some((col) => col.hidden)) {
1821
- return columns.reduce((s, c) => {
1822
- if (c.hidden) {
1823
- return updateColumnProp(s, {
1824
- type: "updateColumnProp",
1825
- column: c,
1826
- hidden: false
1827
- });
1828
- } else {
1829
- return s;
1830
- }
1831
- }, state);
1832
- } else {
1833
- return state;
1834
- }
1835
- }
1836
- function resizeColumn(state, { column, phase, width }) {
1837
- const type = "updateColumnProp";
1838
- const resizing = phase !== "end";
1839
- switch (phase) {
1840
- case "begin":
1841
- case "end":
1842
- return updateColumnProp(state, { type, column, resizing });
1843
- case "resize":
1844
- return updateColumnProp(state, { type, column, width });
1845
- default:
1846
- throw Error(`useTableModel.resizeColumn, invalid resizePhase ${phase}`);
1847
- }
1848
- }
1849
- function setTypes(state, { columnNames, serverDataTypes }) {
1850
- const { columns } = state;
1851
- if (columns.some(columnWithoutDataType)) {
1852
- const cols = columns.map((column) => {
1853
- var _a;
1854
- const serverDataType = getDataType(column, columnNames, serverDataTypes);
1855
- return {
1856
- ...column,
1857
- align: (_a = column.align) != null ? _a : getDefaultAlignment(serverDataType),
1858
- serverDataType
1859
- };
1860
- });
1861
- return {
1862
- ...state,
1863
- columns: cols
1864
- };
1865
- } else {
1866
- return state;
1867
- }
1868
- }
1869
- function pinColumn2(state, action) {
1870
- let { columns } = state;
1871
- const { column, pin } = action;
1872
- const targetColumn = columns.find((col) => col.name === column.name);
1873
- if (targetColumn) {
1874
- columns = replaceColumn(columns, { ...targetColumn, pin });
1875
- columns = sortPinnedColumns(columns);
1876
- return {
1877
- ...state,
1878
- columns
1879
- };
1880
- } else {
1881
- return state;
1882
- }
1883
- }
1884
- function updateColumnProp(state, action) {
1885
- let { columns } = state;
1886
- const { align, column, hidden, label, resizing, width } = action;
1887
- const targetColumn = columns.find((col) => col.name === column.name);
1888
- if (targetColumn) {
1889
- if (align === "left" || align === "right") {
1890
- columns = replaceColumn(columns, { ...targetColumn, align });
1891
- }
1892
- if (typeof label === "string") {
1893
- columns = replaceColumn(columns, { ...targetColumn, label });
1894
- }
1895
- if (typeof resizing === "boolean") {
1896
- columns = replaceColumn(columns, { ...targetColumn, resizing });
1897
- }
1898
- if (typeof hidden === "boolean") {
1899
- columns = replaceColumn(columns, { ...targetColumn, hidden });
1900
- }
1901
- if (typeof width === "number") {
1902
- columns = replaceColumn(columns, { ...targetColumn, width });
1903
- }
1904
- }
1905
- return {
1906
- ...state,
1907
- columns
1908
- };
1909
- }
1910
- function updateTableConfig(state, { columns, confirmed, filter, groupBy, sort }) {
1911
- const hasColumns = columns && columns.length > 0;
1912
- const hasGroupBy = groupBy !== void 0;
1913
- const hasFilter = typeof (filter == null ? void 0 : filter.filter) === "string";
1914
- const hasSort = sort && sort.sortDefs.length > 0;
1915
- let result = state;
1916
- if (hasColumns) {
1917
- result = {
1918
- ...state,
1919
- columns: columns.map((colName, index) => {
1920
- const columnName = getColumnName(colName);
1921
- const key = index + KEY_OFFSET;
1922
- const col = findColumn(result.columns, columnName);
1923
- if (col) {
1924
- if (col.key === key) {
1925
- return col;
1926
- } else {
1927
- return {
1928
- ...col,
1929
- key
1930
- };
1931
- }
1932
- }
1933
- throw Error(`useTableModel column ${colName} not found`);
1934
- })
1935
- };
1936
- }
1937
- if (hasGroupBy) {
1938
- result = {
1939
- ...state,
1940
- columns: applyGroupByToColumns(result.columns, groupBy, confirmed)
1941
- };
1942
- }
1943
- if (hasSort) {
1944
- result = {
1945
- ...state,
1946
- columns: applySortToColumns(result.columns, sort)
1947
- };
1948
- }
1949
- if (hasFilter) {
1950
- result = {
1951
- ...state,
1952
- columns: applyFilterToColumns(result.columns, filter)
1953
- };
1954
- } else if (result.columns.some(isFilteredColumn)) {
1955
- result = {
1956
- ...state,
1957
- columns: stripFilterFromColumns(result.columns)
1958
- };
1959
- }
1960
- return result;
1961
- }
1962
- function replaceColumn(state, column) {
1963
- return state.map((col) => col.name === column.name ? column : col);
1964
- }
1965
-
1966
- // src/useTableScroll.ts
1967
- import { useCallback as useCallback15, useRef as useRef12 } from "react";
1968
- var getPctScroll = (container) => {
1969
- const { scrollLeft, scrollTop } = container;
1970
- const { clientHeight, clientWidth, scrollHeight, scrollWidth } = container;
1971
- const pctScrollLeft = scrollLeft / (scrollWidth - clientWidth);
1972
- const pctScrollTop = scrollTop / (scrollHeight - clientHeight);
1973
- return [pctScrollLeft, pctScrollTop];
1974
- };
1975
- var getMaxScroll = (container) => {
1976
- const { clientHeight, clientWidth, scrollHeight, scrollWidth } = container;
1977
- return [scrollWidth - clientWidth, scrollHeight - clientHeight];
1978
- };
1979
- var useCallbackRef = ({
1980
- onAttach,
1981
- onDetach
1982
- }) => {
1983
- const ref = useRef12(null);
1984
- const callbackRef = useCallback15(
1985
- (el) => {
1986
- if (el) {
1987
- ref.current = el;
1988
- onAttach == null ? void 0 : onAttach(el);
1989
- } else if (ref.current) {
1990
- const { current: originalRef } = ref;
1991
- ref.current = el;
1992
- onDetach == null ? void 0 : onDetach(originalRef);
1993
- }
1994
- },
1995
- [onAttach, onDetach]
1996
- );
1997
- return callbackRef;
1998
- };
1999
- var useTableScroll = ({
2000
- onHorizontalScroll,
2001
- onVerticalScroll,
2002
- viewport
2003
- }) => {
2004
- const contentContainerScrolledRef = useRef12(false);
2005
- const scrollPosRef = useRef12({ scrollTop: 0, scrollLeft: 0 });
2006
- const scrollbarContainerRef = useRef12(null);
2007
- const contentContainerRef = useRef12(null);
2008
- const {
2009
- maxScrollContainerScrollHorizontal: maxScrollLeft,
2010
- maxScrollContainerScrollVertical: maxScrollTop
2011
- } = viewport;
2012
- const handleScrollbarContainerScroll = useCallback15(() => {
2013
- const { current: contentContainer } = contentContainerRef;
2014
- const { current: scrollbarContainer } = scrollbarContainerRef;
2015
- const { current: contentContainerScrolled } = contentContainerScrolledRef;
2016
- if (contentContainerScrolled) {
2017
- contentContainerScrolledRef.current = false;
2018
- } else if (contentContainer && scrollbarContainer) {
2019
- const [pctScrollLeft, pctScrollTop] = getPctScroll(scrollbarContainer);
2020
- const [maxScrollLeft2, maxScrollTop2] = getMaxScroll(contentContainer);
2021
- const rootScrollLeft = Math.round(pctScrollLeft * maxScrollLeft2);
2022
- const rootScrollTop = Math.round(pctScrollTop * maxScrollTop2);
2023
- contentContainer.scrollTo({
2024
- left: rootScrollLeft,
2025
- top: rootScrollTop,
2026
- behavior: "auto"
2027
- });
2028
- }
2029
- }, []);
2030
- const handleContentContainerScroll = useCallback15(() => {
2031
- const { current: contentContainer } = contentContainerRef;
2032
- const { current: scrollbarContainer } = scrollbarContainerRef;
2033
- const { current: scrollPos } = scrollPosRef;
2034
- if (contentContainer && scrollbarContainer) {
2035
- const { scrollLeft, scrollTop } = contentContainer;
2036
- const [pctScrollLeft, pctScrollTop] = getPctScroll(contentContainer);
2037
- contentContainerScrolledRef.current = true;
2038
- scrollbarContainer.scrollLeft = Math.round(pctScrollLeft * maxScrollLeft);
2039
- scrollbarContainer.scrollTop = Math.round(pctScrollTop * maxScrollTop);
2040
- if (scrollPos.scrollTop !== scrollTop) {
2041
- scrollPos.scrollTop = scrollTop;
2042
- onVerticalScroll == null ? void 0 : onVerticalScroll(scrollTop, pctScrollTop);
2043
- }
2044
- if (scrollPos.scrollLeft !== scrollLeft) {
2045
- scrollPos.scrollLeft = scrollLeft;
2046
- onHorizontalScroll == null ? void 0 : onHorizontalScroll(scrollLeft);
2047
- }
2048
- }
2049
- }, [maxScrollLeft, maxScrollTop, onHorizontalScroll, onVerticalScroll]);
2050
- const handleAttachScrollbarContainer = useCallback15(
2051
- (el) => {
2052
- scrollbarContainerRef.current = el;
2053
- el.addEventListener("scroll", handleScrollbarContainerScroll, {
2054
- passive: true
2055
- });
2056
- },
2057
- [handleScrollbarContainerScroll]
2058
- );
2059
- const handleDetachScrollbarContainer = useCallback15(
2060
- (el) => {
2061
- scrollbarContainerRef.current = null;
2062
- el.removeEventListener("scroll", handleScrollbarContainerScroll);
2063
- },
2064
- [handleScrollbarContainerScroll]
2065
- );
2066
- const handleAttachContentContainer = useCallback15(
2067
- (el) => {
2068
- contentContainerRef.current = el;
2069
- el.addEventListener("scroll", handleContentContainerScroll, {
2070
- passive: true
2071
- });
2072
- },
2073
- [handleContentContainerScroll]
2074
- );
2075
- const handleDetachContentContainer = useCallback15(
2076
- (el) => {
2077
- contentContainerRef.current = null;
2078
- el.removeEventListener("scroll", handleContentContainerScroll);
2079
- },
2080
- [handleContentContainerScroll]
2081
- );
2082
- const contentContainerCallbackRef = useCallbackRef({
2083
- onAttach: handleAttachContentContainer,
2084
- onDetach: handleDetachContentContainer
2085
- });
2086
- const scrollbarContainerCallbackRef = useCallbackRef({
2087
- onAttach: handleAttachScrollbarContainer,
2088
- onDetach: handleDetachScrollbarContainer
2089
- });
2090
- const requestScroll = useCallback15(
2091
- (scrollRequest) => {
2092
- const { current: scrollbarContainer } = contentContainerRef;
2093
- if (scrollbarContainer) {
2094
- contentContainerScrolledRef.current = false;
2095
- if (scrollRequest.type === "scroll-page") {
2096
- const { clientHeight, scrollLeft, scrollTop } = scrollbarContainer;
2097
- const { direction } = scrollRequest;
2098
- const scrollBy = direction === "down" ? clientHeight : -clientHeight;
2099
- const newScrollTop = Math.min(
2100
- Math.max(0, scrollTop + scrollBy),
2101
- maxScrollTop
2102
- );
2103
- scrollbarContainer.scrollTo({
2104
- top: newScrollTop,
2105
- left: scrollLeft,
2106
- behavior: "auto"
2107
- });
2108
- } else if (scrollRequest.type === "scroll-end") {
2109
- const { direction } = scrollRequest;
2110
- const scrollTo = direction === "end" ? maxScrollTop : 0;
2111
- scrollbarContainer.scrollTo({
2112
- top: scrollTo,
2113
- left: scrollbarContainer.scrollLeft,
2114
- behavior: "auto"
2115
- });
2116
- }
2117
- }
2118
- },
2119
- [maxScrollTop]
2120
- );
2121
- return {
2122
- /** Ref to be assigned to ScrollbarContainer */
2123
- scrollbarContainerRef: scrollbarContainerCallbackRef,
2124
- /** Ref to be assigned to ContentContainer */
2125
- contentContainerRef: contentContainerCallbackRef,
2126
- /** Scroll the table */
2127
- requestScroll
2128
- };
2129
- };
2130
-
2131
- // src/useTableViewport.ts
2132
- import { useCallback as useCallback16, useMemo as useMemo4, useRef as useRef13 } from "react";
2133
- import {
2134
- actualRowPositioning,
2135
- virtualRowPositioning
2136
- } from "@vuu-ui/vuu-utils";
2137
- var MAX_RAW_ROWS = 15e5;
2138
- var UNMEASURED_VIEWPORT = {
2139
- contentHeight: 0,
2140
- contentWidth: 0,
2141
- getRowAtPosition: () => -1,
2142
- getRowOffset: () => -1,
2143
- horizontalScrollbarHeight: 0,
2144
- maxScrollContainerScrollHorizontal: 0,
2145
- maxScrollContainerScrollVertical: 0,
2146
- pinnedWidthLeft: 0,
2147
- pinnedWidthRight: 0,
2148
- rowCount: 0,
2149
- setPctScrollTop: () => void 0,
2150
- totalHeaderHeight: 0,
2151
- verticalScrollbarWidth: 0,
2152
- viewportBodyHeight: 0
2153
- };
2154
- var measurePinnedColumns = (columns) => {
2155
- let pinnedWidthLeft = 0;
2156
- let pinnedWidthRight = 0;
2157
- let unpinnedWidth = 0;
2158
- for (const column of columns) {
2159
- const { hidden, pin, width } = column;
2160
- const visibleWidth = hidden ? 0 : width;
2161
- if (pin === "left") {
2162
- pinnedWidthLeft += visibleWidth;
2163
- } else if (pin === "right") {
2164
- pinnedWidthRight += visibleWidth;
2165
- } else {
2166
- unpinnedWidth += visibleWidth;
2167
- }
2168
- }
2169
- return { pinnedWidthLeft, pinnedWidthRight, unpinnedWidth };
2170
- };
2171
- var useTableViewport = ({
2172
- columns,
2173
- headerHeight,
2174
- headings,
2175
- rowCount,
2176
- rowHeight,
2177
- size
2178
- }) => {
2179
- const pctScrollTopRef = useRef13(0);
2180
- const appliedRowCount = Math.min(rowCount, MAX_RAW_ROWS);
2181
- const appliedContentHeight = appliedRowCount * rowHeight;
2182
- const virtualContentHeight = rowCount * rowHeight;
2183
- const virtualisedExtent = virtualContentHeight - appliedContentHeight;
2184
- const { pinnedWidthLeft, pinnedWidthRight, unpinnedWidth } = useMemo4(
2185
- () => measurePinnedColumns(columns),
2186
- [columns]
2187
- );
2188
- const [actualRowOffset, actualRowAtPosition] = useMemo4(
2189
- () => actualRowPositioning(rowHeight),
2190
- [rowHeight]
2191
- );
2192
- const [getRowOffset, getRowAtPosition] = useMemo4(() => {
2193
- if (virtualisedExtent) {
2194
- return virtualRowPositioning(
2195
- rowHeight,
2196
- virtualisedExtent,
2197
- pctScrollTopRef
2198
- );
2199
- } else {
2200
- return [actualRowOffset, actualRowAtPosition];
2201
- }
2202
- }, [actualRowAtPosition, actualRowOffset, virtualisedExtent, rowHeight]);
2203
- const setPctScrollTop = useCallback16((scrollPct) => {
2204
- pctScrollTopRef.current = scrollPct;
2205
- }, []);
2206
- return useMemo4(() => {
2207
- var _a;
2208
- if (size) {
2209
- const headingsDepth = headings.length;
2210
- const scrollbarSize = 15;
2211
- const contentWidth = pinnedWidthLeft + unpinnedWidth + pinnedWidthRight;
2212
- const horizontalScrollbarHeight = contentWidth > size.width ? scrollbarSize : 0;
2213
- const totalHeaderHeight = headerHeight * (1 + headingsDepth);
2214
- const maxScrollContainerScrollVertical = appliedContentHeight - (((_a = size == null ? void 0 : size.height) != null ? _a : 0) - horizontalScrollbarHeight) + totalHeaderHeight;
2215
- const maxScrollContainerScrollHorizontal = contentWidth - size.width + pinnedWidthLeft;
2216
- const visibleRows = (size.height - headerHeight) / rowHeight;
2217
- const count = Number.isInteger(visibleRows) ? visibleRows + 1 : Math.ceil(visibleRows);
2218
- const viewportBodyHeight = size.height - totalHeaderHeight;
2219
- const verticalScrollbarWidth = appliedContentHeight > viewportBodyHeight ? scrollbarSize : 0;
2220
- return {
2221
- contentHeight: appliedContentHeight,
2222
- getRowAtPosition,
2223
- getRowOffset,
2224
- horizontalScrollbarHeight,
2225
- maxScrollContainerScrollHorizontal,
2226
- maxScrollContainerScrollVertical,
2227
- pinnedWidthLeft,
2228
- pinnedWidthRight,
2229
- rowCount: count,
2230
- contentWidth,
2231
- setPctScrollTop,
2232
- totalHeaderHeight,
2233
- verticalScrollbarWidth,
2234
- viewportBodyHeight
2235
- };
2236
- } else {
2237
- return UNMEASURED_VIEWPORT;
2238
- }
2239
- }, [
2240
- size,
2241
- headings.length,
2242
- pinnedWidthLeft,
2243
- unpinnedWidth,
2244
- pinnedWidthRight,
2245
- appliedContentHeight,
2246
- headerHeight,
2247
- rowHeight,
2248
- getRowAtPosition,
2249
- getRowOffset,
2250
- setPctScrollTop
2251
- ]);
2252
- };
2253
-
2254
- // src/useVirtualViewport.ts
2255
- import {
2256
- getColumnsInViewport,
2257
- itemsChanged
2258
- } from "@vuu-ui/vuu-utils";
2259
- import { useCallback as useCallback17, useEffect as useEffect4, useMemo as useMemo5, useRef as useRef14, useState as useState4 } from "react";
2260
- var useVirtualViewport = ({
2261
- columns,
2262
- getRowAtPosition,
2263
- setRange,
2264
- viewportMeasurements
2265
- }) => {
2266
- const firstRowRef = useRef14(-1);
2267
- const {
2268
- rowCount: viewportRowCount,
2269
- contentWidth,
2270
- maxScrollContainerScrollHorizontal
2271
- } = viewportMeasurements;
2272
- const availableWidth = contentWidth - maxScrollContainerScrollHorizontal;
2273
- const scrollLeftRef = useRef14(0);
2274
- const [visibleColumns, preSpan] = useMemo5(
2275
- () => getColumnsInViewport(
2276
- columns,
2277
- scrollLeftRef.current,
2278
- scrollLeftRef.current + availableWidth
2279
- ),
2280
- [availableWidth, columns]
2281
- );
2282
- const preSpanRef = useRef14(preSpan);
2283
- useEffect4(() => {
2284
- setColumnsWithinViewport(visibleColumns);
2285
- }, [visibleColumns]);
2286
- const [columnsWithinViewport, setColumnsWithinViewport] = useState4(visibleColumns);
2287
- const handleHorizontalScroll = useCallback17(
2288
- (scrollLeft) => {
2289
- scrollLeftRef.current = scrollLeft;
2290
- const [visibleColumns2, pre] = getColumnsInViewport(
2291
- columns,
2292
- scrollLeft,
2293
- scrollLeft + availableWidth
2294
- );
2295
- if (itemsChanged(columnsWithinViewport, visibleColumns2)) {
2296
- preSpanRef.current = pre;
2297
- setColumnsWithinViewport(visibleColumns2);
2298
- }
2299
- },
2300
- [availableWidth, columns, columnsWithinViewport]
2301
- );
2302
- const handleVerticalScroll = useCallback17(
2303
- (scrollTop) => {
2304
- const firstRow = getRowAtPosition(scrollTop);
2305
- if (firstRow !== firstRowRef.current) {
2306
- firstRowRef.current = firstRow;
2307
- setRange({ from: firstRow, to: firstRow + viewportRowCount });
2308
- }
2309
- },
2310
- [getRowAtPosition, setRange, viewportRowCount]
2311
- );
2312
- return {
2313
- columnsWithinViewport,
2314
- onHorizontalScroll: handleHorizontalScroll,
2315
- onVerticalScroll: handleVerticalScroll,
2316
- /** number of leading columns not rendered because of virtualization */
2317
- virtualColSpan: preSpanRef.current
2318
- };
2319
- };
2320
-
2321
- // src/useTable.ts
2322
- var NO_ROWS = [];
2323
- var { KEY: KEY2, IS_EXPANDED: IS_EXPANDED2, IS_LEAF: IS_LEAF2 } = metadataKeys8;
2324
- var useTable = ({
2325
- config,
2326
- dataSource,
2327
- headerHeight,
2328
- onConfigChange,
2329
- onFeatureEnabled,
2330
- onFeatureInvocation,
2331
- onSelectionChange,
2332
- renderBufferSize = 0,
2333
- rowHeight,
2334
- selectionModel,
2335
- ...measuredProps
2336
- }) => {
2337
- var _a, _b;
2338
- const [rowCount, setRowCount] = useState5(0);
2339
- const expectConfigChangeRef = useRef15(false);
2340
- const dataSourceRef = useRef15();
2341
- dataSourceRef.current = dataSource;
2342
- if (dataSource === void 0) {
2343
- throw Error("no data source provided to DataTable");
2344
- }
2345
- const containerMeasurements = useMeasuredContainer(measuredProps);
2346
- const onDataRowcountChange = useCallback18((size) => {
2347
- setRowCount(size);
2348
- }, []);
2349
- const { columns, dispatchColumnAction, headings } = useTableModel(
2350
- config,
2351
- dataSource.config
2352
- );
2353
- const handlePersistentColumnOperation = useCallback18(
2354
- (action) => {
2355
- expectConfigChangeRef.current = true;
2356
- dispatchColumnAction(action);
2357
- },
2358
- [dispatchColumnAction]
2359
- );
2360
- const handleContextMenuAction = useContextMenu({
2361
- dataSource,
2362
- onPersistentColumnOperation: handlePersistentColumnOperation
2363
- });
2364
- const {
2365
- getRowAtPosition,
2366
- getRowOffset,
2367
- setPctScrollTop,
2368
- ...viewportMeasurements
2369
- } = useTableViewport({
2370
- columns,
2371
- headerHeight,
2372
- headings,
2373
- rowCount,
2374
- rowHeight,
2375
- size: containerMeasurements.innerSize
2376
- });
2377
- const onSubscribed = useCallback18(
2378
- (subscription) => {
2379
- if (subscription.tableMeta) {
2380
- const { columns: columnNames, dataTypes: serverDataTypes } = subscription.tableMeta;
2381
- expectConfigChangeRef.current = true;
2382
- dispatchColumnAction({
2383
- type: "setTypes",
2384
- columnNames,
2385
- serverDataTypes
2386
- });
2387
- }
2388
- },
2389
- [dispatchColumnAction]
2390
- );
2391
- const handleSelectionChange = useCallback18(
2392
- (selected) => {
2393
- dataSource.select(selected);
2394
- onSelectionChange == null ? void 0 : onSelectionChange(selected);
2395
- },
2396
- [dataSource, onSelectionChange]
2397
- );
2398
- const handleRowClick = useSelection({
2399
- onSelectionChange: handleSelectionChange,
2400
- selectionModel
2401
- });
2402
- const { data, getSelectedRows, range, setRange } = useDataSource({
2403
- dataSource,
2404
- onFeatureEnabled,
2405
- onFeatureInvocation,
2406
- onSubscribed,
2407
- onSizeChange: onDataRowcountChange,
2408
- renderBufferSize,
2409
- viewportRowCount: viewportMeasurements.rowCount
2410
- });
2411
- const dataRef = useRef15();
2412
- dataRef.current = data;
2413
- const handleSort = useCallback18(
2414
- (column, extendSort = false, sortType) => {
2415
- if (dataSource) {
2416
- dataSource.sort = applySort(
2417
- dataSource.sort,
2418
- column,
2419
- extendSort,
2420
- sortType
2421
- );
2422
- }
2423
- },
2424
- [dataSource]
2425
- );
2426
- const handleColumnResize = useCallback18(
2427
- (phase, columnName, width) => {
2428
- const column = columns.find((column2) => column2.name === columnName);
2429
- if (column) {
2430
- if (phase === "end") {
2431
- expectConfigChangeRef.current = true;
2432
- }
2433
- dispatchColumnAction({
2434
- type: "resizeColumn",
2435
- phase,
2436
- column,
2437
- width
2438
- });
2439
- } else {
2440
- throw Error(
2441
- `useDataTable.handleColumnResize, column ${columnName} not found`
2442
- );
2443
- }
2444
- },
2445
- [columns, dispatchColumnAction]
2446
- );
2447
- const handleToggleGroup = useCallback18(
2448
- (row, column) => {
2449
- const isJson = isJsonGroup2(column, row);
2450
- const key = row[KEY2];
2451
- if (row[IS_EXPANDED2]) {
2452
- dataSource.closeTreeNode(key, true);
2453
- if (isJson) {
2454
- const idx = columns.indexOf(column);
2455
- const rows = dataSource.getRowsAtDepth(idx + 1);
2456
- if (!rows.some((row2) => row2[IS_EXPANDED2] || row2[IS_LEAF2])) {
2457
- dispatchColumnAction({
2458
- type: "hideColumns",
2459
- columns: columns.slice(idx + 2)
2460
- });
2461
- }
2462
- }
2463
- } else {
2464
- dataSource.openTreeNode(key);
2465
- if (isJson) {
2466
- const childRows = dataSource.getChildRows(key);
2467
- const idx = columns.indexOf(column) + 1;
2468
- const columnsToShow = [columns[idx]];
2469
- if (childRows.some((row2) => row2[IS_LEAF2])) {
2470
- columnsToShow.push(columns[idx + 1]);
2471
- }
2472
- if (columnsToShow.some((col) => col.hidden)) {
2473
- dispatchColumnAction({
2474
- type: "showColumns",
2475
- columns: columnsToShow
2476
- });
2477
- }
2478
- }
2479
- }
2480
- },
2481
- [columns, dataSource, dispatchColumnAction]
2482
- );
2483
- const {
2484
- onVerticalScroll,
2485
- onHorizontalScroll,
2486
- columnsWithinViewport,
2487
- virtualColSpan
2488
- } = useVirtualViewport({
2489
- columns,
2490
- getRowAtPosition,
2491
- setRange,
2492
- viewportMeasurements
2493
- });
2494
- const handleVerticalScroll = useCallback18(
2495
- (scrollTop, pctScrollTop) => {
2496
- setPctScrollTop(pctScrollTop);
2497
- onVerticalScroll(scrollTop);
2498
- },
2499
- [onVerticalScroll, setPctScrollTop]
2500
- );
2501
- const { requestScroll, ...scrollProps } = useTableScroll({
2502
- onHorizontalScroll,
2503
- onVerticalScroll: handleVerticalScroll,
2504
- viewport: viewportMeasurements,
2505
- viewportHeight: ((_b = (_a = containerMeasurements.innerSize) == null ? void 0 : _a.height) != null ? _b : 0) - headerHeight
2506
- });
2507
- const containerProps = useKeyboardNavigation({
2508
- columnCount: columns.length,
2509
- containerRef: containerMeasurements.containerRef,
2510
- data,
2511
- requestScroll,
2512
- rowCount: dataSource == null ? void 0 : dataSource.size,
2513
- viewportRange: range
2514
- });
2515
- const handleRemoveColumnFromGroupBy = useCallback18(
2516
- (column) => {
2517
- if (column) {
2518
- if (dataSource && dataSource.groupBy.includes(column.name)) {
2519
- dataSource.groupBy = dataSource.groupBy.filter(
2520
- (columnName) => columnName !== column.name
2521
- );
2522
- }
2523
- } else {
2524
- dataSource.groupBy = [];
2525
- }
2526
- },
2527
- [dataSource]
2528
- );
2529
- const handleDropColumn = useCallback18(
2530
- (fromIndex, toIndex) => {
2531
- const column = dataSource.columns[fromIndex];
2532
- const columns2 = moveItem2(dataSource.columns, column, toIndex);
2533
- if (columns2 !== dataSource.columns) {
2534
- dataSource.columns = columns2;
2535
- dispatchColumnAction({ type: "tableConfig", columns: columns2 });
2536
- }
2537
- },
2538
- [dataSource, dispatchColumnAction]
2539
- );
2540
- const draggableHook = useDraggableColumn({
2541
- onDrop: handleDropColumn
2542
- });
2543
- useEffect5(() => {
2544
- if (dataSourceRef.current) {
2545
- expectConfigChangeRef.current = true;
2546
- dispatchColumnAction({
2547
- type: "init",
2548
- tableConfig: config,
2549
- dataSourceConfig: dataSourceRef.current.config
2550
- });
2551
- }
2552
- }, [config, dispatchColumnAction]);
2553
- useEffect5(() => {
2554
- dataSource.on("config", (config2, confirmed) => {
2555
- expectConfigChangeRef.current = true;
2556
- dispatchColumnAction({
2557
- type: "tableConfig",
2558
- ...config2,
2559
- confirmed
2560
- });
2561
- });
2562
- }, [dataSource, dispatchColumnAction]);
2563
- useMemo6(() => {
2564
- if (expectConfigChangeRef.current) {
2565
- onConfigChange == null ? void 0 : onConfigChange({
2566
- ...config,
2567
- columns
2568
- });
2569
- expectConfigChangeRef.current = false;
2570
- }
2571
- }, [columns, config, onConfigChange]);
2572
- const showContextMenu = usePopupContextMenu();
2573
- const onContextMenu = useCallback18(
2574
- (evt) => {
2575
- var _a2;
2576
- const { current: currentData } = dataRef;
2577
- const { current: currentDataSource } = dataSourceRef;
2578
- const target = evt.target;
2579
- const cellEl = target == null ? void 0 : target.closest("div[role='cell']");
2580
- const rowEl = target == null ? void 0 : target.closest(".vuuTableRow");
2581
- if (cellEl && rowEl && currentData && currentDataSource) {
2582
- const { columns: columns2, selectedRowsCount } = currentDataSource;
2583
- const columnMap = buildColumnMap2(columns2);
2584
- const rowIndex = parseInt((_a2 = rowEl.ariaRowIndex) != null ? _a2 : "-1");
2585
- const cellIndex = Array.from(rowEl.childNodes).indexOf(cellEl);
2586
- const row = currentData.find(([idx]) => idx === rowIndex);
2587
- const columnName = columns2[cellIndex];
2588
- showContextMenu(evt, "grid", {
2589
- columnMap,
2590
- columnName,
2591
- row,
2592
- selectedRows: selectedRowsCount === 0 ? NO_ROWS : getSelectedRows(),
2593
- viewport: dataSource == null ? void 0 : dataSource.viewport
2594
- });
2595
- }
2596
- },
2597
- [dataSource == null ? void 0 : dataSource.viewport, getSelectedRows, showContextMenu]
2598
- );
2599
- return {
2600
- containerMeasurements,
2601
- containerProps,
2602
- columns,
2603
- columnsWithinViewport,
2604
- data,
2605
- dispatchColumnAction,
2606
- getRowOffset,
2607
- handleContextMenuAction,
2608
- headings,
2609
- onColumnResize: handleColumnResize,
2610
- onContextMenu,
2611
- onRemoveColumnFromGroupBy: handleRemoveColumnFromGroupBy,
2612
- onRowClick: handleRowClick,
2613
- onSort: handleSort,
2614
- onToggleGroup: handleToggleGroup,
2615
- virtualColSpan,
2616
- scrollProps,
2617
- rowCount,
2618
- viewportMeasurements,
2619
- ...draggableHook
2620
- };
2621
- };
2622
-
2623
- // src/Table.tsx
2624
- import cx7 from "classnames";
2625
- import { isDataLoading } from "@vuu-ui/vuu-utils";
2626
- import { jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
2627
- var classBase6 = "vuuTable";
2628
- var Table = ({
2629
- allowConfigEditing: showSettings = false,
2630
- className: classNameProp,
2631
- config,
2632
- dataSource,
2633
- headerHeight = 25,
2634
- height,
2635
- id: idProp,
2636
- onConfigChange,
2637
- onFeatureEnabled,
2638
- onFeatureInvocation,
2639
- onSelectionChange,
2640
- onShowConfigEditor: onShowSettings,
2641
- renderBufferSize = 0,
2642
- rowHeight = 20,
2643
- selectionModel = "extended",
2644
- style: styleProp,
2645
- width,
2646
- zebraStripes = false,
2647
- ...props
2648
- }) => {
2649
- const id = useIdMemo(idProp);
2650
- const {
2651
- containerMeasurements: { containerRef, innerSize, outerSize },
2652
- containerProps,
2653
- dispatchColumnAction,
2654
- draggable,
2655
- draggedItemIndex,
2656
- handleContextMenuAction,
2657
- scrollProps,
2658
- viewportMeasurements,
2659
- ...tableProps
2660
- } = useTable({
2661
- config,
2662
- dataSource,
2663
- renderBufferSize,
2664
- headerHeight,
2665
- height,
2666
- onConfigChange,
2667
- onFeatureEnabled,
2668
- onFeatureInvocation,
2669
- onSelectionChange,
2670
- rowHeight,
2671
- selectionModel,
2672
- width
2673
- });
2674
- const style = {
2675
- ...outerSize,
2676
- "--content-height": `${viewportMeasurements.contentHeight}px`,
2677
- "--horizontal-scrollbar-height": `${viewportMeasurements.horizontalScrollbarHeight}px`,
2678
- "--content-width": `${viewportMeasurements.contentWidth}px`,
2679
- "--pinned-width-left": `${viewportMeasurements.pinnedWidthLeft}px`,
2680
- "--pinned-width-right": `${viewportMeasurements.pinnedWidthRight}px`,
2681
- "--header-height": `${headerHeight}px`,
2682
- "--row-height": `${rowHeight}px`,
2683
- "--table-height": `${innerSize == null ? void 0 : innerSize.height}px`,
2684
- "--table-width": `${innerSize == null ? void 0 : innerSize.width}px`,
2685
- "--total-header-height": `${viewportMeasurements.totalHeaderHeight}px`,
2686
- "--vertical-scrollbar-width": `${viewportMeasurements.verticalScrollbarWidth}px`,
2687
- "--viewport-body-height": `${viewportMeasurements.viewportBodyHeight}px`
2688
- };
2689
- const className = cx7(classBase6, classNameProp, {
2690
- [`${classBase6}-zebra`]: zebraStripes,
2691
- [`${classBase6}-loading`]: isDataLoading(tableProps.columns)
2692
- });
2693
- return /* @__PURE__ */ jsx10(
2694
- ContextMenuProvider,
2695
- {
2696
- menuActionHandler: handleContextMenuAction,
2697
- menuBuilder: buildContextMenuDescriptors(dataSource),
2698
- children: /* @__PURE__ */ jsxs7(
2699
- "div",
2700
- {
2701
- ...props,
2702
- ...containerProps,
2703
- className,
2704
- id,
2705
- ref: containerRef,
2706
- style,
2707
- tabIndex: -1,
2708
- children: [
2709
- innerSize ? /* @__PURE__ */ jsx10(
2710
- "div",
2711
- {
2712
- className: `${classBase6}-scrollbarContainer`,
2713
- ref: scrollProps.scrollbarContainerRef,
2714
- children: /* @__PURE__ */ jsx10("div", { className: `${classBase6}-scrollbarContent` })
2715
- }
2716
- ) : null,
2717
- innerSize ? /* @__PURE__ */ jsxs7(
2718
- "div",
2719
- {
2720
- className: `${classBase6}-contentContainer`,
2721
- ref: scrollProps.contentContainerRef,
2722
- children: [
2723
- /* @__PURE__ */ jsx10(
2724
- RowBasedTable,
2725
- {
2726
- ...tableProps,
2727
- headerHeight,
2728
- tableId: id
2729
- }
2730
- ),
2731
- draggable
2732
- ]
2733
- }
2734
- ) : null,
2735
- showSettings && innerSize ? /* @__PURE__ */ jsx10(
2736
- Button,
2737
- {
2738
- className: `${classBase6}-settings`,
2739
- "data-icon": "settings",
2740
- onClick: onShowSettings,
2741
- variant: "secondary"
2742
- }
2743
- ) : null
2744
- ]
2745
- }
2746
- )
2747
- }
2748
- );
2749
- };
2750
-
2751
- // src/cell-renderers/json-cell/JsonCell.tsx
2752
- import cx8 from "classnames";
2753
- import {
2754
- isJsonAttribute,
2755
- metadataKeys as metadataKeys9,
2756
- registerComponent
2757
- } from "@vuu-ui/vuu-utils";
2758
- import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
2759
- var classBase7 = "vuuJsonCell";
2760
- var { IS_EXPANDED: IS_EXPANDED3, KEY: KEY3 } = metadataKeys9;
2761
- var localKey = (key) => {
2762
- const pos = key.lastIndexOf("|");
2763
- if (pos === -1) {
2764
- return "";
2765
- } else {
2766
- return key.slice(pos + 1);
2767
- }
2768
- };
2769
- var JsonCell = ({ column, row }) => {
2770
- const {
2771
- key: columnKey
2772
- /*, type, valueFormatter */
2773
- } = column;
2774
- let value = row[columnKey];
2775
- let isToggle = false;
2776
- if (isJsonAttribute(value)) {
2777
- value = value.slice(0, -1);
2778
- isToggle = true;
2779
- }
2780
- const rowKey = localKey(row[KEY3]);
2781
- const className = cx8({
2782
- [`${classBase7}-name`]: rowKey === value,
2783
- [`${classBase7}-value`]: rowKey !== value,
2784
- [`${classBase7}-group`]: isToggle
2785
- });
2786
- if (isToggle) {
2787
- const toggleIcon = row[IS_EXPANDED3] ? "minus-box" : "plus-box";
2788
- return /* @__PURE__ */ jsxs8("span", { className, children: [
2789
- /* @__PURE__ */ jsx11("span", { className: `${classBase7}-value`, children: value }),
2790
- /* @__PURE__ */ jsx11("span", { className: `${classBase7}-toggle`, "data-icon": toggleIcon })
2791
- ] });
2792
- } else if (value) {
2793
- return /* @__PURE__ */ jsx11("span", { className, children: value });
2794
- } else {
2795
- return null;
2796
- }
2797
- };
2798
- registerComponent("json", JsonCell, "cell-renderer", {});
2799
- export {
2800
- Table,
2801
- useMeasuredContainer
2802
- };
1
+ import{ContextMenuProvider as os}from"@vuu-ui/vuu-popups";import{Button as rs,useIdMemo as ss}from"@salt-ds/core";import{isNumericColumn as Mn}from"@vuu-ui/vuu-utils";var Ge=e=>(t,n)=>{let o=[];if(e===void 0)return o;if(t==="header")o.push(...Rn(n,e)),o.push(...xn(n,e)),o.push(...Tn(n,e)),o.push(...Dn(n));else if(t==="filter"){let{column:r,filter:i}=n,s=(i==null?void 0:i.column)===(r==null?void 0:r.name);o.push({label:"Edit filter",action:"filter-edit",options:n}),o.push({label:"Remove filter",action:"filter-remove-column",options:n}),r&&!s&&o.push({label:"Remove all filters",action:"remove-filters",options:n})}return o};function Rn(e,{sort:{sortDefs:t}}){let{column:n}=e,o=[];if(n===void 0)return o;let r=t.length>0;return n.sorted==="A"?o.push({label:"Reverse Sort (DSC)",action:"sort-dsc",options:e}):n.sorted==="D"?o.push({label:"Reverse Sort (ASC)",action:"sort-asc",options:e}):typeof n.sorted=="number"?(n.sorted>0?o.push({label:"Reverse Sort (DSC)",action:"sort-add-dsc",options:e}):o.push({label:"Reverse Sort (ASC)",action:"sort-add-asc",options:e}),r&&Math.abs(n.sorted)<t.length&&o.push({label:"Remove from sort",action:"sort-remove",options:e}),o.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]})):r?(o.push({label:"Add to sort",children:[{label:"Ascending",action:"sort-add-asc",options:e},{label:"Descending",action:"sort-add-dsc",options:e}]}),o.push({label:"New Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]})):o.push({label:"Sort",children:[{label:"Ascending",action:"sort-asc",options:e},{label:"Descending",action:"sort-dsc",options:e}]}),o}function Tn(e,t){let{column:n}=e;if(n===void 0||t.groupBy.length===0)return[];let{name:o,label:r=o}=n;return[{label:`Aggregate ${r}`,children:[{label:"Count",action:"agg-count",options:e}].concat(Mn(n)?[{label:"Sum",action:"agg-sum",options:e},{label:"Avg",action:"agg-avg",options:e},{label:"High",action:"agg-high",options:e},{label:"Low",action:"agg-low",options:e}]:[])}]}var Ce=(e,t)=>({label:`Pin ${t}`,action:`column-pin-${t}`,options:e}),pe=e=>Ce(e,"left"),fe=e=>Ce(e,"floating"),ge=e=>Ce(e,"right");function Dn(e){let{column:t}=e;if(t===void 0)return[];let{pin:n}=t,o=[{label:"Hide column",action:"column-hide",options:e},{label:"Remove column",action:"column-remove",options:e}];return n===void 0?o.push({label:"Pin column",children:[pe(e),fe(e),ge(e)]}):n==="left"?o.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[fe(e),ge(e)]}):n==="right"?o.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[pe(e),fe(e)]}):n==="floating"&&o.push({label:"Unpin column",action:"column-unpin",options:e},{label:"Pin column",children:[pe(e),ge(e)]}),o}function xn(e,{groupBy:t}){let{column:n}=e,o=[];if(n===void 0)return o;let{name:r,label:i=r}=n;return t.length===0?o.push({label:`Group by ${i}`,action:"group",options:e}):o.push({label:`Add ${i} to group by`,action:"group-add",options:e}),o}import{removeColumnFromFilter as Hn}from"@vuu-ui/vuu-filters";import{addGroupColumn as Be,addSortColumn as Ue,AggregationType as Pn,setAggregations as Q,setSortColumn as _e}from"@vuu-ui/vuu-utils";var En=(e,t)=>{if(e.filterStruct&&t){let[n,o]=Hn(t,e.filterStruct);return{filter:o,filterStruct:n}}else return e},{Average:Sn,Count:An,High:Ln,Low:kn,Sum:Kn}=Pn,Je=({dataSource:e,onPersistentColumnOperation:t})=>(o,r)=>{let i=r;if(i.column&&e){let{column:s}=i;switch(o){case"sort-asc":return e.sort=_e(e.sort,s,"A"),!0;case"sort-dsc":return e.sort=_e(e.sort,s,"D"),!0;case"sort-add-asc":return e.sort=Ue(e.sort,s,"A"),!0;case"sort-add-dsc":return e.sort=Ue(e.sort,s,"D"),!0;case"group":return e.groupBy=Be(e.groupBy,s),!0;case"group-add":return e.groupBy=Be(e.groupBy,s),!0;case"column-hide":return t({type:"hideColumns",columns:[s]}),!0;case"column-remove":return e.columns=e.columns.filter(l=>l!==s.name),!0;case"filter-remove-column":return e.filter=En(e.filter,s),!0;case"remove-filters":return e.filter={filter:""},!0;case"agg-avg":return e.aggregations=Q(e.aggregations,s,Sn),!0;case"agg-high":return e.aggregations=Q(e.aggregations,s,Ln),!0;case"agg-low":return e.aggregations=Q(e.aggregations,s,kn),!0;case"agg-count":return e.aggregations=Q(e.aggregations,s,An),!0;case"agg-sum":return e.aggregations=Q(e.aggregations,s,Kn),!0;case"column-pin-floating":return t({type:"pinColumn",column:s,pin:"floating"}),!0;case"column-pin-left":return t({type:"pinColumn",column:s,pin:"left"}),!0;case"column-pin-right":return t({type:"pinColumn",column:s,pin:"right"}),!0;case"column-unpin":return t({type:"pinColumn",column:s,pin:void 0}),!0;default:}}return!1};import{buildColumnMap as vo,getColumnStyle as yo,isGroupColumn as wo,metadataKeys as Mo,notHidden as Ro,visibleColumnAtIndex as To}from"@vuu-ui/vuu-utils";import{useCallback as ft,useMemo as gt}from"react";import{isGroupColumn as Ze,isJsonColumn as Yn,isJsonGroup as Qn,metadataKeys as jn,notHidden as Zn}from"@vuu-ui/vuu-utils";import qn from"classnames";import{memo as eo,useCallback as qe}from"react";import{getColumnStyle as zn,metadataKeys as Nn}from"@vuu-ui/vuu-utils";import{EditableLabel as Fn}from"@heswell/salt-lab";import Vn from"classnames";import{memo as In,useCallback as Wn,useRef as On,useState as Xe}from"react";import{jsx as se}from"react/jsx-runtime";var{KEY:Ye}=Nn,be=In(({className:e,column:t,columnMap:n,onClick:o,row:r})=>{let i=On(null),{align:s,CellRenderer:l,key:a,pin:u,editable:c,resizing:d,valueFormatter:p}=t,[h,b]=Xe(!1),g=p(r[a]),[D,y]=Xe(g),m=()=>{var P;(P=i.current)==null||P.focus()},C=P=>{P.key==="Enter"&&b(!0)},T=Wn(()=>{o==null||o(t)},[t,o]),w=()=>{b(!0)},v=(P="",f="",M=!0,E=!1)=>{var R;b(!1),E?y(P):f!==P&&y(f),M===!1&&((R=i.current)==null||R.focus())},H=Vn(e,{vuuAlignRight:s==="right",vuuPinFloating:u==="floating",vuuPinLeft:u==="left",vuuPinRight:u==="right","vuuTableCell-resizing":d})||void 0,S=zn(t);return c?se("div",{className:H,"data-editable":!0,role:"cell",style:S,onKeyDown:C,children:se(Fn,{editing:h,value:D,onChange:y,onMouseDownCapture:m,onEnterEditMode:w,onExitEditMode:v,onKeyDown:C,ref:i,tabIndex:0},"title")}):se("div",{className:H,role:"cell",style:S,onClick:T,children:l?se(l,{column:t,columnMap:n,row:r}):g})},$n);be.displayName="TableCell";function $n(e,t){return e.column===t.column&&e.onClick===t.onClick&&e.row[Ye]===t.row[Ye]&&e.row[e.column.key]===t.row[t.column.key]}import{getColumnStyle as Gn,metadataKeys as Bn}from"@vuu-ui/vuu-utils";import{useCallback as Un}from"react";import{jsx as he,jsxs as Xn}from"react/jsx-runtime";var{DEPTH:_n,IS_LEAF:Qe}=Bn,Jn=(e,t)=>{let{[_n]:n,[Qe]:o}=t;if(o||n>e.length)return[null,n===null?0:n-1];if(n===0)return["$root",0];{let{key:r,valueFormatter:i}=e[n-1];return[i(t[r]),n-1]}},je=({column:e,onClick:t,row:n})=>{let{columns:o}=e,[r,i]=Jn(o,n),s=Un(()=>{t==null||t(e)},[e,t]),l=Gn(e),a=n[Qe],u=Array(i).fill(0).map((c,d)=>he("span",{className:"vuuTableGroupCell-spacer"},d));return Xn("div",{className:"vuuTableGroupCell vuuPinLeft",onClick:a?void 0:s,role:"cell",style:l,children:[u,a?null:he("span",{className:"vuuTableGroupCell-toggle","data-icon":"triangle-right"}),he("span",{children:r})]})};import{jsx as et,jsxs as ro}from"react/jsx-runtime";var{IDX:to,IS_EXPANDED:no,SELECTED:oo}=jn,ie="vuuTableRow",tt=eo(function({columnMap:t,columns:n,offset:o,onClick:r,onToggleGroup:i,virtualColSpan:s=0,row:l}){let{[to]:a,[no]:u,[oo]:c}=l,d=qn(ie,{[`${ie}-even`]:a%2===0,[`${ie}-expanded`]:u,[`${ie}-preSelected`]:c===2}),p=qe(b=>{let g=b.shiftKey,D=b.ctrlKey||b.metaKey;r==null||r(l,g,D)},[r,l]),h=qe(b=>{(Ze(b)||Qn(b,l))&&(i==null||i(l,b))},[i,l]);return ro("div",{"aria-selected":c===1?!0:void 0,"aria-rowindex":a,className:d,onClick:p,role:"row",style:{transform:`translate3d(0px, ${o}px, 0px)`},children:[s>0?et("div",{role:"cell",style:{width:s}}):null,n.filter(Zn).map(b=>{let g=Ze(b),D=Yn(b);return et(g?je:be,{column:b,columnMap:t,onClick:g||D?h:void 0,row:l},b.name)})]})});import st from"classnames";import{useRef as ao}from"react";import{useCallback as ve,useRef as so}from"react";import{jsx as lo}from"react/jsx-runtime";var nt=()=>{},io="vuuColumnResizer",le=({onDrag:e,onDragEnd:t=nt,onDragStart:n=nt})=>{let o=so(0),r=ve(l=>{l.stopPropagation&&l.stopPropagation(),l.preventDefault&&l.preventDefault();let a=Math.round(l.clientX),u=a-o.current;o.current=a,u!==0&&e(l,u)},[e]),i=ve(l=>{window.removeEventListener("mouseup",i),window.removeEventListener("mousemove",r),t(l)},[t,r]),s=ve(l=>{n(l),o.current=Math.round(l.clientX),window.addEventListener("mouseup",i),window.addEventListener("mousemove",r),l.stopPropagation&&l.stopPropagation(),l.preventDefault&&l.preventDefault()},[n,r,i]);return lo("div",{className:io,"data-align":"end",onMouseDown:s})};import{useCallback as ye,useRef as ot}from"react";var ae=({column:e,onResize:t,rootRef:n})=>{let o=ot(0),r=ot(!1),{name:i}=e,s=ye(()=>{if(t&&n.current){let{width:u}=n.current.getBoundingClientRect();o.current=Math.round(u),r.current=!0,t==null||t("begin",i)}},[i,t,n]),l=ye((u,c)=>{if(n.current&&t){let{width:d}=n.current.getBoundingClientRect(),p=Math.round(d)+c;p!==o.current&&p>0&&(t("resize",i,p),o.current=p)}},[i,t,n]),a=ye(()=>{t&&(t("end",i,o.current),setTimeout(()=>{r.current=!1},100))},[i,t]);return{isResizing:r.current,onDrag:l,onDragStart:s,onDragEnd:a}};import{jsx as $,jsxs as lt}from"react/jsx-runtime";var I="vuuTable-groupHeaderCell",rt=({column:e,onClick:t,...n})=>$("span",{...n,className:`${I}-close`,"data-icon":"close-circle",onClick:()=>t==null?void 0:t(e)}),co=e=>{let{children:t,column:n,className:o}=e;return lt("div",{className:st(`${I}-col`,o),role:"columnheader",children:[$("span",{className:`${I}-label`,children:n.name}),t]})},it=({column:e,className:t,onRemoveColumn:n,onResize:o,...r})=>{let i=ao(null),{isResizing:s,...l}=ae({column:e,onResize:o,rootRef:i}),a=st(I,t,{vuuPinLeft:e.pin==="left",[`${I}-right`]:e.align==="right",[`${I}-resizing`]:e.resizing,[`${I}-pending`]:e.groupConfirmed===!1}),{columns:u}=e;return $("div",{className:a,ref:i,...r,children:lt("div",{className:`${I}-inner`,children:[u.map(c=>$(co,{column:c,children:u.length>1?$(rt,{column:c,onClick:n}):null},c.key)),$(rt,{"data-align":"end",onClick:n}),e.resizeable!==!1?$(le,{...l}):null]})})};import Co from"classnames";import{useCallback as we,useRef as dt}from"react";import at from"classnames";import{jsx as ce,jsxs as uo}from"react/jsx-runtime";var ct="vuuSortIndicator",ut=({sorted:e})=>{if(!e)return null;let t=typeof e=="number"?e<0?"dsc":"asc":e==="A"?"asc":"dsc";return typeof e=="number"?uo("div",{className:at(ct,"multi-col",t),children:[ce("span",{"data-icon":`sorted-${t}`}),ce("span",{className:"vuuSortPosition",children:Math.abs(e)})]}):ce("div",{className:at(ct,"single-col"),children:ce("span",{"data-icon":`sorted-${t}`})})};import{useContextMenu as bo}from"@vuu-ui/vuu-popups";import{useContextMenu as mo}from"@vuu-ui/vuu-popups";import po from"classnames";import{useCallback as fo}from"react";import{jsx as go}from"react/jsx-runtime";var mt=({column:e,filter:t})=>{let n=mo(),o=fo(r=>{r.stopPropagation(),n(r,"filter",{column:e,filter:t})},[e,t,n]);return e.filter?go("div",{className:po("vuuFilterIndicator"),"data-icon":"filter",onClick:o}):null};import{jsx as Z,jsxs as ho}from"react/jsx-runtime";var j="vuuTable-headerCell",pt=({column:e,className:t,onClick:n,onDragStart:o,onResize:r,...i})=>{let s=dt(null),{isResizing:l,...a}=ae({column:e,onResize:r,rootRef:s}),u=bo(),c=dt(null),d=D=>{u(D,"header",{column:e})},p=we(D=>!l&&(n==null?void 0:n(D)),[l,n]),h=we(D=>{c.current=window.setTimeout(()=>{o==null||o(D),c.current=null},500)},[o]),b=we(()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},[]),g=Co(j,t,{vuuPinFloating:e.pin==="floating",vuuPinLeft:e.pin==="left",vuuPinRight:e.pin==="right",vuuEndPin:e.endPin,[`${j}-resizing`]:e.resizing,[`${j}-right`]:e.align==="right"});return Z("div",{className:g,...i,onClick:p,onContextMenu:d,onMouseDown:h,onMouseUp:b,ref:s,children:ho("div",{className:`${j}-inner`,children:[Z(mt,{column:e}),Z("div",{className:`${j}-label`,children:e.label}),Z(ut,{sorted:e.sorted}),e.resizeable!==!1?Z(le,{...a}):null]})})};import{jsx as G,jsxs as Ct}from"react/jsx-runtime";var Me="vuuTable",{RENDER_IDX:Do}=Mo,bt=({columns:e,columnsWithinViewport:t,data:n,getRowOffset:o,headings:r,onColumnResize:i,onHeaderCellDragStart:s,onContextMenu:l,onRemoveColumnFromGroupBy:a,onRowClick:u,onSort:c,onToggleGroup:d,tableId:p,virtualColSpan:h=0,rowCount:b})=>{let g=ft(C=>{s==null||s(C)},[s]),D=gt(()=>e.filter(Ro),[e]),y=gt(()=>vo(e),[e]),m=ft(C=>{var P;let w=C.target.closest(".vuuTable-headerCell"),v=parseInt((P=w==null?void 0:w.dataset.idx)!=null?P:"-1"),H=To(e,v),S=C.shiftKey;H&&c(H,S)},[e,c]);return Ct("div",{"aria-rowcount":b,className:`${Me}-table`,role:"table",children:[Ct("div",{className:`${Me}-headers`,role:"rowGroup",children:[r.map((C,T)=>G("div",{className:"vuuTable-heading",children:C.map(({label:w,width:v},H)=>G("div",{className:"vuuTable-headingCell",style:{width:v},children:w},H))},T)),G("div",{role:"row",children:D.map((C,T)=>{let w=yo(C);return wo(C)?G(it,{column:C,"data-idx":T,onRemoveColumn:a,onResize:i,role:"columnHeader",style:w},T):G(pt,{column:C,"data-idx":T,id:`${p}-${T}`,onClick:m,onDragStart:g,onResize:i,role:"columnHeader",style:w},T)})})]}),G("div",{className:`${Me}-body`,onContextMenu:l,role:"rowGroup",children:n==null?void 0:n.map(C=>G(tt,{columnMap:y,columns:t,offset:o(C),onClick:u,virtualColSpan:h,onToggleGroup:d,row:C},C[Do]))})]})};import{useContextMenu as Jr}from"@vuu-ui/vuu-popups";import{applySort as Xr,buildColumnMap as Yr,isJsonGroup as Qr,metadataKeys as jr,moveItem as Zr}from"@vuu-ui/vuu-utils";import{useCallback as z,useEffect as Yt,useMemo as qr,useRef as Ne,useState as es}from"react";import{isVuuFeatureAction as xo,isVuuFeatureInvocation as Ho}from"@vuu-ui/vuu-data";import{getFullRange as Re,metadataKeys as Po,WindowRange as Eo}from"@vuu-ui/vuu-utils";import{useCallback as J,useEffect as ue,useMemo as So,useRef as q,useState as Ao}from"react";var{SELECTED:ee}=Po;function ht({dataSource:e,onConfigChange:t,onFeatureEnabled:n,onFeatureInvocation:o,onSizeChange:r,onSubscribed:i,range:s={from:0,to:0},renderBufferSize:l=0,viewportRowCount:a}){let[,u]=Ao(null),c=q(!0),d=q(!1),p=q({from:0,to:0}),h=q(null),b=q([]),g=So(()=>new Te(Re(s)),[]),D=J(v=>{for(let H of v)g.add(H);b.current=g.data,d.current=!0},[g]),y=J(v=>{v.type==="subscribed"?i==null||i(v):v.type==="viewport-update"?(typeof v.size=="number"&&(r==null||r(v.size),g.setRowCount(v.size)),v.rows?D(v.rows):typeof v.size=="number"&&(b.current=g.data,d.current=!0)):xo(v)?n==null||n(v):Ho(v)?o==null||o(v):console.log(`useDataSource unexpected message ${v.type}`)},[g,n,o,r,i,D]);ue(()=>()=>{h.current&&(cancelAnimationFrame(h.current),h.current=null),c.current=!1},[]);let m=J(()=>{c.current&&(d.current&&(u({}),d.current=!1),h.current=requestAnimationFrame(m))},[u]);ue(()=>{h.current=requestAnimationFrame(m)},[m]);let C=J(v=>{let{from:H}=e.range,S={from:H,to:H+v},P=Re(S,l);g.setRange(P),e.range=p.current=P,e.emit("range",S)},[e,g,l]),T=J(v=>{let H=Re(v,l);g.setRange(H),e.range=p.current=H,e.emit("range",v)},[e,g,l]),w=J(()=>g.getSelectedRows(),[g]);return ue(()=>{e==null||e.subscribe({range:p.current},y)},[e,y,t]),ue(()=>{C(a)},[C,a]),{data:b.current,getSelectedRows:w,range:p.current,setRange:T,dataSource:e}}var Te=class{constructor({from:t,to:n}){this.rowCount=0;this.setRowCount=t=>{t<this.data.length&&(this.data.length=t),this.rowCount=t};this.range=new Eo(t,n),this.data=new Array(n-t),this.rowCount=0}add(t){var o;let[n]=t;if(this.isWithinRange(n)){let r=n-this.range.from;this.data[r]=t;let i=t[ee],s=(o=this.data[r-1])==null?void 0:o[ee];s===0&&i?this.data[r-1][ee]=2:s===2&&!i&&(this.data[r-1][ee]=0)}}getAtIndex(t){return this.range.isWithin(t)&&this.data[t-this.range.from]!=null?this.data[t-this.range.from]:void 0}isWithinRange(t){return this.range.isWithin(t)}setRange({from:t,to:n}){if(t!==this.range.from||n!==this.range.to){let[o,r]=this.range.overlap(t,n),i=new Array(Math.max(0,n-t));for(let s=o;s<r;s++){let l=this.getAtIndex(s);if(l){let a=s-t;i[a]=l}}this.data=i,this.range.from=t,this.range.to=n}}getSelectedRows(){return this.data.filter(t=>t[ee]===1)}};import{useDragDrop as Lo}from"@heswell/salt-lab";import{useCallback as vt,useRef as yt}from"react";var wt=({onDrop:e})=>{let t=yt(),n=yt(null),o=vt(()=>{console.log("handleDropSettle"),t.current=void 0,n.current=null},[]),{draggable:r,draggedItemIndex:i,onMouseDown:s}=Lo({allowDragDrop:!0,draggableClassName:"vuuTable-headerCell",orientation:"horizontal",containerRef:n,itemQuery:".vuuTable-headerCell",onDrop:e,onDropSettle:o}),l=vt(a=>{let{clientX:u,clientY:c}=a;console.log("useDraggableColumn handleHeaderCellDragStart means mouseDown fired on a column in RowBasedTable");let p=a.target.closest(".vuuTable-headerCell");n.current=p==null?void 0:p.closest("[role='row']");let{dataset:{idx:h="-1"}}=p;t.current={clientX:u,clientY:c,idx:h},s==null||s(a)},[s]);return{draggable:r,draggedItemIndex:i,onHeaderCellDragStart:l}};import{withinRange as Io}from"@vuu-ui/vuu-utils";import{useCallback as V,useEffect as Wo,useLayoutEffect as Oo,useMemo as $o,useRef as ke}from"react";function ko(e,...t){let n=new Set(e);for(let o of t)for(let r of o)n.add(r);return n}var De="ArrowUp",xe="ArrowDown",He="ArrowLeft",Pe="ArrowRight";var Ee="Home",Se="End",Ae="PageUp",Le="PageDown";var Ko=new Set(["Enter","Delete"," "]),zo=new Set(["Tab"]),No=new Set(["ArrowRight","ArrowLeft"]),Mt=new Set([Ee,Se,Ae,Le,xe,He,Pe,De]),Fo=new Set(["F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"]),wl=ko(Ko,Mt,No,Fo,zo);var Vo=["Home","End","PageUp","PageDown"],Rt=e=>Vo.includes(e),Tt=e=>Mt.has(e);var Dt=e=>`.vuuTable-headers .vuuTable-headerCell:nth-child(${e+1})`,Go=(e,t)=>`.vuuTable-body > [aria-rowindex='${e}'] > [role='cell']:nth-child(${t+1})`,Bo=[-1,-1];function Uo(e,[t,n],o,r){return e===De?t>-1?[t-1,n]:[t,n]:e===xe?t===-1?[0,n]:t===r-1?[t,n]:[t+1,n]:e===Pe?n<o-1?[t,n+1]:[t,n]:e===He?n>0?[t,n-1]:[t,n]:[t,n]}var xt=({columnCount:e=0,containerRef:t,disableHighlightOnFocus:n,data:o,requestScroll:r,rowCount:i=0,viewportRange:s})=>{var P;let{from:l,to:a}=s,u=ke([-1,-1]),c=ke(),d=ke([-1,0]),p=V(([f,M])=>{var R;let E=f===-1?Dt(M):Go(f,M);return(R=t.current)==null?void 0:R.querySelector(E)},[t]),h=f=>f==null?void 0:f.closest("[role='columnHeader'],[role='cell']"),b=f=>{var M,E;if(f.role==="columnHeader")return[-1,parseInt((M=f.dataset.idx)!=null?M:"-1",10)];{let R=f.closest("[role='row']");if(R){let k=parseInt((E=R.ariaRowIndex)!=null?E:"-1",10),Y=Array.from(R.childNodes).indexOf(f);return[k,Y]}}return Bo},g=V(f=>{var M;if(t.current){let E=p(f);E?(E!==c.current&&((M=c.current)==null||M.setAttribute("tabindex",""),c.current=E,E.setAttribute("tabindex","0")),E.focus()):Io(f[0],s)||(c.current=void 0,r==null||r({type:"scroll-page",direction:"up"}))}},[t,p,r,s]),D=V((f,M,E=!1)=>{let R=[f,M];d.current=R,g(R),E&&(u.current=R)},[g]),y=V(()=>{var f;(f=c.current)==null||f.setAttribute("tabindex",""),c.current=void 0},[]),m=V(async(f,M)=>{switch(f){case Le:r==null||r({type:"scroll-page",direction:"down"});break;case Ae:r==null||r({type:"scroll-page",direction:"up"});break;case Ee:r==null||r({type:"scroll-end",direction:"home"});break;case Se:r==null||r({type:"scroll-end",direction:"end"});break}return M},[r]),C=V(()=>{var f;if(n!==!0&&(f=t.current)!=null&&f.contains(document.activeElement)){let M=h(document.activeElement);M&&(u.current=b(M))}},[n,t]),T=V(async f=>{let[M,E]=Rt(f)?await m(f,d.current):Uo(f,d.current,e,i),[R,k]=d.current;(M!==R||E!==k)&&D(M,E,!0)},[e,m,i,D]),w=V(f=>{o.length>0&&Tt(f.key)&&(f.preventDefault(),f.stopPropagation(),T(f.key))},[o,T]),v=V(f=>{let M=f.target,E=h(M);if(E){let[R,k]=b(E);D(R,k)}},[D]),H=$o(()=>({onClick:v,onFocus:C,onKeyDown:w}),[v,C,w]);Oo(()=>{let{current:f}=d,M=f[0]>=l&&f[0]<=a;c.current&&!M?y():!c.current&&M&&g(f)},[g,l,a,y]);let S=((P=t.current)==null?void 0:P.firstChild)!=null;return Wo(()=>{var f;if(S&&c.current===void 0){let M=(f=t.current)==null?void 0:f.querySelector(Dt(0));M&&(M.setAttribute("tabindex","0"),c.current=M)}},[t,S]),H};import{useCallback as Xo,useRef as Yo,useState as Qo}from"react";import{useCallback as _o,useEffect as Ht,useRef as Jo}from"react";var B=new Map,Et=(e,t,n)=>{switch(n){case"height":return t.height;case"clientHeight":return e.clientHeight;case"clientWidth":return e.clientWidth;case"contentHeight":return t.contentHeight;case"contentWidth":return t.contentWidth;case"scrollHeight":return Math.ceil(e.scrollHeight);case"scrollWidth":return Math.ceil(e.scrollWidth);case"width":return t.width;default:return 0}},Pt=new ResizeObserver(e=>{for(let t of e){let{target:n,borderBoxSize:o,contentBoxSize:r}=t,i=B.get(n);if(i){let[{blockSize:s,inlineSize:l}]=o,[{blockSize:a,inlineSize:u}]=r,{onResize:c,measurements:d}=i,p=!1;for(let[h,b]of Object.entries(d)){let g=Et(n,{height:s,width:l,contentHeight:a,contentWidth:u},h);g!==b&&(p=!0,d[h]=g)}p&&c&&c(d)}}});function St(e,t,n,o=!1){let r=Jo(t),i=_o(s=>{let{width:l,height:a}=s.getBoundingClientRect(),{clientWidth:u,clientHeight:c}=s;return r.current.reduce((d,p)=>(d[p]=Et(s,{width:l,height:a,contentHeight:c,contentWidth:u},p),d),{})},[]);Ht(()=>{let s=e.current;async function l(){B.set(s,{measurements:{}}),await document.fonts.ready;let a=B.get(s);if(a){let u=i(s);a.measurements=u,Pt.observe(s),o&&n(u)}else console.log("%cuseResizeObserver an target expected to be under observation wa snot found. This warrants investigation","font-weight:bold; color:red;")}if(s){if(B.has(s))throw Error("useResizeObserver attemping to observe same element twice");l()}return()=>{s&&B.has(s)&&(Pt.unobserve(s),B.delete(s))}},[i,e]),Ht(()=>{let s=e.current,l=B.get(s);if(l){if(r.current!==t){r.current=t;let a=i(s);l.measurements=a}l.onResize=n}},[t,i,e,n])}var jo=["clientHeight","clientWidth"],At=e=>Number.isFinite(e),Lt=({defaultHeight:e=0,defaultWidth:t=0,height:n,width:o})=>{let r=Yo(null),[i,s]=Qo({outer:{height:n!=null?n:"100%",width:o!=null?o:"100%"}}),l=Xo(({clientWidth:a,clientHeight:u})=>{console.log(`Resize ${u}`),s(c=>{let{inner:d,outer:p}=c;return At(u)&&At(a)&&(a!==(d==null?void 0:d.width)||u!==(d==null?void 0:d.height))?{outer:p,inner:{width:Math.floor(a)||t,height:Math.floor(u)||e}}:c})},[e,t]);return St(r,jo,l,!0),{containerRef:r,outerSize:i.outer,innerSize:i.inner}};import{deselectItem as Zo,metadataKeys as qo,selectItem as er}from"@vuu-ui/vuu-utils";import{useCallback as tr,useRef as kt}from"react";var{IDX:nr,SELECTED:or}=qo,rr=[],Kt=({selectionModel:e,onSelectionChange:t})=>{let n=kt(-1),o=kt(rr);return tr((i,s,l)=>{let{[nr]:a,[or]:u}=i,{current:c}=n,{current:d}=o,h=(u?Zo:er)(e,d,a,s,l,c);o.current=h,n.current=a,t&&t(h)},[t,e])};import{moveItem as sr}from"@heswell/salt-lab";import{applyFilterToColumns as ir,applyGroupByToColumns as lr,applySortToColumns as ar,findColumn as cr,getCellRenderer as ur,getColumnName as mr,getTableHeadings as dr,getValueFormatter as pr,isFilteredColumn as fr,isGroupColumn as gr,isPinned as Cr,isTypeDescriptor as br,logger as hr,metadataKeys as vr,sortPinnedColumns as zt,stripFilterFromColumns as yr}from"@vuu-ui/vuu-utils";import{useReducer as wr}from"react";var{info:Ke}=hr("useTableModel"),Mr=100,Nt=vr.count,Rr=({serverDataType:e})=>e===void 0,Tr=e=>{var t;if(br(e.type))return ur((t=e.type)==null?void 0:t.renderer)},Dr=(e,t,n)=>{var r;let o=t.indexOf(e.name);return o!==-1&&n[o]?n[o]:(r=e.serverDataType)!=null?r:"string"},xr=["int","long","double"],Ft=e=>e===void 0?void 0:xr.includes(e)?"right":"left",Hr=(e,t)=>{switch(Ke==null||Ke(`GridModelReducer ${t.type}`),t.type){case"init":return It(t);case"moveColumn":return Er(e,t);case"resizeColumn":return Lr(e,t);case"setTypes":return kr(e,t);case"hideColumns":return Sr(e,t);case"showColumns":return Ar(e,t);case"pinColumn":return Kr(e,t);case"updateColumnProp":return te(e,t);case"tableConfig":return Ot(e,t);default:return console.log(`unhandled action ${t.type}`),e}},Vt=(e,t)=>{let[n,o]=wr(Hr,{tableConfig:e,dataSourceConfig:t},It);return{columns:n.columns,dispatchColumnAction:o,headings:n.headings}};function It({dataSourceConfig:e,tableConfig:t}){let n=t.columns.map(Wt(t)),o=n.some(Cr)?zt(n):n,r={columns:o,headings:dr(o)};if(e){let{columns:i,...s}=e;return Ot(r,{type:"tableConfig",...s})}else return r}var Pr=(e,t)=>t==="uppercase"?e.toUpperCase():t==="capitalize"?e[0].toUpperCase()+e.slice(1).toLowerCase():e,Wt=e=>(t,n)=>{let{columnDefaultWidth:o=Mr,columnFormatHeader:r}=e,{align:i=Ft(t.serverDataType),key:s,name:l,label:a=l,width:u=o,...c}=t,d={...c,align:i,CellRenderer:Tr(t),label:Pr(a,r),key:s!=null?s:n+Nt,name:l,originalIdx:n,valueFormatter:pr(t),width:u};return gr(d)&&(d.columns=d.columns.map(p=>Wt(e)(p,p.key))),d};function Er(e,{column:t,moveBy:n,moveTo:o}){let{columns:r}=e;if(typeof n=="number"){let i=r.indexOf(t),s=r.slice(),[l]=s.splice(i,1);return s.splice(i+n,0,l),{...e,columns:s}}else if(typeof o=="number"){let i=r.indexOf(t);return{...e,columns:sr(r,i,o)}}return e}function Sr(e,{columns:t}){return t.some(n=>n.hidden!==!0)?t.reduce((n,o)=>o.hidden!==!0?te(n,{type:"updateColumnProp",column:o,hidden:!0}):n,e):e}function Ar(e,{columns:t}){return t.some(n=>n.hidden)?t.reduce((n,o)=>o.hidden?te(n,{type:"updateColumnProp",column:o,hidden:!1}):n,e):e}function Lr(e,{column:t,phase:n,width:o}){let r="updateColumnProp",i=n!=="end";switch(n){case"begin":case"end":return te(e,{type:r,column:t,resizing:i});case"resize":return te(e,{type:r,column:t,width:o});default:throw Error(`useTableModel.resizeColumn, invalid resizePhase ${n}`)}}function kr(e,{columnNames:t,serverDataTypes:n}){let{columns:o}=e;if(o.some(Rr)){let r=o.map(i=>{var l;let s=Dr(i,t,n);return{...i,align:(l=i.align)!=null?l:Ft(s),serverDataType:s}});return{...e,columns:r}}else return e}function Kr(e,t){let{columns:n}=e,{column:o,pin:r}=t,i=n.find(s=>s.name===o.name);return i?(n=X(n,{...i,pin:r}),n=zt(n),{...e,columns:n}):e}function te(e,t){let{columns:n}=e,{align:o,column:r,hidden:i,label:s,resizing:l,width:a}=t,u=n.find(c=>c.name===r.name);return u&&((o==="left"||o==="right")&&(n=X(n,{...u,align:o})),typeof s=="string"&&(n=X(n,{...u,label:s})),typeof l=="boolean"&&(n=X(n,{...u,resizing:l})),typeof i=="boolean"&&(n=X(n,{...u,hidden:i})),typeof a=="number"&&(n=X(n,{...u,width:a}))),{...e,columns:n}}function Ot(e,{columns:t,confirmed:n,filter:o,groupBy:r,sort:i}){let s=t&&t.length>0,l=r!==void 0,a=typeof(o==null?void 0:o.filter)=="string",u=i&&i.sortDefs.length>0,c=e;return s&&(c={...e,columns:t.map((d,p)=>{let h=mr(d),b=p+Nt,g=cr(c.columns,h);if(g)return g.key===b?g:{...g,key:b};throw Error(`useTableModel column ${d} not found`)})}),l&&(c={...e,columns:lr(c.columns,r,n)}),u&&(c={...e,columns:ar(c.columns,i)}),a?c={...e,columns:ir(c.columns,o)}:c.columns.some(fr)&&(c={...e,columns:yr(c.columns)}),c}function X(e,t){return e.map(n=>n.name===t.name?t:n)}import{useCallback as W,useRef as ne}from"react";var $t=e=>{let{scrollLeft:t,scrollTop:n}=e,{clientHeight:o,clientWidth:r,scrollHeight:i,scrollWidth:s}=e,l=t/(s-r),a=n/(i-o);return[l,a]},zr=e=>{let{clientHeight:t,clientWidth:n,scrollHeight:o,scrollWidth:r}=e;return[r-n,o-t]},Gt=({onAttach:e,onDetach:t})=>{let n=ne(null);return W(r=>{if(r)n.current=r,e==null||e(r);else if(n.current){let{current:i}=n;n.current=r,t==null||t(i)}},[e,t])},Bt=({onHorizontalScroll:e,onVerticalScroll:t,viewport:n})=>{let o=ne(!1),r=ne({scrollTop:0,scrollLeft:0}),i=ne(null),s=ne(null),{maxScrollContainerScrollHorizontal:l,maxScrollContainerScrollVertical:a}=n,u=W(()=>{let{current:m}=s,{current:C}=i,{current:T}=o;if(T)o.current=!1;else if(m&&C){let[w,v]=$t(C),[H,S]=zr(m),P=Math.round(w*H),f=Math.round(v*S);m.scrollTo({left:P,top:f,behavior:"auto"})}},[]),c=W(()=>{let{current:m}=s,{current:C}=i,{current:T}=r;if(m&&C){let{scrollLeft:w,scrollTop:v}=m,[H,S]=$t(m);o.current=!0,C.scrollLeft=Math.round(H*l),C.scrollTop=Math.round(S*a),T.scrollTop!==v&&(T.scrollTop=v,t==null||t(v,S)),T.scrollLeft!==w&&(T.scrollLeft=w,e==null||e(w))}},[l,a,e,t]),d=W(m=>{i.current=m,m.addEventListener("scroll",u,{passive:!0})},[u]),p=W(m=>{i.current=null,m.removeEventListener("scroll",u)},[u]),h=W(m=>{s.current=m,m.addEventListener("scroll",c,{passive:!0})},[c]),b=W(m=>{s.current=null,m.removeEventListener("scroll",c)},[c]),g=Gt({onAttach:h,onDetach:b}),D=Gt({onAttach:d,onDetach:p}),y=W(m=>{let{current:C}=s;if(C){if(o.current=!1,m.type==="scroll-page"){let{clientHeight:T,scrollLeft:w,scrollTop:v}=C,{direction:H}=m,S=H==="down"?T:-T,P=Math.min(Math.max(0,v+S),a);C.scrollTo({top:P,left:w,behavior:"auto"})}else if(m.type==="scroll-end"){let{direction:T}=m,w=T==="end"?a:0;C.scrollTo({top:w,left:C.scrollLeft,behavior:"auto"})}}},[a]);return{scrollbarContainerRef:D,contentContainerRef:g,requestScroll:y}};import{useCallback as Nr,useMemo as me,useRef as Fr}from"react";import{actualRowPositioning as Vr,virtualRowPositioning as Ir}from"@vuu-ui/vuu-utils";var Wr=15e5,Or={contentHeight:0,contentWidth:0,getRowAtPosition:()=>-1,getRowOffset:()=>-1,horizontalScrollbarHeight:0,maxScrollContainerScrollHorizontal:0,maxScrollContainerScrollVertical:0,pinnedWidthLeft:0,pinnedWidthRight:0,rowCount:0,setPctScrollTop:()=>{},totalHeaderHeight:0,verticalScrollbarWidth:0,viewportBodyHeight:0},$r=e=>{let t=0,n=0,o=0;for(let r of e){let{hidden:i,pin:s,width:l}=r,a=i?0:l;s==="left"?t+=a:s==="right"?n+=a:o+=a}return{pinnedWidthLeft:t,pinnedWidthRight:n,unpinnedWidth:o}},Ut=({columns:e,headerHeight:t,headings:n,rowCount:o,rowHeight:r,size:i})=>{let s=Fr(0),a=Math.min(o,Wr)*r,c=o*r-a,{pinnedWidthLeft:d,pinnedWidthRight:p,unpinnedWidth:h}=me(()=>$r(e),[e]),[b,g]=me(()=>Vr(r),[r]),[D,y]=me(()=>c?Ir(r,c,s):[b,g],[g,b,c,r]),m=Nr(C=>{s.current=C},[]);return me(()=>{var C;if(i){let T=n.length,w=15,v=d+h+p,H=v>i.width?w:0,S=t*(1+T),P=a-(((C=i==null?void 0:i.height)!=null?C:0)-H)+S,f=v-i.width+d,M=(i.height-t)/r,E=Number.isInteger(M)?M+1:Math.ceil(M),R=i.height-S,k=a>R?w:0;return{contentHeight:a,getRowAtPosition:y,getRowOffset:D,horizontalScrollbarHeight:H,maxScrollContainerScrollHorizontal:f,maxScrollContainerScrollVertical:P,pinnedWidthLeft:d,pinnedWidthRight:p,rowCount:E,contentWidth:v,setPctScrollTop:m,totalHeaderHeight:S,verticalScrollbarWidth:k,viewportBodyHeight:R}}else return Or},[i,n.length,d,h,p,a,t,r,y,D,m])};import{getColumnsInViewport as _t,itemsChanged as Gr}from"@vuu-ui/vuu-utils";import{useCallback as Jt,useEffect as Br,useMemo as Ur,useRef as ze,useState as _r}from"react";var Xt=({columns:e,getRowAtPosition:t,setRange:n,viewportMeasurements:o})=>{let r=ze(-1),{rowCount:i,contentWidth:s,maxScrollContainerScrollHorizontal:l}=o,a=s-l,u=ze(0),[c,d]=Ur(()=>_t(e,u.current,u.current+a),[a,e]),p=ze(d);Br(()=>{b(c)},[c]);let[h,b]=_r(c),g=Jt(y=>{u.current=y;let[m,C]=_t(e,y,y+a);Gr(h,m)&&(p.current=C,b(m))},[a,e,h]),D=Jt(y=>{let m=t(y);m!==r.current&&(r.current=m,n({from:m,to:m+i}))},[t,n,i]);return{columnsWithinViewport:h,onHorizontalScroll:g,onVerticalScroll:D,virtualColSpan:p.current}};var ts=[],{KEY:ns,IS_EXPANDED:Qt,IS_LEAF:jt}=jr,Zt=({config:e,dataSource:t,headerHeight:n,onConfigChange:o,onFeatureEnabled:r,onFeatureInvocation:i,onSelectionChange:s,renderBufferSize:l=0,rowHeight:a,selectionModel:u,...c})=>{var Oe,$e;let[d,p]=es(0),h=Ne(!1),b=Ne();if(b.current=t,t===void 0)throw Error("no data source provided to DataTable");let g=Lt(c),D=z(x=>{p(x)},[]),{columns:y,dispatchColumnAction:m,headings:C}=Vt(e,t.config),T=z(x=>{h.current=!0,m(x)},[m]),w=Je({dataSource:t,onPersistentColumnOperation:T}),{getRowAtPosition:v,getRowOffset:H,setPctScrollTop:S,...P}=Ut({columns:y,headerHeight:n,headings:C,rowCount:d,rowHeight:a,size:g.innerSize}),f=z(x=>{if(x.tableMeta){let{columns:A,dataTypes:K}=x.tableMeta;h.current=!0,m({type:"setTypes",columnNames:A,serverDataTypes:K})}},[m]),M=z(x=>{t.select(x),s==null||s(x)},[t,s]),E=Kt({onSelectionChange:M,selectionModel:u}),{data:R,getSelectedRows:k,range:Y,setRange:de}=ht({dataSource:t,onFeatureEnabled:r,onFeatureInvocation:i,onSubscribed:f,onSizeChange:D,renderBufferSize:l,viewportRowCount:P.rowCount}),Ve=Ne();Ve.current=R;let en=z((x,A=!1,K)=>{t&&(t.sort=Xr(t.sort,x,A,K))},[t]),tn=z((x,A,K)=>{let L=y.find(N=>N.name===A);if(L)x==="end"&&(h.current=!0),m({type:"resizeColumn",phase:x,column:L,width:K});else throw Error(`useDataTable.handleColumnResize, column ${A} not found`)},[y,m]),nn=z((x,A)=>{let K=Qr(A,x),L=x[ns];if(x[Qt]){if(t.closeTreeNode(L,!0),K){let N=y.indexOf(A);t.getRowsAtDepth(N+1).some(F=>F[Qt]||F[jt])||m({type:"hideColumns",columns:y.slice(N+2)})}}else if(t.openTreeNode(L),K){let N=t.getChildRows(L),O=y.indexOf(A)+1,F=[y[O]];N.some(_=>_[jt])&&F.push(y[O+1]),F.some(_=>_.hidden)&&m({type:"showColumns",columns:F})}},[y,t,m]),{onVerticalScroll:Ie,onHorizontalScroll:on,columnsWithinViewport:rn,virtualColSpan:sn}=Xt({columns:y,getRowAtPosition:v,setRange:de,viewportMeasurements:P}),ln=z((x,A)=>{S(A),Ie(x)},[Ie,S]),{requestScroll:an,...cn}=Bt({onHorizontalScroll:on,onVerticalScroll:ln,viewport:P,viewportHeight:(($e=(Oe=g.innerSize)==null?void 0:Oe.height)!=null?$e:0)-n}),un=xt({columnCount:y.length,containerRef:g.containerRef,data:R,requestScroll:an,rowCount:t==null?void 0:t.size,viewportRange:Y}),mn=z(x=>{x?t&&t.groupBy.includes(x.name)&&(t.groupBy=t.groupBy.filter(A=>A!==x.name)):t.groupBy=[]},[t]),dn=z((x,A)=>{let K=t.columns[x],L=Zr(t.columns,K,A);L!==t.columns&&(t.columns=L,m({type:"tableConfig",columns:L}))},[t,m]),pn=wt({onDrop:dn});Yt(()=>{b.current&&(h.current=!0,m({type:"init",tableConfig:e,dataSourceConfig:b.current.config}))},[e,m]),Yt(()=>{t.on("config",(x,A)=>{h.current=!0,m({type:"tableConfig",...x,confirmed:A})})},[t,m]),qr(()=>{h.current&&(o==null||o({...e,columns:y}),h.current=!1)},[y,e,o]);let We=Jr(),fn=z(x=>{var F;let{current:A}=Ve,{current:K}=b,L=x.target,N=L==null?void 0:L.closest("div[role='cell']"),O=L==null?void 0:L.closest(".vuuTableRow");if(N&&O&&A&&K){let{columns:_,selectedRowsCount:gn}=K,Cn=Yr(_),bn=parseInt((F=O.ariaRowIndex)!=null?F:"-1"),hn=Array.from(O.childNodes).indexOf(N),vn=A.find(([wn])=>wn===bn),yn=_[hn];We(x,"grid",{columnMap:Cn,columnName:yn,row:vn,selectedRows:gn===0?ts:k(),viewport:t==null?void 0:t.viewport})}},[t==null?void 0:t.viewport,k,We]);return{containerMeasurements:g,containerProps:un,columns:y,columnsWithinViewport:rn,data:R,dispatchColumnAction:m,getRowOffset:H,handleContextMenuAction:w,headings:C,onColumnResize:tn,onContextMenu:fn,onRemoveColumnFromGroupBy:mn,onRowClick:E,onSort:en,onToggleGroup:nn,virtualColSpan:sn,scrollProps:cn,rowCount:d,viewportMeasurements:P,...pn}};import is from"classnames";import{isDataLoading as ls}from"@vuu-ui/vuu-utils";import{jsx as oe,jsxs as qt}from"react/jsx-runtime";var U="vuuTable",Na=({allowConfigEditing:e=!1,className:t,config:n,dataSource:o,headerHeight:r=25,height:i,id:s,onConfigChange:l,onFeatureEnabled:a,onFeatureInvocation:u,onSelectionChange:c,onShowConfigEditor:d,renderBufferSize:p=0,rowHeight:h=20,selectionModel:b="extended",style:g,width:D,zebraStripes:y=!1,...m})=>{let C=ss(s),{containerMeasurements:{containerRef:T,innerSize:w,outerSize:v},containerProps:H,dispatchColumnAction:S,draggable:P,draggedItemIndex:f,handleContextMenuAction:M,scrollProps:E,viewportMeasurements:R,...k}=Zt({config:n,dataSource:o,renderBufferSize:p,headerHeight:r,height:i,onConfigChange:l,onFeatureEnabled:a,onFeatureInvocation:u,onSelectionChange:c,rowHeight:h,selectionModel:b,width:D}),Y={...v,"--content-height":`${R.contentHeight}px`,"--horizontal-scrollbar-height":`${R.horizontalScrollbarHeight}px`,"--content-width":`${R.contentWidth}px`,"--pinned-width-left":`${R.pinnedWidthLeft}px`,"--pinned-width-right":`${R.pinnedWidthRight}px`,"--header-height":`${r}px`,"--row-height":`${h}px`,"--table-height":`${w==null?void 0:w.height}px`,"--table-width":`${w==null?void 0:w.width}px`,"--total-header-height":`${R.totalHeaderHeight}px`,"--vertical-scrollbar-width":`${R.verticalScrollbarWidth}px`,"--viewport-body-height":`${R.viewportBodyHeight}px`},de=is(U,t,{[`${U}-zebra`]:y,[`${U}-loading`]:ls(k.columns)});return oe(os,{menuActionHandler:M,menuBuilder:Ge(o),children:qt("div",{...m,...H,className:de,id:C,ref:T,style:Y,tabIndex:-1,children:[w?oe("div",{className:`${U}-scrollbarContainer`,ref:E.scrollbarContainerRef,children:oe("div",{className:`${U}-scrollbarContent`})}):null,w?qt("div",{className:`${U}-contentContainer`,ref:E.contentContainerRef,children:[oe(bt,{...k,headerHeight:r,tableId:C}),P]}):null,e&&w?oe(rs,{className:`${U}-settings`,"data-icon":"settings",onClick:d,variant:"secondary"}):null]})})};import as from"classnames";import{isJsonAttribute as cs,metadataKeys as us,registerComponent as ms}from"@vuu-ui/vuu-utils";import{jsx as Fe,jsxs as Cs}from"react/jsx-runtime";var re="vuuJsonCell",{IS_EXPANDED:ds,KEY:ps}=us,fs=e=>{let t=e.lastIndexOf("|");return t===-1?"":e.slice(t+1)},gs=({column:e,row:t})=>{let{key:n}=e,o=t[n],r=!1;cs(o)&&(o=o.slice(0,-1),r=!0);let i=fs(t[ps]),s=as({[`${re}-name`]:i===o,[`${re}-value`]:i!==o,[`${re}-group`]:r});if(r){let l=t[ds]?"minus-box":"plus-box";return Cs("span",{className:s,children:[Fe("span",{className:`${re}-value`,children:o}),Fe("span",{className:`${re}-toggle`,"data-icon":l})]})}else return o?Fe("span",{className:s,children:o}):null};ms("json",gs,"cell-renderer",{});export{Na as Table,Lt as useMeasuredContainer};
2803
2
  //# sourceMappingURL=index.js.map