@react-fabric/data 1.0.0-beta.0 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/cjs/table/AddColumn.js +56 -0
  2. package/dist/cjs/table/BodyCell.js +13 -4
  3. package/dist/cjs/table/CheckboxCell.js +44 -0
  4. package/dist/cjs/table/Context.js +43 -0
  5. package/dist/cjs/table/EmptyCell.js +52 -0
  6. package/dist/cjs/table/HeaderCell.js +77 -32
  7. package/dist/cjs/table/Table.js +168 -93
  8. package/dist/cjs/table/types.js +32 -0
  9. package/dist/cjs/table/useResizer.js +65 -0
  10. package/dist/cjs/table/useTableColumns.js +45 -8
  11. package/dist/cjs/table/useVirtualTable.js +42 -25
  12. package/dist/cjs/tree/TreePanel.js +14 -2
  13. package/dist/cjs/tree/useTree.js +7 -0
  14. package/dist/esm/table/AddColumn.js +56 -0
  15. package/dist/esm/table/BodyCell.js +13 -4
  16. package/dist/esm/table/CheckboxCell.js +44 -0
  17. package/dist/esm/table/Context.js +42 -0
  18. package/dist/esm/table/EmptyCell.js +52 -0
  19. package/dist/esm/table/HeaderCell.js +79 -34
  20. package/dist/esm/table/Table.js +169 -94
  21. package/dist/esm/table/types.js +30 -0
  22. package/dist/esm/table/useResizer.js +65 -0
  23. package/dist/esm/table/useTableColumns.js +46 -9
  24. package/dist/esm/table/useVirtualTable.js +43 -26
  25. package/dist/esm/tree/TreePanel.js +15 -3
  26. package/dist/esm/tree/useTree.js +7 -0
  27. package/dist/types/index.d.ts +2 -0
  28. package/dist/types/table/AddColumn.d.ts +5 -0
  29. package/dist/types/table/CheckboxCell.d.ts +4 -0
  30. package/dist/types/table/Context.d.ts +8 -0
  31. package/dist/types/table/EmptyCell.d.ts +2 -0
  32. package/dist/types/table/HeaderCell.d.ts +2 -2
  33. package/dist/types/table/Table.d.ts +1 -1
  34. package/dist/types/table/types.d.ts +30 -3
  35. package/dist/types/table/useResizer.d.ts +1 -0
  36. package/dist/types/table/useTableColumns.d.ts +6 -4
  37. package/dist/types/table/useVirtualTable.d.ts +9 -1
  38. package/dist/types/tree/TreePanel.d.ts +1 -1
  39. package/dist/types/tree/types.d.ts +6 -2
  40. package/dist/types/tree/useTree.d.ts +1 -0
  41. package/package.json +5 -5
  42. package/src/index.ts +2 -0
  43. package/src/table/AddColumn.tsx +55 -0
  44. package/src/table/BodyCell.tsx +18 -4
  45. package/src/table/CheckboxCell.tsx +48 -0
  46. package/src/table/Context.tsx +70 -0
  47. package/src/table/EmptyCell.tsx +57 -0
  48. package/src/table/HeaderCell.tsx +92 -25
  49. package/src/table/Table.tsx +178 -88
  50. package/src/table/types.ts +28 -2
  51. package/src/table/useResizer.ts +66 -0
  52. package/src/table/useTableColumns.ts +51 -18
  53. package/src/table/useVirtualTable.ts +47 -2
  54. package/src/tree/TreePanel.tsx +12 -1
  55. package/src/tree/types.ts +8 -1
  56. package/src/tree/useTree.ts +5 -0
@@ -21,21 +21,51 @@
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 { useCallback, useMemo } from "react";
24
+ import { EmptyContent, Loading, useDebounce } from "@react-fabric/core";
25
+ import classNames from "classnames";
26
+ import { useImperativeHandle, useMemo, useRef } from "react";
27
+ import { useTranslation } from "react-i18next";
28
+ import { AddColumn } from "./AddColumn";
25
29
  import { BodyCell } from "./BodyCell";
