@react-fabric/data 1.0.0-beta.29 → 1.0.0-beta.30

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.
@@ -1,42 +1,20 @@
1
1
  'use strict';
2
2
 
3
+ var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
3
4
  var core = require('@react-fabric/core');
4
5
  var react = require('react');
5
6
  var Context = require('./Context.js');
6
7
  var types = require('./types.js');
7
8
  var jsxRuntime = require('react/jsx-runtime');
8
9
 
9
- /*
10
- * React Fabric
11
- * @version: 1.0.0
12
- *
13
- *
14
- * The MIT License (MIT)
15
- * Copyright (c) 2024 Adarsh Pastakia
16
- *
17
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
18
- * and associated documentation files (the "Software"), to deal in the Software without restriction,
19
- * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
20
- * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
21
- * subject to the following conditions:
22
- *
23
- * The above copyright notice and this permission notice shall be included in all copies or substantial
24
- * portions of the Software.
25
- *
26
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
27
- * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
29
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
- */
31
-
32
10
  var HeaderCell = function HeaderCell(_ref) {
33
11
  var id = _ref.id,
34
12
  label = _ref.label,
35
13
  icon = _ref.icon,
36
14
  iconBg = _ref.iconBg,
37
15
  iconColor = _ref.iconColor,
38
- rtlFlip = _ref.rtlFlip;
39
- _ref.actions;
16
+ rtlFlip = _ref.rtlFlip,
17
+ actions = _ref.actions;
40
18
  _ref.locked;
41
19
  var tooltip = _ref.tooltip,
42
20
  sortable = _ref.sortable,
@@ -76,15 +54,21 @@ var HeaderCell = function HeaderCell(_ref) {
76
54
  }
77
55
  }, "sort-desc"));
78
56
  }
57
+ if (sortable && actions) {
58
+ ret.push( /*#__PURE__*/jsxRuntime.jsx(core.Divider, {}));
59
+ }
60
+ if (actions) {
61
+ ret.push.apply(ret, _toConsumableArray(actions));
62
+ }
79
63
  return ret;
80
- }, [sortable]);
64
+ }, [sortable, actions]);
81
65
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
82
66
  role: "none",
83
67
  "data-id": id,
84
68
  onClick: function onClick() {
85
69
  return handleSort();
86
70
  },