30
+ import { CheckboxCell } from "./CheckboxCell";
31
+ import { TableProvider } from "./Context";
32
+ import { EmptyCell } from "./EmptyCell";
26
33
  import { HeaderCell } from "./HeaderCell";
27
- import { type ColumnType, type TableProps } from "./types";
34
+ import { type TableProps } from "./types";
28
35
  import { useTableColumns } from "./useTableColumns";
29
36
  import { useVirtualTable } from "./useVirtualTable";
30
- import classNames from "classnames";
31
37
 
32
38
  export const Table = <T extends KeyValue = KeyValue>({
39
+ ref,
33
40
  data,
34
41
  columns,
42
+ keyProperty,
43
+ checkableRows,
44
+ hideableColumns,
45
+ sort,
46
+ loading,
47
+ onSort,
48
+ onRowClick,
49
+ onCheckedChanged,
35
50
  }: TableProps<T>) => {
36
- const { columnMap } = useTableColumns(columns);
37
- const { scrollerRef, items, getData, totalSize, measureElement } =
38
- useVirtualTable(data);
51
+ const { t } = useTranslation("data");
52
+ const fireCheckChanged = useDebounce(
53
+ (checkedIds: Array<keyof T>) => onCheckedChanged?.(checkedIds),
54
+ [],
55
+ );
56
+
57
+ const { state, onHide } = useTableColumns(columns);
58
+ const {
59
+ scrollerRef,
60
+ items,
61
+ checkState,
62
+ toggleChecked,
63
+ toggleAllChecked,
64
+ getData,
65
+ totalSize,
66
+ measureElement,
67
+ } = useVirtualTable(data, keyProperty, fireCheckChanged);
68
+ const refBody = useRef<HTMLDivElement>(null);
39
69
 
40
70
  const wrapperStart = useMemo(
41
71
  () => "bg-inherit sticky start-0 flex flex-nowrap z-1",
@@ -45,99 +75,159 @@ export const Table = <T extends KeyValue = KeyValue>({
45
75
  () => "bg-inherit sticky end-0 flex flex-nowrap z-1 border-s -ms-px",
46
76
  [],
47
77
  );
48
- const emptyCol = useCallback(
49
- (col: ColumnType, idc: number) => (
50
- <div
51
- key={`blank:${idc}`}
52
- className="overflow-hidden border-e"
53
- style={{
54
- width: col.width ?? "12rem",
55
- minWidth: col.minWidth ?? "2rem",
56
- maxWidth: col.maxWidth ?? "32rem",
57
- }}
58
- />
59
- ),
78
+
79
+ useImperativeHandle(
80
+ ref,
81
+ () => ({
82
+ hilight: (row: number) => {
83
+ refBody.current
84
+ ?.querySelectorAll<HTMLElement>(`.datatable-row[data-hilight="true"]`)
85
+ .forEach((el) => el && (el.dataset.hilight = undefined));
86
+ const el = refBody.current?.querySelector<HTMLElement>(
87
+ `[data-row="${row}"]`,
88
+ );
89
+ el?.scrollIntoView({ behavior: "smooth", block: "center" });
90
+ el && (el.dataset.hilight = "true");
91
+ },
92
+ unhilight: () => {
93
+ refBody.current
94
+ ?.querySelectorAll<HTMLElement>(`.datatable-row[data-hilight="true"]`)
95
+ .forEach((el) => el && (el.dataset.hilight = undefined));
96
+ },
97
+ scrollTo: (row: number) => {
98
+ const el = refBody.current?.querySelector(`[data-row="${row}"]`);
99
+ el?.scrollIntoView({ behavior: "smooth" });
100
+ },
101
+ }),
60
102
  [],
61
103
  );
62
104
 
63
105
  return (
64
- <div
65
- className="grid area-content overflow-auto relative"
66
- style={{
67
- gridTemplate: `"head" auto "content" 1fr "foot" auto/1fr`,
68
- }}
69
- ref={scrollerRef}
70
- >
71
- <div className="bg-base font-medium sticky top-0 area-head border-b select-none flex flex-nowrap z-2">
72
- <div className={wrapperStart}>
73
- {columnMap.start?.map((col, idx) => (
74
- <HeaderCell key={idx} {...col} />
75
- ))}
76
- </div>
77
- {columnMap.cols?.map((col, idx) => <HeaderCell key={idx} {...col} />)}
78
- <div className={wrapperEnd}>
79
- {columnMap.end?.map((col, idx) => <HeaderCell key={idx} {...col} />)}
80
- </div>
81
- </div>
106
+ <TableProvider>
82
107
  <div
83
- className="area-content flex flex-col flex-nowrap"
84
- style={{ height: totalSize() }}
108
+ className="grid area-content overflow-auto relative"
109
+ style={{
110
+ gridTemplate: `"head" auto "loader" auto "content" 1fr "foot" auto/1fr`,
111
+ }}
112
+ ref={scrollerRef}
85
113
  >
86
- <div style={{ height: items[0]?.start }} />
87
- {items.map(({ index, key }) => (
88
- <div
89
- key={key}
90
- className={classNames(
91
- "flex flex-nowrap",
92
- index % 2 ? "bg-even" : "bg-odd",
93
- )}
94
- data-index={index}
95
- ref={measureElement}
96
- >
97
- <div className={wrapperStart}>
98
- {columnMap.start?.map((col, ids) => (
99
- <BodyCell
100
- key={`${key}:${ids}`}
101
- column={col}
102
- item={getData(index)}
103
- />
104
- ))}
105
- </div>
106
- {columnMap.cols?.map((col, idc) => (
107
- <BodyCell
108
- key={`${key}:${idc}`}
109
- column={col}
110
- item={getData(index)}
114
+ <div className="bg-base font-medium sticky top-0 area-head border-b select-none flex flex-nowrap z-2">
115
+ <div className={wrapperStart}>
116
+ {checkableRows && (
117
+ <CheckboxCell
118
+ state={checkState.allChecked}
119
+ onClick={toggleAllChecked}
111
120
  />
121
+ )}
122
+ {state.start?.map((col, idx) => (
123
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
112
124
  ))}
113
- <div className={wrapperEnd}>
114
- {columnMap.end?.map((col, ide) => (
115
- <BodyCell
116
- key={`${key}:${ide}`}
117
- column={col}
118
- item={getData(index)}
119
- />
120
- ))}
121
- </div>
122
125
  </div>
123
- ))}
124
- <div className="flex-1 flex flex-nowrap">
125
- <div className={wrapperStart}>{columnMap.start?.map(emptyCol)}</div>
126
- {columnMap.cols?.map(emptyCol)}
127
- <div className={wrapperEnd}>{columnMap.end?.map(emptyCol)}</div>
128
- </div>
129
- </div>
130
- <div className="area-foot bg-dimmed border-t sticky bottom-0 flex flex-nowrap z-2">
131
- <div className={wrapperStart}>
132
- {columnMap.start?.map((col, idx) => (
133
- <HeaderCell key={idx} {...col} />
126
+ {state.cols?.map((col, idx) => (
127
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
134
128
  ))}
129
+ <div className={wrapperEnd}>
130
+ {state.end?.map((col, idx) => (
131
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
132
+ ))}
133
+
134
+ {hideableColumns && (
135
+ <AddColumn
136
+ onClick={onHide}
137
+ columns={state.columns.filter((col) => col.hideable !== false)}
138
+ />
139
+ )}
140
+ </div>
135
141
  </div>
136
- {columnMap.cols?.map((col, idx) => <HeaderCell key={idx} {...col} />)}
137
- <div className={wrapperEnd}>
138
- {columnMap.end?.map((col, idx) => <HeaderCell key={idx} {...col} />)}
139
- </div>
142
+ {loading && <Loading />}
143
+ {data.length > 0 && (
144
+ <div
145
+ className="area-content flex flex-col flex-nowrap"
146
+ style={{ height: totalSize() }}
147
+ ref={refBody}
148
+ >
149
+ <div style={{ height: items[0]?.start }} />
150
+ {items.map(({ index, key }) => {
151
+ const data = getData(index);
152
+ return (
153
+ <div
154
+ key={key}
155
+ role="none"
156
+ data-row={index}
157
+ className={classNames(
158
+ "flex flex-nowrap datatable-row data-[hilight]:outline-1 -outline-offset-1 outline-primary-500",
159
+ index % 2 ? "bg-even" : "bg-odd",
160
+ onRowClick && "hover:bg-primary-50 active:bg-primary-100",
161
+ )}
162
+ onClick={() =>
163
+ checkableRows && !onRowClick
164
+ ? toggleChecked(data[keyProperty])
165
+ : onRowClick?.(data)
166
+ }
167
+ data-index={index}
168
+ ref={measureElement}
169
+ >
170
+ <div className={wrapperStart}>
171
+ {checkableRows && (
172
+ <CheckboxCell
173
+ onClick={() => toggleChecked(data[keyProperty])}
174
+ state={
175
+ checkState.checked.includes(data[keyProperty]) ? 1 : 0
176
+ }
177
+ />
178
+ )}
179
+ {state.start?.map((col, ids) => (
180
+ <BodyCell
181
+ key={`${key}:${ids}`}
182
+ column={col}
183
+ item={data}
184
+ />
185
+ ))}
186
+ </div>
187
+ {state.cols?.map((col, idc) => (
188
+ <BodyCell key={`${key}:${idc}`} column={col} item={data} />
189
+ ))}
190
+ <div className={wrapperEnd}>
191
+ {state.end?.map((col, ide) => (
192
+ <BodyCell
193
+ key={`${key}:${ide}`}
194
+ column={col}
195
+ item={data}
196
+ />
197
+ ))}
198
+ {hideableColumns && <div className="w-6" />}
199
+ </div>
200
+ </div>
201
+ );
202
+ })}
203
+ <div className="flex-1 flex flex-nowrap">
204
+ <div className={wrapperStart}>
205
+ {checkableRows && <div className="w-6" />}
206
+ {state.start?.map((col) => (
207
+ <EmptyCell key={String(col.id)} {...col} />
208
+ ))}
209
+ </div>
210
+ {state.cols?.map((col) => (
211
+ <EmptyCell key={String(col.id)} {...col} />
212
+ ))}
213
+ <div className={wrapperEnd}>
214
+ {state.end?.map((col) => (
215
+ <EmptyCell key={String(col.id)} {...col} />
216
+ ))}
217
+
218
+ {hideableColumns && <div className="w-6" />}
219
+ </div>
220
+ </div>
221
+ </div>
222
+ )}
223
+ {!loading && data.length === 0 && (
224
+ <EmptyContent
225
+ size="sm"
226
+ className="bg-dimmed"
227
+ message={t("datagrid.empty")}
228
+ />
229
+ )}
140
230
  </div>
141
- </div>
231
+ </TableProvider>
142
232
  );
143
233
  };
@@ -24,10 +24,15 @@
24
24
  import {
25
25
  type CssProp,
26
26
  type IconProps,
27
+ type RefProp,
27
28
  type TestProps,
28
29
  } from "@react-fabric/core/dist/types/types";
29
30
  import { type ReactElement } from "react";
30
31
 
32
+ export const COL_MIN_WIDTH = "3rem";
33
+ export const COL_MAX_WIDTH = "64rem";
34
+ export const COL_DEFAULT_WIDTH = "12rem";
35
+
31
36
  export interface ColumnType<T = KeyValue>
32
37
  extends CssProp,
33
38
  IconProps,
@@ -58,8 +63,29 @@ export interface ColumnType<T = KeyValue>
58
63
  renderer?: (value: AnyObject, data: T) => void;
59
64
  }
60
65
 
61
- export interface TableProps<T = KeyValue> {
66
+ export interface TableRef {
67
+ hilight: (row: number) => void;
68
+ unhilight: () => void;
69
+ scrollTo: (row: number) => void;
70
+ }
71
+
72
+ export interface TableProps<T = KeyValue> extends RefProp<TableRef> {
62
73
  columns: Array<ColumnType<T>>;
63
74
  data: T[];
64
- autoColumns?: boolean;
75
+ keyProperty: keyof T;
76
+ /**
77
+ * checkable rows
78
+ */
79
+ checkableRows?: boolean;
80
+ onCheckedChanged?: (rows: Array<keyof T>) => void;
81
+ /**
82
+ * sorting
83
+ */
84
+ sort?: { id: string; order: "asc" | "desc" };
85
+ onSort?: (sort: { id: string; order: "asc" | "desc" }) => void;
86
+
87
+ loading?: boolean;
88
+ hideableColumns?: boolean;
89
+
90
+ onRowClick?: (data: T) => void;
65
91
  }
@@ -0,0 +1,66 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2024 Adarsh Pastakia
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
10
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
11
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
16
+ * portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ */
23
+
24
+ export const useResizer = (
25
+ colEl: HTMLElement,
26
+ ghostEl: HTMLElement,
27
+ callback: (width: number) => void,
28
+ ) => {
29
+ const placeholder = ghostEl.firstElementChild as HTMLElement;
30
+ const isRtl = getComputedStyle(colEl).direction === "rtl";
31
+
32
+ const onResize = (evt: MouseEvent) => {
33
+ /** ***************** check if reverse enabled of RTL *******************/
34
+ const box = colEl.getBoundingClientRect();
35
+ const x = isRtl ? box.left - evt.clientX : evt.clientX - box.right;
36
+ placeholder.style.width = `${colEl.offsetWidth + x}px`;
37
+ };
38
+
39
+ /** ***************** dettach handlers on mouseup *******************/
40
+ const onResizeEnd = () => {
41
+ callback(placeholder.offsetWidth);
42
+ ghostEl.style.display = "none";
43
+ document.removeEventListener("mousemove", onResize);
44
+ document.removeEventListener("mouseup", onResizeEnd);
45
+ };
46
+
47
+ /** ***************** attach handlers *******************/
48
+ const box = colEl.getBoundingClientRect();
49
+ if (colEl.parentElement != null) {
50
+ const parentBox = colEl.parentElement?.getBoundingClientRect();
51
+ if (isRtl) {
52
+ placeholder.style.left = "unset";
53
+ placeholder.style.right = `${box.right - parentBox.right}px`;
54
+ } else {
55
+ placeholder.style.right = "unset";
56
+ placeholder.style.left = `${box.left - parentBox.left}px`;
57
+ }
58
+ }
59
+ placeholder.style.width = `${colEl.offsetWidth}px`;
60
+ placeholder.style.minWidth = colEl.style.minWidth || "48px";
61
+ placeholder.style.maxWidth = colEl.style.maxWidth || "75vw";
62
+ ghostEl.style.display = "block";
63
+
64
+ document.addEventListener("mousemove", onResize);
65
+ document.addEventListener("mouseup", onResizeEnd);
66
+ };
@@ -22,31 +22,64 @@
22
22
  */
23
23
 
24
24
  import { groupBy } from "@react-fabric/utilities";
25
- import { useEffect, useState } from "react";
25
+ import { useEffect, useReducer } from "react";
26
26
  import { type ColumnType } from "./types";
27
27
 
28
- export const useTableColumns = (columns: ColumnType[]) => {
29
- const [columnMap, setColumnMap] = useState<{
30
- start: ColumnType[];
31
- end: ColumnType[];
32
- cols: ColumnType[];
33
- }>({
34
- start: [],
35
- end: [],
36
- cols: [],
37
- });
28
+ interface ColumnState {
29
+ columns: ColumnType[];
30
+ start: ColumnType[];
31
+ end: ColumnType[];
32
+ cols: ColumnType[];
33
+ }
38
34
 
39
- useEffect(() => {
40
- setColumnMap(
41
- groupBy(
42
- columns.filter((col) => !(col.hideable && col.hidden)),
35
+ type ColumnActions =
36
+ | { type: "columns"; columns: ColumnType[] }
37
+ | { type: "hide"; id: string };
38
+
39
+ export const useTableColumns = (columns: ColumnType[]) => {
40
+ const [state, dispatch] = useReducer(
41
+ (state: ColumnState, action: ColumnActions) => {
42
+ if (action.type === "columns") {
43
+ state.columns = action.columns;
44
+ }
45
+ if (action.type === "hide") {
46
+ const col = state.columns.find((col) => col.id === action.id);
47
+ col &&
48
+ state.columns.splice(state.columns.indexOf(col), 1, {
49
+ ...col,
50
+ hidden: col.hidden !== true,
51
+ });
52
+ }
53
+ const {
54
+ start = [],
55
+ end = [],
56
+ cols = [],
57
+ } = groupBy(
58
+ state.columns.filter((col) => col.hidden !== true),
43
59
  "locked",
44
60
  "cols",
45
- ) as AnyObject,
46
- );
61
+ );
62
+ return {
63
+ ...state,
64
+ start,
65
+ end,
66
+ cols,
67
+ };
68
+ },
69
+ {
70
+ columns: [],
71
+ start: [],
72
+ end: [],
73
+ cols: [],
74
+ },
75
+ );
76
+
77
+ useEffect(() => {
78
+ dispatch({ type: "columns", columns });
47
79
  }, [columns]);
48
80
 
49
81
  return {
50
- columnMap,
82
+ state,
83
+ onHide: (id: string) => dispatch({ type: "hide", id }),
51
84
  };
52
85
  };
@@ -22,9 +22,20 @@
22
22
  */
23
23
 
24
24
  import { useVirtualizer } from "@tanstack/react-virtual";
25
- import { useCallback, useRef } from "react";
25
+ import { useCallback, useReducer, useRef } from "react";
26
26
 
27
- export const useVirtualTable = (data: KeyValue[]) => {
27
+ interface DataState {
28
+ checked: Key[];
29
+ allChecked: 0 | 1 | 2;
30
+ }
31
+
32
+ type DataAction = { type: "check"; key: Key } | { type: "checkall" };
33
+
34
+ export const useVirtualTable = (
35
+ data: KeyValue[],
36
+ keyProperty: Key,
37
+ onCheckChanged: (checked: Key[]) => void,
38
+ ) => {
28
39
  // TODO: refactor data into item list, apply grouping if groupColumn provided
29
40
  // TODO: when grouping maintain map of group with children, {___GROUP___:true, label, items, open}
30
41
 
@@ -35,6 +46,37 @@ export const useVirtualTable = (data: KeyValue[]) => {
35
46
  estimateSize: () => 24,
36
47
  });
37
48
 
49
+ const [state, dispatch] = useReducer(
50
+ (state: DataState, action: DataAction) => {
51
+ if (action.type === "check") {
52
+ if (state.checked.includes(action.key))
53
+ state.checked.splice(state.checked.indexOf(action.key), 1);
54
+ else state.checked.push(action.key);
55
+ }
56
+ if (action.type === "checkall") {
57
+ if (state.allChecked !== 0) {
58
+ state.checked = [];
59
+ } else {
60
+ state.checked = data.map((item) => item[keyProperty]);
61
+ }
62
+ }
63
+ onCheckChanged(state.checked);
64
+ return {
65
+ ...state,
66
+ allChecked:
67
+ state.checked.length === data.length
68
+ ? 1
69
+ : state.checked.length
70
+ ? 2
71
+ : 0,
72
+ } as DataState;
73
+ },
74
+ {
75
+ checked: [],
76
+ allChecked: 0,
77
+ },
78
+ );
79
+
38
80
  const virtualItems = virtualizer.getVirtualItems();
39
81
 
40
82
  const getData = useCallback(
@@ -47,8 +89,11 @@ export const useVirtualTable = (data: KeyValue[]) => {
47
89
  return {
48
90
  scrollerRef,
49
91
  items: virtualItems,
92
+ checkState: state,
50
93
  getData,
51
94
  totalSize: virtualizer.getTotalSize,
52
95
  measureElement: virtualizer.measureElement,
96
+ toggleChecked: (key: Key) => dispatch({ type: "check", key }),
97
+ toggleAllChecked: () => dispatch({ type: "checkall" }),
53
98
  };
54
99
  };
@@ -31,7 +31,7 @@ import {
31
31
  } from "@react-fabric/core";
32
32
  import { Search } from "@react-fabric/form";
33
33
  import { useVirtualizer } from "@tanstack/react-virtual";
34
- import { useMemo, useRef } from "react";
34
+ import { useImperativeHandle, useMemo, useRef } from "react";
35
35
  import { TreeNode } from "./TreeNode";
36
36
  import { iconCollapseAll, iconExpandAll, type TreePanelProps } from "./types";
37
37
  import { useTree } from "./useTree";
@@ -39,6 +39,7 @@ import { useTree } from "./useTree";
39
39
  // TODO: implement keyboard handler for navigating tree
40
40
 
41
41
  export const TreePanel = <T extends KeyValue>({
42
+ ref,
42
43
  items,
43
44
  selected,
44
45
  checked,
@@ -64,6 +65,7 @@ export const TreePanel = <T extends KeyValue>({
64
65
  expandAll,
65
66
  collapseAll,
66
67
  select,
68
+ expand,
67
69
  onFilter,
68
70
  } = useTree({
69
71
  items,
@@ -93,6 +95,15 @@ export const TreePanel = <T extends KeyValue>({
93
95
  return [CoreIcons.expand, CoreIcons.collapse];
94
96
  }, [expander]);
95
97
 
98
+ useImperativeHandle(
99
+ ref,
100
+ () => ({
101
+ open: (id: string) => expand(id),
102
+ select: (id: string) => expand(id),
103
+ }),
104
+ [],
105
+ );
106
+
96
107
  return (
97
108
  <Section>
98
109
  <Header
package/src/tree/types.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  type CssProp,
28
28
  type Elements,
29
29
  type IconProps,
30
+ type RefProp,
30
31
  type TestProps,
31
32
  } from "@react-fabric/core/dist/types/types";
32
33
 
@@ -105,8 +106,14 @@ export interface TreeNodeProps extends ChildProp {
105
106
  onChecked: (id: string) => void;
106
107
  }
107
108
 
109
+ export interface TreeRef {
110
+ select: (id: string) => void;
111
+ open: (id: string) => void;
112
+ }
113
+
108
114
  export interface TreePanelProps<T extends KeyValue = KeyValue>
109
- extends TestProps {
115
+ extends TestProps,
116
+ RefProp<TreeRef> {
110
117
  items?: Array<TreeNodeType<T>>;
111
118
  /**
112
119
  * make tree searchable
@@ -203,6 +203,10 @@ export const useTree = <T extends KeyValue>({
203
203
  dispatch({ type: "select", id });
204
204
  }, []);
205
205
 
206
+ const expand = useCallback((id: string) => {
207
+ dispatch({ type: "expand", id });
208
+ }, []);
209
+
206
210
  const expandAll = useCallback(() => {
207
211
  dispatch({ type: "expandAll" });
208
212
  }, []);
@@ -222,6 +226,7 @@ export const useTree = <T extends KeyValue>({
222
226
  collapseAll,
223
227
  toggleCheck,
224
228
  select,
229
+ expand,
225
230
  onFilter,
226
231
  };
227
232
  };