87
- className: "group font-medium border-e flex flex-nowrap text-start items-center table-header-cell",
71
+ className: "group/tool font-medium border-e flex flex-nowrap text-start items-center table-header-cell",
88
72
  style: {
89
73
  width: width !== null && width !== void 0 ? width : types.COL_DEFAULT_WIDTH,
90
74
  minWidth: minWidth !== null && minWidth !== void 0 ? minWidth : types.COL_MIN_WIDTH,
@@ -3,6 +3,7 @@
3
3
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
4
4
  var core = require('@react-fabric/core');
5
5
  var utilities = require('@react-fabric/utilities');
6
+ var classNames = require('classnames');
6
7
  var react = require('react');
7
8
  var reactI18next = require('react-i18next');
8
9
  var AddColumn = require('./AddColumn.js');
@@ -18,17 +19,21 @@ var jsxRuntime = require('react/jsx-runtime');
18
19
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
19
20
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
20
21
  var Table = function Table(_ref) {
21
- var _state$start, _state$cols, _state$end, _items$, _state$start2, _state$cols2, _state$end2;
22
+ var _state$start, _state$cols, _state$end, _items, _state$start2, _state$cols2, _state$end2;
22
23
  var ref = _ref.ref,
23
24
  data = _ref.data,
24
25
  columns = _ref.columns,
25
- keyProperty = _ref.keyProperty,
26
+ _ref$keyProperty = _ref.keyProperty,
27
+ keyProperty = _ref$keyProperty === void 0 ? "id" : _ref$keyProperty,
28
+ groupProperty = _ref.groupProperty,
26
29
  checkableRows = _ref.checkableRows,
27
30
  initialScroll = _ref.initialScroll,
28
31
  hideableColumns = _ref.hideableColumns,
29
32
  sort = _ref.sort,
30
33
  loading = _ref.loading,
34
+ checked = _ref.checked,
31
35
  emptyDisplay = _ref.emptyDisplay,
36
+ groupRenderer = _ref.groupRenderer,
32
37
  canExpand = _ref.canExpand,
33
38
  children = _ref.children,
34
39
  onSort = _ref.onSort,
@@ -43,17 +48,25 @@ var Table = function Table(_ref) {
43
48
  var _useTableColumns = useTableColumns.useTableColumns(columns),
44
49
  state = _useTableColumns.state,
45
50
  onHide = _useTableColumns.onHide;
46
- var _useVirtualTable = useVirtualTable.useVirtualTable(data, keyProperty, fireCheckChanged),
51
+ var _useVirtualTable = useVirtualTable.useVirtualTable(data, {
52
+ checked: checked,
53
+ keyProperty: keyProperty,
54
+ groupProperty: groupProperty,
55
+ onCheckChanged: fireCheckChanged
56
+ }),
47
57
  scrollerRef = _useVirtualTable.scrollerRef,
48
58
  items = _useVirtualTable.items,
49
59
  top = _useVirtualTable.top,
50
60
  checkState = _useVirtualTable.checkState,
51
61
  virtualizer = _useVirtualTable.virtualizer,
62
+ hasActiveSticky = _useVirtualTable.hasActiveSticky,
52
63
  toggleExpand = _useVirtualTable.toggleExpand,
53
64
  toggleChecked = _useVirtualTable.toggleChecked,
54
65
  toggleAllChecked = _useVirtualTable.toggleAllChecked,
66
+ toggleGroupExpand = _useVirtualTable.toggleGroupExpand,
55
67
  getData = _useVirtualTable.getData,
56
68
  totalSize = _useVirtualTable.totalSize,
69
+ isActiveSticky = _useVirtualTable.isActiveSticky,
57
70
  measureElement = _useVirtualTable.measureElement;
58
71
  var refBody = react.useRef(null);
59
72
  var wrapperStart = react.useMemo(function () {
@@ -153,13 +166,34 @@ var Table = function Table(_ref) {
153
166
  ref: refBody,
154
167
  children: [/*#__PURE__*/jsxRuntime.jsx("div", {
155
168
  style: {
156
- height: (_items$ = items[0]) === null || _items$ === void 0 ? void 0 : _items$.start
169
+ height: (_items = items[hasActiveSticky ? 1 : 0]) === null || _items === void 0 ? void 0 : _items.start
157
170
  }
158
171
  }), items.map(function (_ref2) {
172
+ var _groupRenderer;
159
173
  var index = _ref2.index,
160
174
  key = _ref2.key;
161
175
  var data = getData(index);
162
- return /*#__PURE__*/jsxRuntime.jsx(BodyRow.BodyRow, {
176
+ return "__GROUP__" in data ? /*#__PURE__*/jsxRuntime.jsxs("div", {
177
+ ref: measureElement,
178
+ "data-index": index,
179
+ className: classNames("px-2 py-1 text-md bg-base border-y border-tint-100 cursor-pointer flex items-center gap-1", isActiveSticky(index) && "sticky top-8 z-30"),
180
+ role: "none",
181
+ onClick: function onClick() {
182
+ return toggleGroupExpand(data.key);
183
+ },
184
+ children: [/*#__PURE__*/jsxRuntime.jsx(core.Icon, {
185
+ rtlFlip: true,
186
+ icon: data.open ? core.CoreIcons.chevronDown : core.CoreIcons.chevronRight
187
+ }), (_groupRenderer = groupRenderer === null || groupRenderer === void 0 ? void 0 : groupRenderer(data)) !== null && _groupRenderer !== void 0 ? _groupRenderer : /*#__PURE__*/jsxRuntime.jsxs("div", {
188
+ className: "flex gap-1 items-center",
189
+ children: [/*#__PURE__*/jsxRuntime.jsx("span", {
190
+ children: data.key
191
+ }), /*#__PURE__*/jsxRuntime.jsxs("span", {
192
+ className: "text-sm",
193
+ children: ["(", data.itemCount, ")"]
194
+ })]
195
+ })]
196
+ }, key) : /*#__PURE__*/jsxRuntime.jsx(BodyRow.BodyRow, {
163
197
  rowKey: key,
164
198
  index: index,
165
199
  checkableRows: checkableRows,
@@ -1,49 +1,83 @@
1
1
  'use strict';
2
2
 
3
3
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
4
+ var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
4
5
  var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
6
+ var utilities = require('@react-fabric/utilities');
5
7
  var reactVirtual = require('@tanstack/react-virtual');
6
8
  var react = require('react');
7
9
 
8
10
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
9
11
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
10
- var useVirtualTable = function useVirtualTable(data, keyProperty, onCheckChanged) {
12
+ var useVirtualTable = function useVirtualTable(data, options) {
11
13
  var _virtualizer$range;
12
14
  // TODO: refactor data into item list, apply grouping if groupColumn provided
13
15
  // TODO: when grouping maintain map of group with children, {___GROUP___:true, label, items, open}
14
16
 
15
- var scrollerRef = react.useRef(null);
16
- var virtualizer = reactVirtual.useVirtualizer({
17
- count: data.length,
18
- getScrollElement: function getScrollElement() {
19
- return scrollerRef.current;
20
- },
21
- estimateSize: function estimateSize() {
22
- return 24;
23
- }
24
- });
25
17
  var _useReducer = react.useReducer(function (state, action) {
18
+ if (action.type === "updateState") {
19
+ state.checked = action.checked;
20
+ }
26
21
  if (action.type === "expand") {
27
22
  if (state.expanded.includes(action.key)) state.expanded.splice(state.expanded.indexOf(action.key), 1);else state.expanded.push(action.key);
28
23
  }
29
24
  if (action.type === "check") {
25
+ var _options$onCheckChang;
30
26
  if (state.checked.includes(action.key)) state.checked.splice(state.checked.indexOf(action.key), 1);else state.checked.push(action.key);
31
- onCheckChanged === null || onCheckChanged === void 0 || onCheckChanged(state.checked);
27
+ (_options$onCheckChang = options.onCheckChanged) === null || _options$onCheckChang === void 0 || _options$onCheckChang.call(options, state.checked);
32
28
  }
33
29
  if (action.type === "checkall") {
30
+ var _options$onCheckChang2;
34
31
  if (state.allChecked !== 0) {
35
32
  state.checked = [];
36
- } else if (keyProperty) {
33
+ } else if (options.keyProperty) {
37
34
  state.checked = data.map(function (item) {
38
- return item[keyProperty];
35
+ return item[options.keyProperty];
36
+ });
37
+ }
38
+ (_options$onCheckChang2 = options.onCheckChanged) === null || _options$onCheckChang2 === void 0 || _options$onCheckChang2.call(options, state.checked);
39
+ }
40
+ var checkList = data.filter(function (hit) {
41
+ return state.checked.includes(hit[options.keyProperty]);
42
+ });
43
+ if (action.type === "groupExpand") {
44
+ var group = state.groups.find(function (group) {
45
+ return group.key === action.key;
46
+ });
47
+ if (group) {
48
+ group.open = !group.open;
49
+ state.groups = state.groups.slice();
50
+ state.items = state.groups.map(function (group) {
51
+ return [group, group.open ? state.grouped[group.key] : undefined];
52
+ }).flat(2).filter(Boolean);
53
+ }
54
+ }
55
+ if (action.type === "grouped") {
56
+ if (action.key) {
57
+ state.grouped = utilities.groupBy(data, action.key);
58
+ state.groups = Object.keys(state.grouped).sort(utilities.compareValues("asc")).map(function (group) {
59
+ return {
60
+ __GROUP__: true,
61
+ open: true,
62
+ key: group,
63
+ items: state.grouped[group],
64
+ itemCount: state.grouped[group].length
65
+ };
39
66
  });
67
+ state.items = state.groups.map(function (group) {
68
+ return [group].concat(_toConsumableArray(state.grouped[group.key]));
69
+ }).flat();
70
+ } else {
71
+ state.items = data;
40
72
  }
41
- onCheckChanged === null || onCheckChanged === void 0 || onCheckChanged(state.checked);
42
73
  }
43
74
  return _objectSpread(_objectSpread({}, state), {}, {
44
- allChecked: state.checked.length === data.length ? 1 : state.checked.length ? 2 : 0
75
+ allChecked: checkList.length === data.length ? 1 : state.checked.length ? 2 : 0
45
76
  });
46
77
  }, {
78
+ items: data,
79
+ grouped: {},
80
+ groups: [],
47
81
  checked: [],
48
82
  expanded: [],
49
83
  allChecked: 0
@@ -51,19 +85,72 @@ var useVirtualTable = function useVirtualTable(data, keyProperty, onCheckChanged
51
85
  _useReducer2 = _slicedToArray(_useReducer, 2),
52
86
  state = _useReducer2[0],
53
87
  dispatch = _useReducer2[1];
88
+ var activeStickyIndexRef = react.useRef(0);
89
+ var stickyIndexes = react.useMemo(function () {
90
+ return state.items.map(function (hit, idx) {
91
+ return "__GROUP__" in hit ? idx : undefined;
92
+ }).filter(Boolean);
93
+ }, [state.items]);
94
+ var isActiveSticky = function isActiveSticky(index) {
95
+ return activeStickyIndexRef.current === index;
96
+ };
97
+ var _useState = react.useState(false),
98
+ _useState2 = _slicedToArray(_useState, 2),
99
+ hasActiveSticky = _useState2[0],
100
+ setHasActiveSticky = _useState2[1];
101
+ var scrollerRef = react.useRef(null);
102
+ var virtualizer = reactVirtual.useVirtualizer({
103
+ count: state.items.length,
104
+ getScrollElement: function getScrollElement() {
105
+ return scrollerRef.current;
106
+ },
107
+ estimateSize: function estimateSize() {
108
+ return 32;
109
+ },
110
+ rangeExtractor: react.useCallback(function (range) {
111
+ var _reverse$find;
112
+ activeStickyIndexRef.current = (_reverse$find = _toConsumableArray(stickyIndexes).reverse().find(function (index) {
113
+ return range.startIndex > index;
114
+ })) !== null && _reverse$find !== void 0 ? _reverse$find : 0;
115
+ setHasActiveSticky(range.startIndex !== activeStickyIndexRef.current);
116
+ var next = new Set([activeStickyIndexRef.current].concat(_toConsumableArray(reactVirtual.defaultRangeExtractor(range))));
117
+ return _toConsumableArray(next);
118
+ }, [stickyIndexes])
119
+ });
54
120
  var virtualItems = virtualizer.getVirtualItems();
55
121
  var getData = react.useCallback(function (index) {
56
- return data[index];
57
- }, [data]);
122
+ return state.items[index];
123
+ }, [state.items]);
124
+ react.useEffect(function () {
125
+ dispatch({
126
+ type: "grouped",
127
+ key: options.groupProperty
128
+ });
129
+ }, [options.groupProperty]);
130
+ react.useEffect(function () {
131
+ var _options$checked;
132
+ dispatch({
133
+ type: "updateState",
134
+ checked: (_options$checked = options.checked) !== null && _options$checked !== void 0 ? _options$checked : []
135
+ });
136
+ }, [options.checked]);
58
137
  return {
59
138
  scrollerRef: scrollerRef,
60
139
  items: virtualItems,
61
140
  checkState: state,
62
141
  getData: getData,
63
142
  virtualizer: virtualizer,
143
+ hasActiveSticky: hasActiveSticky,
144
+ isActiveSticky: isActiveSticky,
64
145
  top: (_virtualizer$range = virtualizer.range) === null || _virtualizer$range === void 0 ? void 0 : _virtualizer$range.startIndex,
65
146
  totalSize: virtualizer.getTotalSize,
66
147
  measureElement: virtualizer.measureElement,
148
+ toggleGroupExpand: function toggleGroupExpand(key) {
149
+ return dispatch({
150
+ type: "groupExpand",
151
+ key: key
152
+ });
153
+ },
67
154
  toggleExpand: function toggleExpand(key) {
68
155
  return dispatch({
69
156
  type: "expand",
@@ -1,42 +1,20 @@
1
1
  'use client';
2
2
 
3
- import { MenuItem, CoreIcons, Tooltip, Icon, DropdownTool, Menu } from '@react-fabric/core';
3
+ import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
4
+ import { MenuItem, CoreIcons, Divider, Tooltip, Icon, DropdownTool, Menu } from '@react-fabric/core';
4
5
  import { useMemo, useCallback } from 'react';
5
6
  import { useTableContext } from './Context.js';
6
7
  import { COL_DEFAULT_WIDTH, COL_MIN_WIDTH, COL_MAX_WIDTH } from './types.js';
7
8
  import { jsx, jsxs } from 'react/jsx-runtime';
8
9
 
9
- /*
10
- * React Fabric
11
- * @version: 1.0.0
12
- *
13
- *
14
- * The MIT License (MIT)
15
- * Copyright (c) 2024 Adarsh Pastakia
16
- *
17
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
18
- * and associated documentation files (the "Software"), to deal in the Software without restriction,
19
- * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
20
- * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
21
- * subject to the following conditions:
22
- *
23
- * The above copyright notice and this permission notice shall be included in all copies or substantial
24
- * portions of the Software.
25
- *
26
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
27
- * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
28
- * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
29
- * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
- */
31
-
32
10
  var HeaderCell = function HeaderCell(_ref) {
33
11
  var id = _ref.id,
34
12
  label = _ref.label,
35
13
  icon = _ref.icon,
36
14
  iconBg = _ref.iconBg,
37
15
  iconColor = _ref.iconColor,
38
- rtlFlip = _ref.rtlFlip;
39
- _ref.actions;
16
+ rtlFlip = _ref.rtlFlip,
17
+ actions = _ref.actions;
40
18
  _ref.locked;
41
19
  var tooltip = _ref.tooltip,
42
20
  sortable = _ref.sortable,
@@ -76,15 +54,21 @@ var HeaderCell = function HeaderCell(_ref) {
76
54
  }
77
55
  }, "sort-desc"));
78
56
  }
57
+ if (sortable && actions) {
58
+ ret.push( /*#__PURE__*/jsx(Divider, {}));
59
+ }
60
+ if (actions) {
61
+ ret.push.apply(ret, _toConsumableArray(actions));
62
+ }
79
63
  return ret;
80
- }, [sortable]);
64
+ }, [sortable, actions]);
81
65
  return /*#__PURE__*/jsxs("div", {
82
66
  role: "none",
83
67
  "data-id": id,
84
68
  onClick: function onClick() {
85
69
  return handleSort();
86
70
  },
87
- className: "group font-medium border-e flex flex-nowrap text-start items-center table-header-cell",
71
+ className: "group/tool font-medium border-e flex flex-nowrap text-start items-center table-header-cell",
88
72
  style: {
89
73
  width: width !== null && width !== void 0 ? width : COL_DEFAULT_WIDTH,
90
74
  minWidth: minWidth !== null && minWidth !== void 0 ? minWidth : COL_MIN_WIDTH,
@@ -1,8 +1,9 @@
1
1
  'use client';
2
2
 
3
3
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
4
- import { useDebounce, Loading, EmptyContent } from '@react-fabric/core';
4
+ import { useDebounce, Loading, Icon, CoreIcons, EmptyContent } from '@react-fabric/core';
5
5
  import { debounce } from '@react-fabric/utilities';
6
+ import classNames from 'classnames';
6
7
  import { useRef, useMemo, useLayoutEffect, useImperativeHandle, useEffect } from 'react';
7
8
  import { useTranslation } from 'react-i18next';
8
9
  import { AddColumn } from './AddColumn.js';
@@ -18,17 +19,21 @@ import { jsx, jsxs } from 'react/jsx-runtime';
18
19
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
19
20
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
20
21
  var Table = function Table(_ref) {
21
- var _state$start, _state$cols, _state$end, _items$, _state$start2, _state$cols2, _state$end2;
22
+ var _state$start, _state$cols, _state$end, _items, _state$start2, _state$cols2, _state$end2;
22
23
  var ref = _ref.ref,
23
24
  data = _ref.data,
24
25
  columns = _ref.columns,
25
- keyProperty = _ref.keyProperty,
26
+ _ref$keyProperty = _ref.keyProperty,
27
+ keyProperty = _ref$keyProperty === void 0 ? "id" : _ref$keyProperty,
28
+ groupProperty = _ref.groupProperty,
26
29
  checkableRows = _ref.checkableRows,
27
30
  initialScroll = _ref.initialScroll,
28
31
  hideableColumns = _ref.hideableColumns,
29
32
  sort = _ref.sort,
30
33
  loading = _ref.loading,
34
+ checked = _ref.checked,
31
35
  emptyDisplay = _ref.emptyDisplay,
36
+ groupRenderer = _ref.groupRenderer,
32
37
  canExpand = _ref.canExpand,
33
38
  children = _ref.children,
34
39
  onSort = _ref.onSort,
@@ -43,17 +48,25 @@ var Table = function Table(_ref) {
43
48
  var _useTableColumns = useTableColumns(columns),
44
49
  state = _useTableColumns.state,
45
50
  onHide = _useTableColumns.onHide;
46
- var _useVirtualTable = useVirtualTable(data, keyProperty, fireCheckChanged),
51
+ var _useVirtualTable = useVirtualTable(data, {
52
+ checked: checked,
53
+ keyProperty: keyProperty,
54
+ groupProperty: groupProperty,
55
+ onCheckChanged: fireCheckChanged
56
+ }),
47
57
  scrollerRef = _useVirtualTable.scrollerRef,
48
58
  items = _useVirtualTable.items,
49
59
  top = _useVirtualTable.top,
50
60
  checkState = _useVirtualTable.checkState,
51
61
  virtualizer = _useVirtualTable.virtualizer,
62
+ hasActiveSticky = _useVirtualTable.hasActiveSticky,
52
63
  toggleExpand = _useVirtualTable.toggleExpand,
53
64
  toggleChecked = _useVirtualTable.toggleChecked,
54
65
  toggleAllChecked = _useVirtualTable.toggleAllChecked,
66
+ toggleGroupExpand = _useVirtualTable.toggleGroupExpand,
55
67
  getData = _useVirtualTable.getData,
56
68
  totalSize = _useVirtualTable.totalSize,
69
+ isActiveSticky = _useVirtualTable.isActiveSticky,
57
70
  measureElement = _useVirtualTable.measureElement;
58
71
  var refBody = useRef(null);
59
72
  var wrapperStart = useMemo(function () {
@@ -153,13 +166,34 @@ var Table = function Table(_ref) {
153
166
  ref: refBody,
154
167
  children: [/*#__PURE__*/jsx("div", {
155
168
  style: {
156
- height: (_items$ = items[0]) === null || _items$ === void 0 ? void 0 : _items$.start
169
+ height: (_items = items[hasActiveSticky ? 1 : 0]) === null || _items === void 0 ? void 0 : _items.start
157
170
  }
158
171
  }), items.map(function (_ref2) {
172
+ var _groupRenderer;
159
173
  var index = _ref2.index,
160
174
  key = _ref2.key;
161
175
  var data = getData(index);
162
- return /*#__PURE__*/jsx(BodyRow, {
176
+ return "__GROUP__" in data ? /*#__PURE__*/jsxs("div", {
177
+ ref: measureElement,
178
+ "data-index": index,
179
+ className: classNames("px-2 py-1 text-md bg-base border-y border-tint-100 cursor-pointer flex items-center gap-1", isActiveSticky(index) && "sticky top-8 z-30"),
180
+ role: "none",
181
+ onClick: function onClick() {
182
+ return toggleGroupExpand(data.key);
183
+ },
184
+ children: [/*#__PURE__*/jsx(Icon, {
185
+ rtlFlip: true,
186
+ icon: data.open ? CoreIcons.chevronDown : CoreIcons.chevronRight
187
+ }), (_groupRenderer = groupRenderer === null || groupRenderer === void 0 ? void 0 : groupRenderer(data)) !== null && _groupRenderer !== void 0 ? _groupRenderer : /*#__PURE__*/jsxs("div", {
188
+ className: "flex gap-1 items-center",
189
+ children: [/*#__PURE__*/jsx("span", {
190
+ children: data.key
191
+ }), /*#__PURE__*/jsxs("span", {
192
+ className: "text-sm",
193
+ children: ["(", data.itemCount, ")"]
194
+ })]
195
+ })]
196
+ }, key) : /*#__PURE__*/jsx(BodyRow, {
163
197
  rowKey: key,
164
198
  index: index,
165
199
  checkableRows: checkableRows,
@@ -1,49 +1,83 @@
1
1
  'use client';
2
2
 
3
3
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
4
+ import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
4
5
  import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
5
- import { useVirtualizer } from '@tanstack/react-virtual';
6
- import { useRef, useReducer, useCallback } from 'react';
6
+ import { groupBy, compareValues } from '@react-fabric/utilities';
7
+ import { useVirtualizer, defaultRangeExtractor } from '@tanstack/react-virtual';
8
+ import { useReducer, useRef, useMemo, useState, useCallback, useEffect } from 'react';
7
9
 
8
10
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
9
11
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
10
- var useVirtualTable = function useVirtualTable(data, keyProperty, onCheckChanged) {
12
+ var useVirtualTable = function useVirtualTable(data, options) {
11
13
  var _virtualizer$range;
12
14
  // TODO: refactor data into item list, apply grouping if groupColumn provided
13
15
  // TODO: when grouping maintain map of group with children, {___GROUP___:true, label, items, open}
14
16
 
15
- var scrollerRef = useRef(null);
16
- var virtualizer = useVirtualizer({
17
- count: data.length,
18
- getScrollElement: function getScrollElement() {
19
- return scrollerRef.current;
20
- },
21
- estimateSize: function estimateSize() {
22
- return 24;
23
- }
24
- });
25
17
  var _useReducer = useReducer(function (state, action) {
18
+ if (action.type === "updateState") {
19
+ state.checked = action.checked;
20
+ }
26
21
  if (action.type === "expand") {
27
22
  if (state.expanded.includes(action.key)) state.expanded.splice(state.expanded.indexOf(action.key), 1);else state.expanded.push(action.key);
28
23
  }
29
24
  if (action.type === "check") {
25
+ var _options$onCheckChang;
30
26
  if (state.checked.includes(action.key)) state.checked.splice(state.checked.indexOf(action.key), 1);else state.checked.push(action.key);
31
- onCheckChanged === null || onCheckChanged === void 0 || onCheckChanged(state.checked);
27
+ (_options$onCheckChang = options.onCheckChanged) === null || _options$onCheckChang === void 0 || _options$onCheckChang.call(options, state.checked);
32
28
  }
33
29
  if (action.type === "checkall") {
30
+ var _options$onCheckChang2;
34
31
  if (state.allChecked !== 0) {
35
32
  state.checked = [];
36
- } else if (keyProperty) {
33
+ } else if (options.keyProperty) {
37
34
  state.checked = data.map(function (item) {
38
- return item[keyProperty];
35
+ return item[options.keyProperty];
36
+ });
37
+ }
38
+ (_options$onCheckChang2 = options.onCheckChanged) === null || _options$onCheckChang2 === void 0 || _options$onCheckChang2.call(options, state.checked);
39
+ }
40
+ var checkList = data.filter(function (hit) {
41
+ return state.checked.includes(hit[options.keyProperty]);
42
+ });
43
+ if (action.type === "groupExpand") {
44
+ var group = state.groups.find(function (group) {
45
+ return group.key === action.key;
46
+ });
47
+ if (group) {
48
+ group.open = !group.open;
49
+ state.groups = state.groups.slice();
50
+ state.items = state.groups.map(function (group) {
51
+ return [group, group.open ? state.grouped[group.key] : undefined];
52
+ }).flat(2).filter(Boolean);
53
+ }
54
+ }
55
+ if (action.type === "grouped") {
56
+ if (action.key) {
57
+ state.grouped = groupBy(data, action.key);
58
+ state.groups = Object.keys(state.grouped).sort(compareValues("asc")).map(function (group) {
59
+ return {
60
+ __GROUP__: true,
61
+ open: true,
62
+ key: group,
63
+ items: state.grouped[group],
64
+ itemCount: state.grouped[group].length
65
+ };
39
66
  });
67
+ state.items = state.groups.map(function (group) {
68
+ return [group].concat(_toConsumableArray(state.grouped[group.key]));
69
+ }).flat();
70
+ } else {
71
+ state.items = data;
40
72
  }
41
- onCheckChanged === null || onCheckChanged === void 0 || onCheckChanged(state.checked);
42
73
  }
43
74
  return _objectSpread(_objectSpread({}, state), {}, {
44
- allChecked: state.checked.length === data.length ? 1 : state.checked.length ? 2 : 0
75
+ allChecked: checkList.length === data.length ? 1 : state.checked.length ? 2 : 0
45
76
  });
46
77
  }, {
78
+ items: data,
79
+ grouped: {},
80
+ groups: [],
47
81
  checked: [],
48
82
  expanded: [],
49
83
  allChecked: 0
@@ -51,19 +85,72 @@ var useVirtualTable = function useVirtualTable(data, keyProperty, onCheckChanged
51
85
  _useReducer2 = _slicedToArray(_useReducer, 2),
52
86
  state = _useReducer2[0],
53
87
  dispatch = _useReducer2[1];
88
+ var activeStickyIndexRef = useRef(0);
89
+ var stickyIndexes = useMemo(function () {
90
+ return state.items.map(function (hit, idx) {
91
+ return "__GROUP__" in hit ? idx : undefined;
92
+ }).filter(Boolean);
93
+ }, [state.items]);
94
+ var isActiveSticky = function isActiveSticky(index) {
95
+ return activeStickyIndexRef.current === index;
96
+ };
97
+ var _useState = useState(false),
98
+ _useState2 = _slicedToArray(_useState, 2),
99
+ hasActiveSticky = _useState2[0],
100
+ setHasActiveSticky = _useState2[1];
101
+ var scrollerRef = useRef(null);
102
+ var virtualizer = useVirtualizer({
103
+ count: state.items.length,
104
+ getScrollElement: function getScrollElement() {
105
+ return scrollerRef.current;
106
+ },
107
+ estimateSize: function estimateSize() {
108
+ return 32;
109
+ },
110
+ rangeExtractor: useCallback(function (range) {
111
+ var _reverse$find;
112
+ activeStickyIndexRef.current = (_reverse$find = _toConsumableArray(stickyIndexes).reverse().find(function (index) {
113
+ return range.startIndex > index;
114
+ })) !== null && _reverse$find !== void 0 ? _reverse$find : 0;
115
+ setHasActiveSticky(range.startIndex !== activeStickyIndexRef.current);
116
+ var next = new Set([activeStickyIndexRef.current].concat(_toConsumableArray(defaultRangeExtractor(range))));
117
+ return _toConsumableArray(next);
118
+ }, [stickyIndexes])
119
+ });
54
120
  var virtualItems = virtualizer.getVirtualItems();
55
121
  var getData = useCallback(function (index) {
56
- return data[index];
57
- }, [data]);
122
+ return state.items[index];
123
+ }, [state.items]);
124
+ useEffect(function () {
125
+ dispatch({
126
+ type: "grouped",
127
+ key: options.groupProperty
128
+ });
129
+ }, [options.groupProperty]);
130
+ useEffect(function () {
131
+ var _options$checked;
132
+ dispatch({
133
+ type: "updateState",
134
+ checked: (_options$checked = options.checked) !== null && _options$checked !== void 0 ? _options$checked : []
135
+ });
136
+ }, [options.checked]);
58
137
  return {
59
138
  scrollerRef: scrollerRef,
60
139
  items: virtualItems,
61
140
  checkState: state,
62
141
  getData: getData,
63
142
  virtualizer: virtualizer,
143
+ hasActiveSticky: hasActiveSticky,
144
+ isActiveSticky: isActiveSticky,
64
145
  top: (_virtualizer$range = virtualizer.range) === null || _virtualizer$range === void 0 ? void 0 : _virtualizer$range.startIndex,
65
146
  totalSize: virtualizer.getTotalSize,
66
147
  measureElement: virtualizer.measureElement,
148
+ toggleGroupExpand: function toggleGroupExpand(key) {
149
+ return dispatch({
150
+ type: "groupExpand",
151
+ key: key
152
+ });
153
+ },
67
154
  toggleExpand: function toggleExpand(key) {
68
155
  return dispatch({
69
156
  type: "expand",
@@ -1,2 +1,2 @@
1
1
  import { type TableProps } from "./types";
2
- export declare const Table: <T extends KeyValue<any> = KeyValue<any>>({ ref, data, columns, keyProperty, checkableRows, initialScroll, hideableColumns, sort, loading, emptyDisplay, canExpand, children, onSort, onScroll, onRowClick, onCheckedChanged, }: TableProps<T>) => import("react/jsx-runtime").JSX.Element;
2
+ export declare const Table: <T extends KeyValue<any> = KeyValue<any>>({ ref, data, columns, keyProperty, groupProperty, checkableRows, initialScroll, hideableColumns, sort, loading, checked, emptyDisplay, groupRenderer, canExpand, children, onSort, onScroll, onRowClick, onCheckedChanged, }: TableProps<T>) => import("react/jsx-runtime").JSX.Element;
@@ -7,7 +7,7 @@ export interface TableColumn<T = KeyValue> extends CssProp, IconProps, TestProps
7
7
  id: keyof T | string;
8
8
  label?: string;
9
9
  tooltip?: string;
10
- actions?: ReactElement;
10
+ actions?: ReactElement[];
11
11
  align?: "start" | "center" | "end";
12
12
  locked?: "start" | "end";
13
13
  hidden?: boolean;
@@ -34,12 +34,15 @@ export interface TableProps<T = KeyValue> extends RefProp<TableRef> {
34
34
  columns: Array<TableColumn<T>>;
35
35
  data: T[];
36
36
  keyProperty?: keyof T;
37
+ groupProperty?: keyof T;
38
+ groupRenderer?: (key: AnyObject) => ReactElement;
37
39
  emptyDisplay?: ReactElement;
38
40
  /**
39
41
  * checkable rows
40
42
  */
43
+ checked?: AnyObject[];
41
44
  checkableRows?: boolean;
42
- onCheckedChanged?: (rows: Array<keyof T>) => void;
45
+ onCheckedChanged?: (rows: AnyObject[]) => void;
43
46
  /**
44
47
  * sorting
45
48
  */
@@ -1,18 +1,29 @@
1
1
  /// <reference types="react" />
2
- interface DataState {
3
- expanded: Key[];
4
- checked: Key[];
2
+ interface DataState<T = KeyValue> {
3
+ items: T[];
4
+ grouped: KeyValue<T[]>;
5
+ groups: AnyObject[];
6
+ expanded: AnyObject[];
7
+ checked: AnyObject[];
5
8
  allChecked: 0 | 1 | 2;
6
9
  }
7
- export declare const useVirtualTable: (data: KeyValue[], keyProperty?: Key, onCheckChanged?: (checked: Key[]) => void) => {
10
+ export declare const useVirtualTable: <T extends KeyValue<any> = KeyValue<any>>(data: T[], options: {
11
+ checked?: AnyObject[];
12
+ keyProperty: keyof T;
13
+ groupProperty?: keyof T;
14
+ onCheckChanged?: (checked: AnyObject[]) => void;
15
+ }) => {
8
16
  scrollerRef: import("react").RefObject<HTMLDivElement>;
9
17
  items: import("@tanstack/virtual-core").VirtualItem<Element>[];
10
- checkState: DataState;
11
- getData: (index: number) => KeyValue<any>;
18
+ checkState: DataState<T>;
19
+ getData: (index: number) => T;
12
20
  virtualizer: import("@tanstack/virtual-core").Virtualizer<HTMLDivElement, Element>;
21
+ hasActiveSticky: boolean;
22
+ isActiveSticky: (index: number) => boolean;
13
23
  top: number | undefined;
14
24
  totalSize: () => number;
15
25
  measureElement: (node: Element | null | undefined) => void;
26
+ toggleGroupExpand: (key: Key) => void;
16
27
  toggleExpand: (key: Key) => void;
17
28
  toggleChecked: (key: Key) => void;
18
29
  toggleAllChecked: () => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-fabric/data",
3
- "version": "1.0.0-beta.29",
3
+ "version": "1.0.0-beta.30",
4
4
  "description": "RUF: Data package",
5
5
  "author": "Adarsh Pastakia <adarshpastakia@outlook.com>",
6
6
  "license": "MIT",
@@ -33,10 +33,10 @@
33
33
  "watch": "npm-run-all -p watch:rollup watch:dts"
34
34
  },
35
35
  "dependencies": {
36
- "@react-fabric/core": "^1.0.0-beta.29",
37
- "@react-fabric/date": "^1.0.0-beta.29",
38
- "@react-fabric/form": "^1.0.0-beta.29",
39
- "@react-fabric/utilities": "^1.0.0-beta.29",
36
+ "@react-fabric/core": "^1.0.0-beta.30",
37
+ "@react-fabric/date": "^1.0.0-beta.30",
38
+ "@react-fabric/form": "^1.0.0-beta.30",
39
+ "@react-fabric/utilities": "^1.0.0-beta.30",
40
40
  "@tanstack/react-virtual": "^3.8.6",
41
41
  "classnames": "^2.5.1",
42
42
  "color": "^4.2.3",
@@ -52,5 +52,5 @@
52
52
  "node": ">=18.12.0",
53
53
  "npm": ">=8.19.0"
54
54
  },
55
- "gitHead": "1011b13034b9f8f28c292468aed602217496da4a"
55
+ "gitHead": "5b10298b7627c2e56bcccf18100b6d85a02c9b06"
56
56
  }
@@ -23,6 +23,7 @@
23
23
 
24
24
  import {
25
25
  CoreIcons,
26
+ Divider,
26
27
  DropdownTool,
27
28
  Icon,
28
29
  Menu,
@@ -94,15 +95,21 @@ export const HeaderCell = ({
94
95
  />,
95
96
  );
96
97
  }
98
+ if (sortable && actions) {
99
+ ret.push(<Divider />);
100
+ }
101
+ if (actions) {
102
+ ret.push(...actions);
103
+ }
97
104
  return ret;
98
- }, [sortable]);
105
+ }, [sortable, actions]);
99
106
 
100
107
  return (
101
108
  <div
102
109
  role="none"
103
110
  data-id={id}
104
111
  onClick={() => handleSort()}
105
- className="group font-medium border-e flex flex-nowrap text-start items-center table-header-cell"
112
+ className="group/tool font-medium border-e flex flex-nowrap text-start items-center table-header-cell"
106
113
  style={{
107
114
  width: width ?? COL_DEFAULT_WIDTH,
108
115
  minWidth: minWidth ?? COL_MIN_WIDTH,
@@ -21,8 +21,15 @@
21
21
  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
22
  */
23
23
 
24
- import { EmptyContent, Loading, useDebounce } from "@react-fabric/core";
24
+ import {
25
+ CoreIcons,
26
+ EmptyContent,
27
+ Icon,
28
+ Loading,
29
+ useDebounce,
30
+ } from "@react-fabric/core";
25
31
  import { debounce } from "@react-fabric/utilities";
32
+ import classNames from "classnames";
26
33
  import {
27
34
  useEffect,
28
35
  useImperativeHandle,
@@ -45,13 +52,16 @@ export const Table = <T extends KeyValue = KeyValue>({
45
52
  ref,
46
53
  data,
47
54
  columns,
48
- keyProperty,
55
+ keyProperty = "id",
56
+ groupProperty,
49
57
  checkableRows,
50
58
  initialScroll,
51
59
  hideableColumns,
52
60
  sort,
53
61
  loading,
62
+ checked,
54
63
  emptyDisplay,
64
+ groupRenderer,
55
65
  canExpand,
56
66
  children,
57
67
  onSort,
@@ -72,13 +82,21 @@ export const Table = <T extends KeyValue = KeyValue>({
72
82
  top,
73
83
  checkState,
74
84
  virtualizer,
85
+ hasActiveSticky,
75
86
  toggleExpand,
76
87
  toggleChecked,
77
88
  toggleAllChecked,
89
+ toggleGroupExpand,
78
90
  getData,
79
91
  totalSize,
92
+ isActiveSticky,
80
93
  measureElement,
81
- } = useVirtualTable(data, keyProperty, fireCheckChanged);
94
+ } = useVirtualTable(data, {
95
+ checked,
96
+ keyProperty,
97
+ groupProperty,
98
+ onCheckChanged: fireCheckChanged,
99
+ });
82
100
  const refBody = useRef<HTMLDivElement>(null);
83
101
 
84
102
  const wrapperStart = useMemo(
@@ -184,10 +202,39 @@ export const Table = <T extends KeyValue = KeyValue>({
184
202
  style={{ height: totalSize() }}
185
203
  ref={refBody}
186
204
  >
187
- <div style={{ height: items[0]?.start }} />
205
+ <div
206
+ style={{
207
+ height: items[hasActiveSticky ? 1 : 0]?.start,
208
+ }}
209
+ />
188
210
  {items.map(({ index, key }) => {
189
211
  const data = getData(index);
190
- return (
212
+ return "__GROUP__" in data ? (
213
+ <div
214
+ key={key}
215
+ ref={measureElement}
216
+ data-index={index}
217
+ className={classNames(
218
+ "px-2 py-1 text-md bg-base border-y border-tint-100 cursor-pointer flex items-center gap-1",
219
+ isActiveSticky(index) && "sticky top-8 z-30",
220
+ )}
221
+ role="none"
222
+ onClick={() => toggleGroupExpand(data.key)}
223
+ >
224
+ <Icon
225
+ rtlFlip
226
+ icon={
227
+ data.open ? CoreIcons.chevronDown : CoreIcons.chevronRight
228
+ }
229
+ />
230
+ {groupRenderer?.(data) ?? (
231
+ <div className="flex gap-1 items-center">
232
+ <span>{data.key}</span>
233
+ <span className="text-sm">({data.itemCount})</span>
234
+ </div>
235
+ )}
236
+ </div>
237
+ ) : (
191
238
  <BodyRow
192
239
  rowKey={key}
193
240
  index={index}
@@ -41,7 +41,7 @@ export interface TableColumn<T = KeyValue>
41
41
  id: keyof T | string;
42
42
  label?: string;
43
43
  tooltip?: string;
44
- actions?: ReactElement;
44
+ actions?: ReactElement[];
45
45
  align?: "start" | "center" | "end";
46
46
  locked?: "start" | "end";
47
47
  hidden?: boolean;
@@ -77,12 +77,16 @@ export interface TableProps<T = KeyValue> extends RefProp<TableRef> {
77
77
  columns: Array<TableColumn<T>>;
78
78
  data: T[];
79
79
  keyProperty?: keyof T;
80
+ groupProperty?: keyof T;
81
+ groupRenderer?: (key: AnyObject) => ReactElement;
80
82
  emptyDisplay?: ReactElement;
83
+
81
84
  /**
82
85
  * checkable rows
83
86
  */
87
+ checked?: AnyObject[];
84
88
  checkableRows?: boolean;
85
- onCheckedChanged?: (rows: Array<keyof T>) => void;
89
+ onCheckedChanged?: (rows: AnyObject[]) => void;
86
90
  /**
87
91
  * sorting
88
92
  */
@@ -21,37 +21,55 @@
21
21
  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
22
  */
23
23
 
24
- import { useVirtualizer } from "@tanstack/react-virtual";
25
- import { useCallback, useReducer, useRef } from "react";
24
+ import { compareValues, groupBy } from "@react-fabric/utilities";
25
+ import {
26
+ defaultRangeExtractor,
27
+ type Range,
28
+ useVirtualizer,
29
+ } from "@tanstack/react-virtual";
30
+ import {
31
+ useCallback,
32
+ useEffect,
33
+ useMemo,
34
+ useReducer,
35
+ useRef,
36
+ useState,
37
+ } from "react";
26
38
 
27
- interface DataState {
28
- expanded: Key[];
29
- checked: Key[];
39
+ interface DataState<T = KeyValue> {
40
+ items: T[];
41
+ grouped: KeyValue<T[]>;
42
+ groups: AnyObject[];
43
+ expanded: AnyObject[];
44
+ checked: AnyObject[];
30
45
  allChecked: 0 | 1 | 2;
31
46
  }
32
47
 
33
48
  type DataAction =
34
- | { type: "expand"; key: Key }
35
- | { type: "check"; key: Key }
49
+ | { type: "updateState"; checked: AnyObject[] }
50
+ | { type: "groupExpand"; key: AnyObject }
51
+ | { type: "grouped"; key: AnyObject }
52
+ | { type: "expand"; key: AnyObject }
53
+ | { type: "check"; key: AnyObject }
36
54
  | { type: "checkall" };
37
55
 
38
- export const useVirtualTable = (
39
- data: KeyValue[],
40
- keyProperty?: Key,
41
- onCheckChanged?: (checked: Key[]) => void,
56
+ export const useVirtualTable = <T extends KeyValue = KeyValue>(
57
+ data: T[],
58
+ options: {
59
+ checked?: AnyObject[];
60
+ keyProperty: keyof T;
61
+ groupProperty?: keyof T;
62
+ onCheckChanged?: (checked: AnyObject[]) => void;
63
+ },
42
64
  ) => {
43
65
  // TODO: refactor data into item list, apply grouping if groupColumn provided
44
66
  // TODO: when grouping maintain map of group with children, {___GROUP___:true, label, items, open}
45
67
 
46
- const scrollerRef = useRef<HTMLDivElement>(null);
47
- const virtualizer = useVirtualizer({
48
- count: data.length,
49
- getScrollElement: () => scrollerRef.current,
50
- estimateSize: () => 24,
51
- });
52
-
53
68
  const [state, dispatch] = useReducer(
54
- (state: DataState, action: DataAction) => {
69
+ (state: DataState<T>, action: DataAction) => {
70
+ if (action.type === "updateState") {
71
+ state.checked = action.checked;
72
+ }
55
73
  if (action.type === "expand") {
56
74
  if (state.expanded.includes(action.key))
57
75
  state.expanded.splice(state.expanded.indexOf(action.key), 1);
@@ -61,51 +79,134 @@ export const useVirtualTable = (
61
79
  if (state.checked.includes(action.key))
62
80
  state.checked.splice(state.checked.indexOf(action.key), 1);
63
81
  else state.checked.push(action.key);
64
- onCheckChanged?.(state.checked);
82
+ options.onCheckChanged?.(state.checked);
65
83
  }
66
84
  if (action.type === "checkall") {
67
85
  if (state.allChecked !== 0) {
68
86
  state.checked = [];
69
- } else if (keyProperty) {
70
- state.checked = data.map((item) => item[keyProperty]);
87
+ } else if (options.keyProperty) {
88
+ state.checked = data.map((item) => item[options.keyProperty]);
89
+ }
90
+ options.onCheckChanged?.(state.checked);
91
+ }
92
+ const checkList = data.filter((hit) =>
93
+ state.checked.includes(hit[options.keyProperty]),
94
+ );
95
+ if (action.type === "groupExpand") {
96
+ const group = state.groups.find((group) => group.key === action.key);
97
+ if (group) {
98
+ group.open = !group.open;
99
+ state.groups = state.groups.slice();
100
+ state.items = state.groups
101
+ .map((group) => [
102
+ group,
103
+ group.open ? state.grouped[group.key] : undefined,
104
+ ])
105
+ .flat(2)
106
+ .filter(Boolean) as any;
107
+ }
108
+ }
109
+ if (action.type === "grouped") {
110
+ if (action.key) {
111
+ state.grouped = groupBy<T>(data, action.key);
112
+ state.groups = Object.keys(state.grouped)
113
+ .sort(compareValues("asc"))
114
+ .map((group) => ({
115
+ __GROUP__: true,
116
+ open: true,
117
+ key: group,
118
+ items: state.grouped[group],
119
+ itemCount: state.grouped[group].length,
120
+ }));
121
+ state.items = state.groups
122
+ .map((group) => [group, ...state.grouped[group.key]])
123
+ .flat() as any;
124
+ } else {
125
+ state.items = data;
71
126
  }
72
- onCheckChanged?.(state.checked);
73
127
  }
74
128
  return {
75
129
  ...state,
76
130
  allChecked:
77
- state.checked.length === data.length
78
- ? 1
79
- : state.checked.length
80
- ? 2
81
- : 0,
82
- } as DataState;
131
+ checkList.length === data.length ? 1 : state.checked.length ? 2 : 0,
132
+ } as DataState<T>;
83
133
  },
84
134
  {
135
+ items: data,
136
+ grouped: {},
137
+ groups: [],
85
138
  checked: [],
86
139
  expanded: [],
87
140
  allChecked: 0,
88
141
  },
89
142
  );
90
143
 
144
+ const activeStickyIndexRef = useRef(0);
145
+ const stickyIndexes = useMemo<number[]>(
146
+ () =>
147
+ state.items
148
+ .map((hit, idx) => ("__GROUP__" in hit ? idx : undefined))
149
+ .filter(Boolean) as number[],
150
+ [state.items],
151
+ );
152
+ const isActiveSticky = (index: number) =>
153
+ activeStickyIndexRef.current === index;
154
+
155
+ const [hasActiveSticky, setHasActiveSticky] = useState(false);
156
+ const scrollerRef = useRef<HTMLDivElement>(null);
157
+ const virtualizer = useVirtualizer({
158
+ count: state.items.length,
159
+ getScrollElement: () => scrollerRef.current,
160
+ estimateSize: () => 32,
161
+ rangeExtractor: useCallback(
162
+ (range: Range) => {
163
+ activeStickyIndexRef.current =
164
+ [...stickyIndexes]
165
+ .reverse()
166
+ .find((index) => range.startIndex > index) ?? 0;
167
+
168
+ setHasActiveSticky(range.startIndex !== activeStickyIndexRef.current);
169
+
170
+ const next = new Set([
171
+ activeStickyIndexRef.current,
172
+ ...defaultRangeExtractor(range),
173
+ ]);
174
+
175
+ return [...next];
176
+ },
177
+ [stickyIndexes],
178
+ ),
179
+ });
180
+
91
181
  const virtualItems = virtualizer.getVirtualItems();
92
182
 
93
183
  const getData = useCallback(
94
184
  (index: number) => {
95
- return data[index];
185
+ return state.items[index];
96
186
  },
97
- [data],
187
+ [state.items],
98
188
  );
99
189
 
190
+ useEffect(() => {
191
+ dispatch({ type: "grouped", key: options.groupProperty });
192
+ }, [options.groupProperty]);
193
+
194
+ useEffect(() => {
195
+ dispatch({ type: "updateState", checked: options.checked ?? [] });
196
+ }, [options.checked]);
197
+
100
198
  return {
101
199
  scrollerRef,
102
200
  items: virtualItems,
103
201
  checkState: state,
104
202
  getData,
105
203
  virtualizer,
204
+ hasActiveSticky,
205
+ isActiveSticky,
106
206
  top: virtualizer.range?.startIndex,
107
207
  totalSize: virtualizer.getTotalSize,
108
208
  measureElement: virtualizer.measureElement,
209
+ toggleGroupExpand: (key: Key) => dispatch({ type: "groupExpand", key }),
109
210
  toggleExpand: (key: Key) => dispatch({ type: "expand", key }),
110
211
  toggleChecked: (key: Key) => dispatch({ type: "check", key }),
111
212
  toggleAllChecked: () => dispatch({ type: "checkall" }),