@react-fabric/data 1.0.0-beta.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/{src/histogram/Histogram.module.css → css/_histogram.css} +16 -13
  2. package/css/styles.css +24 -0
  3. package/dist/cjs/checklist/CheckList.js +59 -33
  4. package/dist/cjs/histogram/Histogram.js +41 -26
  5. package/dist/cjs/hooks/useFilteredList.js +100 -17
  6. package/dist/cjs/hooks/usePagination.js +29 -8
  7. package/dist/cjs/hooks/useSelectableList.js +30 -5
  8. package/dist/cjs/i18n/{ar.json.js → ar/data.json.js} +8 -1
  9. package/dist/cjs/i18n/{en.json.js → en/data.json.js} +8 -1
  10. package/dist/cjs/i18n/index.js +4 -4
  11. package/dist/cjs/index.js +30 -0
  12. package/dist/cjs/json/JsonViewer.js +80 -43
  13. package/dist/cjs/pagination/Pagination.js +24 -15
  14. package/dist/cjs/table/AddColumn.js +5 -5
  15. package/dist/cjs/table/BodyCell.js +20 -13
  16. package/dist/cjs/table/BodyRow.js +41 -28
  17. package/dist/cjs/table/CheckboxCell.js +10 -9
  18. package/dist/cjs/table/ColumnFilters.js +100 -0
  19. package/dist/cjs/table/EmptyCell.js +4 -4
  20. package/dist/cjs/table/HeaderCell.js +79 -53
  21. package/dist/cjs/table/HtmlTable.js +84 -0
  22. package/dist/cjs/table/{Context.js → Provider.js} +8 -10
  23. package/dist/cjs/table/Table.js +99 -33
  24. package/dist/cjs/{tree/types.js → table/context.js} +9 -5
  25. package/dist/cjs/table/types.js +29 -0
  26. package/dist/cjs/table/useResizer.js +10 -10
  27. package/dist/cjs/table/useTableColumns.js +4 -4
  28. package/dist/cjs/table/useVirtualTable.js +129 -22
  29. package/dist/cjs/tree/TreeNode.js +66 -46
  30. package/dist/cjs/tree/TreePanel.js +60 -24
  31. package/dist/cjs/tree/useTree.js +212 -47
  32. package/dist/cjs/tree/utils.js +63 -34
  33. package/dist/cjs/utils/getColor.js +58 -0
  34. package/dist/cjs/virtual/Gallery.js +119 -61
  35. package/dist/cjs/virtual/List.js +116 -55
  36. package/dist/cjs/virtual/Scroller.js +16 -8
  37. package/dist/esm/checklist/CheckList.js +61 -35
  38. package/dist/esm/histogram/Histogram.js +43 -28
  39. package/dist/esm/hooks/useFilteredList.js +101 -18
  40. package/dist/esm/hooks/usePagination.js +29 -8
  41. package/dist/esm/hooks/useSelectableList.js +30 -5
  42. package/dist/esm/i18n/{ar.json.js → ar/data.json.js} +8 -2
  43. package/dist/esm/i18n/{en.json.js → en/data.json.js} +8 -2
  44. package/dist/esm/i18n/index.js +2 -2
  45. package/dist/esm/index.js +31 -0
  46. package/dist/esm/json/JsonViewer.js +82 -45
  47. package/dist/esm/pagination/Pagination.js +25 -16
  48. package/dist/esm/table/AddColumn.js +6 -6
  49. package/dist/esm/table/BodyCell.js +21 -14
  50. package/dist/esm/table/BodyRow.js +41 -28
  51. package/dist/esm/table/CheckboxCell.js +11 -10
  52. package/dist/esm/table/ColumnFilters.js +100 -0
  53. package/dist/esm/table/EmptyCell.js +4 -4
  54. package/dist/esm/table/HeaderCell.js +80 -54
  55. package/dist/esm/table/HtmlTable.js +84 -0
  56. package/dist/esm/table/{Context.js → Provider.js} +11 -12
  57. package/dist/esm/table/Table.js +100 -34
  58. package/dist/esm/{tree/types.js → table/context.js} +8 -4
  59. package/dist/esm/table/types.js +29 -0
  60. package/dist/esm/table/useResizer.js +10 -10
  61. package/dist/esm/table/useTableColumns.js +4 -4
  62. package/dist/esm/table/useVirtualTable.js +131 -24
  63. package/dist/esm/tree/TreeNode.js +69 -49
  64. package/dist/esm/tree/TreePanel.js +62 -26
  65. package/dist/esm/tree/useTree.js +215 -50
  66. package/dist/esm/tree/utils.js +64 -35
  67. package/dist/esm/utils/getColor.js +58 -0
  68. package/dist/esm/virtual/Gallery.js +121 -63
  69. package/dist/esm/virtual/List.js +118 -57
  70. package/dist/esm/virtual/Scroller.js +17 -9
  71. package/dist/types/checklist/CheckList.d.ts +25 -6
  72. package/dist/types/histogram/Histogram.d.ts +28 -6
  73. package/dist/types/hooks/useFilteredList.d.ts +62 -5
  74. package/dist/types/hooks/usePagination.d.ts +18 -2
  75. package/dist/types/hooks/useSelectableList.d.ts +24 -1
  76. package/dist/types/index.d.ts +27 -0
  77. package/dist/types/json/JsonViewer.d.ts +23 -3
  78. package/dist/types/pagination/Pagination.d.ts +8 -2
  79. package/dist/types/table/AddColumn.d.ts +2 -2
  80. package/dist/types/table/BodyCell.d.ts +2 -2
  81. package/dist/types/table/BodyRow.d.ts +9 -9
  82. package/dist/types/table/CheckboxCell.d.ts +3 -3
  83. package/dist/types/table/ColumnFilters.d.ts +12 -0
  84. package/dist/types/table/EmptyCell.d.ts +1 -1
  85. package/dist/types/table/HeaderCell.d.ts +1 -1
  86. package/dist/types/table/HtmlTable.d.ts +21 -0
  87. package/dist/types/table/Provider.d.ts +2 -0
  88. package/dist/types/table/Table.d.ts +10 -1
  89. package/dist/types/table/context.d.ts +7 -0
  90. package/dist/types/table/types.d.ts +52 -10
  91. package/dist/types/table/useResizer.d.ts +1 -1
  92. package/dist/types/table/useTableColumns.d.ts +1 -1
  93. package/dist/types/table/useVirtualTable.d.ts +31 -12
  94. package/dist/types/tree/TreeNode.d.ts +1 -1
  95. package/dist/types/tree/TreePanel.d.ts +36 -1
  96. package/dist/types/tree/types.d.ts +75 -28
  97. package/dist/types/tree/useTree.d.ts +8 -12
  98. package/dist/types/tree/utils.d.ts +15 -8
  99. package/dist/types/utils/getColor.d.ts +43 -0
  100. package/dist/types/virtual/Gallery.d.ts +37 -6
  101. package/dist/types/virtual/List.d.ts +38 -6
  102. package/dist/types/virtual/Scroller.d.ts +1 -1
  103. package/package.json +17 -19
  104. package/src/checklist/CheckList.tsx +68 -71
  105. package/src/histogram/Histogram.tsx +47 -48
  106. package/src/hooks/useFilteredList.tsx +111 -28
  107. package/src/hooks/usePagination.tsx +39 -39
  108. package/src/hooks/useSelectableList.ts +45 -33
  109. package/src/i18n/{ar.json → ar/data.json} +5 -0
  110. package/src/i18n/{en.json → en/data.json} +5 -0
  111. package/src/i18n/index.ts +2 -2
  112. package/src/index.ts +23 -17
  113. package/src/json/JsonViewer.tsx +89 -120
  114. package/src/pagination/Pagination.tsx +104 -105
  115. package/src/table/AddColumn.tsx +6 -15
  116. package/src/table/BodyCell.tsx +27 -36
  117. package/src/table/BodyRow.tsx +36 -59
  118. package/src/table/CheckboxCell.tsx +12 -15
  119. package/src/table/ColumnFilters.tsx +93 -0
  120. package/src/table/EmptyCell.tsx +5 -18
  121. package/src/table/HeaderCell.tsx +72 -53
  122. package/src/table/HtmlTable.tsx +106 -0
  123. package/src/table/{Context.tsx → Provider.tsx} +11 -28
  124. package/src/table/Table.tsx +98 -83
  125. package/src/table/context.ts +33 -0
  126. package/src/table/types.ts +53 -27
  127. package/src/table/useResizer.ts +5 -9
  128. package/src/table/useTableColumns.ts +4 -6
  129. package/src/table/useVirtualTable.ts +136 -37
  130. package/src/tree/TreeNode.tsx +91 -86
  131. package/src/tree/TreePanel.tsx +87 -51
  132. package/src/tree/types.ts +85 -46
  133. package/src/tree/useTree.ts +210 -65
  134. package/src/tree/utils.ts +81 -62
  135. package/src/utils/getColor.ts +55 -0
  136. package/src/virtual/Gallery.tsx +129 -120
  137. package/src/virtual/List.tsx +124 -91
  138. package/src/virtual/Scroller.tsx +25 -9
  139. package/dist/cjs/histogram/Histogram.module.css +0 -1
  140. package/dist/esm/histogram/Histogram.module.css +0 -1
  141. package/dist/types/table/Context.d.ts +0 -8
@@ -22,26 +22,13 @@
22
22
  */
23
23
 
24
24
  import { useMemo } from "react";
25
- import { useTableContext } from "./Context";
26
- import {
27
- COL_DEFAULT_WIDTH,
28
- COL_MAX_WIDTH,
29
- COL_MIN_WIDTH,
30
- type TableColumn,
31
- } from "./types";
25
+ import { useTableContext } from "./context";
26
+ import { COL_DEFAULT_WIDTH, COL_MAX_WIDTH, COL_MIN_WIDTH, type TableColumn } from "./types";
32
27
 
33
- export const EmptyCell = ({
34
- id,
35
- width: _width,
36
- maxWidth,
37
- minWidth,
38
- }: TableColumn) => {
28
+ export function EmptyCell({ id, width: _width, maxWidth, minWidth }: TableColumn) {
39
29
  const { widths } = useTableContext();
40
30
 
41
- const width = useMemo(
42
- () => widths.get(id.toString()) ?? _width,
43
- [widths, id, _width],
44
- );
31
+ const width = useMemo(() => widths.get(id.toString()) ?? _width, [widths, id, _width]);
45
32
 
46
33
  return (
47
34
  <div
@@ -54,4 +41,4 @@ export const EmptyCell = ({
54
41
  }}
55
42
  />
56
43
  );
57
- };
44
+ }
@@ -21,33 +21,23 @@
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 {
25
- CoreIcons,
26
- DropdownTool,
27
- Icon,
28
- Menu,
29
- MenuItem,
30
- Tooltip,
31
- } from "@react-fabric/core";
24
+ import { Button, Divider, DropdownTool, getIconProps, Icon, Menu, MenuItem, Tooltip } from "@react-fabric/core";
25
+ import { isEmpty } from "@react-fabric/utilities";
32
26
  import { useCallback, useMemo } from "react";
33
- import { useTableContext } from "./Context";
34
- import {
35
- COL_DEFAULT_WIDTH,
36
- COL_MAX_WIDTH,
37
- COL_MIN_WIDTH,
38
- type TableColumn,
39
- type TableProps,
40
- } from "./types";
27
+ import { ColumnFilters } from "./ColumnFilters";
28
+ import { useTableContext } from "./context";
29
+ import { COL_DEFAULT_WIDTH, COL_MAX_WIDTH, COL_MIN_WIDTH, type TableColumn, type TableProps } from "./types";
41
30
 
42
- export const HeaderCell = ({
31
+ export function HeaderCell({
43
32
  id,
33
+ field,
34
+ dataType,
44
35
  label,
45
36
  icon,
46
- iconBg,
47
- iconColor,
48
- rtlFlip,
49
37
  actions,
50
- locked,
38
+ filter,
39
+ filterable,
40
+ filterOptions,
51
41
  tooltip,
52
42
  sortable,
53
43
  resizable,
@@ -56,47 +46,72 @@ export const HeaderCell = ({
56
46
  minWidth,
57
47
  sort,
58
48
  onSort,
59
- }: TableColumn & Pick<TableProps, "sort" | "onSort">) => {
49
+ onFilter,
50
+ }: TableColumn & Pick<TableProps, "sort" | "onSort" | "onFilter">) {
60
51
  const { startResize, widths } = useTableContext();
61
52
 
62
- const width = useMemo(
63
- () => widths.get(id.toString()) ?? _width,
64
- [widths, _width, id],
65
- );
53
+ const width = useMemo(() => widths.get(id.toString()) ?? _width, [widths, _width, id]);
66
54
 
67
- const handleSort = useCallback(() => {
68
- sortable &&
69
- onSort?.({
70
- id: id.toString(),
71
- order: sort?.id === id && sort.order === "asc" ? "desc" : "asc",
72
- });
73
- }, [onSort, name, sort, sortable]);
55
+ const handleSort = useCallback(
56
+ (order?: "asc" | "desc") => {
57
+ if (sortable)
58
+ onSort?.({
59
+ id: id.toString(),
60
+ order: order ?? (sort?.id === id && sort.order === "asc" ? "desc" : "asc"),
61
+ });
62
+ },
63
+ [id, onSort, sort, sortable],
64
+ );
74
65
 
75
66
  const menus = useMemo(() => {
76
- const ret = [];
67
+ let ret = [];
68
+ if (filterable && (dataType ?? filterOptions)) {
69
+ ret.push(
70
+ <Menu key="filters" label="Filter" icon={filter ? "icon-[mdi--check]" : ""} trigger="click">
71
+ <ColumnFilters
72
+ type={dataType}
73
+ list={filterOptions}
74
+ filter={filter}
75
+ onFilter={(value) => onFilter?.(field ?? id, value)}
76
+ />
77
+ </Menu>,
78
+ );
79
+ }
77
80
  if (sortable) {
78
81
  ret.push(
79
- <MenuItem
80
- key="sort-asc"
81
- label="Sort ascending"
82
- icon={CoreIcons.sortAsc}
83
- />,
82
+ <MenuItem key="sort-asc" label="Sort ascending" icon="icon-[mdi--sort-ascending]" onClick={() => handleSort("asc")} />,
84
83
  <MenuItem
85
84
  key="sort-desc"
86
85
  label="Sort descending"
87
- icon={CoreIcons.sortDesc}
86
+ icon="icon-[mdi--sort-descending]"
87
+ onClick={() => handleSort("desc")}
88
88
  />,
89
89
  );
90
90
  }
91
+ if (actions) {
92
+ ret.push(<Divider key="div" />);
93
+ ret.push(...actions);
94
+ }
95
+ if (ret.length === 1) {
96
+ ret = [
97
+ <ColumnFilters
98
+ key="filters"
99
+ type={dataType}
100
+ list={filterOptions}
101
+ filter={filter}
102
+ onFilter={(value) => onFilter?.(field ?? id, value)}
103
+ />,
104
+ ];
105
+ }
91
106
  return ret;
92
- }, [sortable]);
107
+ }, [filterable, dataType, filterOptions, sortable, actions, filter, onFilter, field, id, handleSort]);
93
108
 
94
109
  return (
95
110
  <div
96
111
  role="none"
97
112
  data-id={id}
98
- onClick={handleSort}
99
- className="group font-medium border-e flex flex-nowrap text-start items-center table-header-cell"
113
+ onClick={() => handleSort()}
114
+ className="group/tool font-medium border-e flex flex-nowrap text-start items-center table-header-cell"
100
115
  style={{
101
116
  width: width ?? COL_DEFAULT_WIDTH,
102
117
  minWidth: minWidth ?? COL_MIN_WIDTH,
@@ -104,10 +119,8 @@ export const HeaderCell = ({
104
119
  }}
105
120
  >
106
121
  <Tooltip content={tooltip ?? label} disabled={!(tooltip ?? label)}>
107
- <div className="flex-initial px-2 py-1 text-sm truncate sticky start-0">
108
- {icon && (
109
- <Icon icon={icon} bg={iconBg} color={iconColor} rtlFlip={rtlFlip} />
110
- )}
122
+ <div className="flex-initial px-2 py-1 text-sm truncate sticky inset-s-0">
123
+ {icon && <Icon {...getIconProps(icon)} />}
111
124
  <span>{label ?? " "}</span>
112
125
  </div>
113
126
  </Tooltip>
@@ -123,16 +136,22 @@ export const HeaderCell = ({
123
136
  <Menu className="text-sm">{menus}</Menu>
124
137
  </DropdownTool>
125
138
  )}
139
+ {filterable && !isEmpty(filter) && (
140
+ <Button
141
+ size="sm"
142
+ variant="link"
143
+ aria-label="clear filter"
144
+ icon="icon-[mdi--filter-remove]"
145
+ onClick={(e) => (e?.stopPropagation(), onFilter?.(id))}
146
+ />
147
+ )}
126
148
  {resizable && (
127
149
  <div
128
150
  role="none"
129
- className="cursor-col-resize border-e bg-transparent border-tint-200 w-[5px] self-stretch"
130
- onMouseDown={(e) =>
131
- e.currentTarget.parentElement &&
132
- startResize(e.currentTarget.parentElement)
133
- }
151
+ className="cursor-col-resize border-e bg-transparent border-tint-200 w-[calc(5px)] self-stretch"
152
+ onMouseDown={(e) => e.currentTarget.parentElement && startResize(e.currentTarget.parentElement)}
134
153
  />
135
154
  )}
136
155
  </div>
137
156
  );
138
- };
157
+ }
@@ -0,0 +1,106 @@
1
+ /*
2
+ * React Fabric
3
+ * @version: 1.0.0
4
+ *
5
+ *
6
+ * The MIT License (MIT)
7
+ * Copyright (c) 2026 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
+ import { cn, getByPath } from "@react-fabric/utilities";
25
+ import { useMemo } from "react";
26
+ import { usePagination } from "../hooks/usePagination";
27
+ import { Pagination } from "../pagination/Pagination";
28
+
29
+ interface Props<T = KeyValue> {
30
+ data: T[];
31
+ columns: Array<{
32
+ id: keyof T;
33
+ label?: string;
34
+ width?: number | string;
35
+ maxWidth?: number | string;
36
+ align?: "start" | "center" | "end";
37
+ className?: string;
38
+ headRenderer?: React.ReactNode;
39
+ renderer?: (value: AnyObject, row: T, index: number) => React.ReactNode;
40
+ }>;
41
+ /**
42
+ * Number of pagination buttons to show, default is 25
43
+ * If set to 0, pagination will be hidden
44
+ */
45
+ paginationSize?: number;
46
+
47
+ className?: string;
48
+ }
49
+
50
+ export function HtmlTable<T extends KeyValue = KeyValue>({ data, columns, paginationSize = 25, className }: Props<T>) {
51
+ const paginator = usePagination({
52
+ totalRecords: data.length,
53
+ perPage: paginationSize,
54
+ });
55
+
56
+ const startIndex = useMemo(() => paginator.page * paginationSize, [paginator.page, paginationSize]);
57
+
58
+ const dataPage = useMemo(() => (paginationSize > 0 ? data.slice(startIndex, startIndex + paginationSize) : data), [data, paginationSize, startIndex]);
59
+
60
+ return (
61
+ <div className={className}>
62
+ <table className="table-fixed border-spacing-1 border-separate w-full text-sm">
63
+ <thead className="sticky top-0 z-1 bg-dimmed">
64
+ <tr>
65
+ {columns.map((col, idx) => (
66
+ <th
67
+ // eslint-disable-next-line @eslint-react/no-array-index-key
68
+ key={idx}
69
+ className="text-start truncate bg-accent-100 px-2 py-1 font-medium text-accent-800"
70
+ style={{ width: col.width, maxWidth: col.maxWidth }}
71
+ >
72
+ {col.headRenderer ?? col.label ?? " "}
73
+ </th>
74
+ ))}
75
+ </tr>
76
+ </thead>
77
+ <tbody className="bg-alternate">
78
+ {dataPage.map((row, idx) => (
79
+ // eslint-disable-next-line @eslint-react/no-array-index-key
80
+ <tr key={idx}>
81
+ {columns.map((col, cidx) => (
82
+ <td
83
+ // eslint-disable-next-line @eslint-react/no-array-index-key
84
+ key={`${idx}-${cidx}`}
85
+ className={cn("px-2 py-1 truncate", col.align === "center" && "text-center", col.align === "end" && "text-end", col.className)}
86
+ style={{ width: col.width, maxWidth: col.maxWidth }}
87
+ >
88
+ {col.renderer?.(getByPath(row, col.id.toString()), row, startIndex + idx) ?? getByPath(row, col.id.toString())}
89
+ </td>
90
+ ))}
91
+ </tr>
92
+ ))}
93
+ </tbody>
94
+ {paginationSize > 0 && (
95
+ <tfoot className="sticky bottom-0 bg-dimmed z-1">
96
+ <tr>
97
+ <td colSpan={columns.length} className="text-end py-1">
98
+ <Pagination minimal {...paginator} />
99
+ </td>
100
+ </tr>
101
+ </tfoot>
102
+ )}
103
+ </table>
104
+ </div>
105
+ );
106
+ }
@@ -22,30 +22,18 @@
22
22
  */
23
23
 
24
24
  import { type ChildrenProp } from "@react-fabric/core/dist/types/types";
25
- import {
26
- createContext,
27
- useCallback,
28
- useContext,
29
- useRef,
30
- useState,
31
- } from "react";
32
- import { useResizer } from "./useResizer";
25
+ import { useCallback, useRef, useState } from "react";
26
+ import { TableContext } from "./context";
27
+ import { startResizer } from "./useResizer";
33
28
 
34
- interface Context {
35
- widths: Map<string, number>;
36
- startResize: (col: HTMLElement) => void;
37
- }
38
-
39
- const TableContext = createContext<Context>({} as Context);
40
-
41
- export const TableProvider = ({ children }: ChildrenProp) => {
29
+ export function TableProvider({ children }: ChildrenProp) {
42
30
  const ghostRef = useRef<HTMLDivElement>(null);
43
- const [widths, setWidths] = useState<Map<string, number>>(new Map());
31
+ const [widths, setWidths] = useState<Map<string, number>>(() => new Map());
44
32
  const startResize = useCallback(
45
33
  (col: HTMLElement) => {
46
34
  if (col) {
47
- ghostRef.current != null &&
48
- useResizer(col, ghostRef.current, (width) => {
35
+ if (ghostRef.current != null)
36
+ startResizer(col, ghostRef.current, (width) => {
49
37
  setWidths(new Map(widths.set(col.dataset.id ?? "", width)));
50
38
  });
51
39
  }
@@ -54,17 +42,12 @@ export const TableProvider = ({ children }: ChildrenProp) => {
54
42
  );
55
43
 
56
44
  return (
57
- <TableContext.Provider value={{ startResize, widths }}>
45
+ <TableContext value={{ startResize, widths }}>
58
46
  {children}
59
47
 
60
- <div
61
- className="absolute inset-0 hidden z-20 cursor-col-resize"
62
- ref={ghostRef}
63
- >
48
+ <div className="absolute inset-0 hidden z-20 cursor-col-resize" ref={ghostRef}>
64
49
  <div className="absolute inset-y-0 bg-muted opacity-50 border-primary border-e-2" />
65
50
  </div>
66
- </TableContext.Provider>
51
+ </TableContext>
67
52
  );
68
- };
69
-
70
- export const useTableContext = () => useContext(TableContext);
53
+ }
@@ -21,49 +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 { EmptyContent, Loading, useDebounce } from "@react-fabric/core";
25
- import { debounce } from "@react-fabric/utilities";
26
- import {
27
- useEffect,
28
- useImperativeHandle,
29
- useLayoutEffect,
30
- useMemo,
31
- useRef,
32
- } from "react";
24
+ import { EmptyContent, Icon, LoadingLine, useDebounce } from "@react-fabric/core";
25
+ import { cn, debounce } from "@react-fabric/utilities";
26
+ import { useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
33
27
  import { useTranslation } from "react-i18next";
34
28
  import { AddColumn } from "./AddColumn";
35
29
  import { BodyRow } from "./BodyRow";
36
30
  import { CheckboxCell } from "./CheckboxCell";
37
- import { TableProvider } from "./Context";
38
31
  import { EmptyCell } from "./EmptyCell";
39
32
  import { HeaderCell } from "./HeaderCell";
33
+ import { TableProvider } from "./Provider";
40
34
  import { type TableProps } from "./types";
41
35
  import { useTableColumns } from "./useTableColumns";
42
36
  import { useVirtualTable } from "./useVirtualTable";
43
37
 
44
- export const Table = <T extends KeyValue = KeyValue>({
38
+ /**
39
+ * Table component for displaying data in a tabular format with features like sorting, filtering, and virtual scrolling.
40
+ * It supports expandable rows, checkable rows, and customizable columns.
41
+ * The component is designed to handle large datasets efficiently by rendering only the visible rows.
42
+ * It also provides a way to manage column visibility and allows for custom rendering of group headers.
43
+ * Uses TanStack's `useVirtual` for virtualization and React's `useMemo` for performance optimization.
44
+ *
45
+ * @see {@link https://tanstack.com/table/v8/docs/api/virtual}
46
+ */
47
+ export function Table<T extends KeyValue = KeyValue>({
45
48
  ref,
46
49
  data,
47
50
  columns,
48
- keyProperty,
51
+ keyProperty = "id" as never,
52
+ groupProperty,
49
53
  checkableRows,
50
54
  initialScroll,
51
55
  hideableColumns,
52
56
  sort,
53
57
  loading,
58
+ checked,
54
59
  emptyDisplay,
60
+ groupRenderer,
55
61
  canExpand,
56
62
  children,
57
63
  onSort,
64
+ onFilter,
58
65
  onScroll,
59
66
  onRowClick,
60
67
  onCheckedChanged,
61
- }: TableProps<T>) => {
68
+ total = 0,
69
+ onLoadMore,
70
+ }: TableProps<T>) {
62
71
  const { t } = useTranslation("data");
63
- const fireCheckChanged = useDebounce(
64
- (checkedIds: Array<keyof T>) => onCheckedChanged?.(checkedIds),
65
- [],
66
- );
72
+ const fireCheckChanged = useDebounce((checkedIds: Array<keyof T>) => onCheckedChanged?.(checkedIds), []);
67
73
 
68
74
  const { state, onHide } = useTableColumns(columns);
69
75
  const {
@@ -72,29 +78,38 @@ export const Table = <T extends KeyValue = KeyValue>({
72
78
  top,
73
79
  checkState,
74
80
  virtualizer,
81
+ hasActiveSticky,
75
82
  toggleExpand,
76
83
  toggleChecked,
77
84
  toggleAllChecked,
85
+ toggleGroupExpand,
78
86
  getData,
79
87
  totalSize,
88
+ isActiveSticky,
80
89
  measureElement,
81
- } = useVirtualTable(data, keyProperty, fireCheckChanged);
82
- const refBody = useRef<HTMLDivElement>(null);
90
+ } = useVirtualTable(data, {
91
+ checked,
92
+ keyProperty,
93
+ groupProperty,
94
+ total,
95
+ loading,
96
+ onLoadMore,
97
+ onCheckChanged: fireCheckChanged,
98
+ });
99
+ const bodyRef = useRef<HTMLDivElement>(null);
83
100
 
84
- const wrapperStart = useMemo(
85
- () => "bg-inherit sticky start-0 flex flex-nowrap z-1",
86
- [],
87
- );
88
- const wrapperEnd = useMemo(
89
- () => "bg-inherit sticky end-0 flex flex-nowrap z-1 border-s -ms-px",
90
- [],
91
- );
101
+ const wrapperStart = useMemo(() => "bg-inherit sticky start-0 flex flex-nowrap z-1", []);
102
+ const wrapperEnd = useMemo(() => "bg-inherit sticky end-0 flex flex-nowrap z-1 border-s -ms-px", []);
92
103
 
93
104
  useLayoutEffect(() => {
94
- setTimeout(() => {
95
- initialScroll &&
96
- virtualizer.scrollToIndex(initialScroll, { align: "start" });
105
+ const tmr = setTimeout(() => {
106
+ if (initialScroll) virtualizer.scrollToIndex(initialScroll, { align: "start" });
97
107
  }, 100);
108
+
109
+ return () => {
110
+ clearTimeout(tmr);
111
+ };
112
+ // eslint-disable-next-line @eslint-react/exhaustive-deps
98
113
  }, []);
99
114
 
100
115
  useImperativeHandle(
@@ -104,24 +119,19 @@ export const Table = <T extends KeyValue = KeyValue>({
104
119
  virtualizer.scrollToIndex(row, { align: "start" });
105
120
  },
106
121
  hilight(row) {
107
- scrollerRef.current
108
- ?.querySelector(".hilight")
109
- ?.classList.remove("hilight", "ring-1");
122
+ scrollerRef.current?.querySelector(".hilight")?.classList.remove("hilight", "ring-1");
110
123
  virtualizer.scrollToIndex(Math.floor(row), {
111
124
  align: "start",
112
125
  });
113
126
  setTimeout(() => {
114
- scrollerRef.current
115
- ?.querySelector(`[data-index="${row}"]`)
116
- ?.classList.add("hilight", "ring-1");
127
+ scrollerRef.current?.querySelector(`[data-index="${row}"]`)?.classList.add("hilight", "ring-1");
117
128
  }, 100);
118
129
  },
119
130
  unhilight() {
120
- scrollerRef.current
121
- ?.querySelector(".hilight")
122
- ?.classList.remove("hilight", "ring-1");
131
+ scrollerRef.current?.querySelector(".hilight")?.classList.remove("hilight", "ring-1");
123
132
  },
124
133
  }),
134
+ // eslint-disable-next-line @eslint-react/exhaustive-deps
125
135
  [],
126
136
  );
127
137
 
@@ -133,7 +143,7 @@ export const Table = <T extends KeyValue = KeyValue>({
133
143
  return () => {
134
144
  handle.cancel();
135
145
  };
136
- }, [top]);
146
+ }, [onScroll, top]);
137
147
 
138
148
  return (
139
149
  <TableProvider>
@@ -142,62 +152,73 @@ export const Table = <T extends KeyValue = KeyValue>({
142
152
  style={{
143
153
  gridTemplate: `"head" auto "loader" auto "content" 1fr "foot" auto/1fr`,
144
154
  }}
155
+ data-ref="tableScroller"
145
156
  ref={scrollerRef}
146
157
  >
147
- <div className="bg-base font-medium sticky top-0 area-head border-b select-none flex flex-nowrap z-2">
158
+ <div
159
+ data-ref="tableHeader"
160
+ className="bg-default font-medium sticky top-0 h-8 area-head border-b select-none flex flex-nowrap z-3"
161
+ >
148
162
  <div className={wrapperStart}>
149
163
  {canExpand && <div className="w-6" />}
150
- {checkableRows && (
151
- <CheckboxCell
152
- state={checkState.allChecked}
153
- onClick={toggleAllChecked}
154
- />
155
- )}
164
+ {checkableRows && <CheckboxCell state={checkState.allChecked} onClick={toggleAllChecked} />}
156
165
  {state.start?.map((col, idx) => (
157
- <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
166
+ // eslint-disable-next-line @eslint-react/no-array-index-key
167
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} onFilter={onFilter} />
158
168
  ))}
159
169
  </div>
160
170
  {state.cols?.map((col, idx) => (
161
- <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
171
+ // eslint-disable-next-line @eslint-react/no-array-index-key
172
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} onFilter={onFilter} />
162
173
  ))}
163
174
  <div className={wrapperEnd}>
164
175
  {state.end?.map((col, idx) => (
165
- <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} />
176
+ // eslint-disable-next-line @eslint-react/no-array-index-key
177
+ <HeaderCell key={idx} {...col} sort={sort} onSort={onSort} onFilter={onFilter} />
166
178
  ))}
167
179
 
168
- {hideableColumns && (
169
- <AddColumn
170
- onClick={onHide}
171
- columns={state.columns.filter((col) => col.hideable !== false)}
172
- />
173
- )}
180
+ {hideableColumns && <AddColumn onClick={onHide} columns={state.columns.filter((col) => col.hideable !== false)} />}
174
181
  </div>
175
182
  </div>
176
- {loading && <Loading />}
183
+ {loading && <LoadingLine />}
177
184
  {data.length > 0 && (
178
- <div
179
- className="area-content flex flex-col flex-nowrap"
180
- style={{ height: totalSize() }}
181
- ref={refBody}
182
- >
183
- <div style={{ height: items[0]?.start }} />
185
+ <div className="area-content flex flex-col flex-nowrap min-h-full" style={{ height: totalSize() }} ref={bodyRef}>
186
+ <div
187
+ style={{
188
+ height: items[hasActiveSticky ? 1 : 0]?.start,
189
+ }}
190
+ />
184
191
  {items.map(({ index, key }) => {
185
192
  const data = getData(index);
186
- return (
193
+ return "__GROUP__" in data ? (
194
+ <div
195
+ key={key}
196
+ ref={measureElement}
197
+ data-index={index}
198
+ className={cn(
199
+ "text-md bg-default border-y border-tint-100 border-t-0 cursor-pointer flex items-center justify-start gap-1 z-2",
200
+ isActiveSticky(index) && "sticky top-8",
201
+ )}
202
+ role="none"
203
+ onClick={() => toggleGroupExpand(data.key as never)}
204
+ >
205
+ <div className={cn("px-2 py-1 flex items-center gap-1 z-2 sticky inset-s-0")}>
206
+ <Icon rtlFlip icon={data.open ? "icon-[mdi--chevron-down]" : "icon-[mdi--chevron-right]"} />
207
+ {groupRenderer?.(data) ?? (
208
+ <div className="flex gap-1 items-center">
209
+ <span>{data.key}</span>
210
+ <span className="text-sm">({data.itemCount})</span>
211
+ </div>
212
+ )}
213
+ </div>
214
+ </div>
215
+ ) : (
187
216
  <BodyRow
188
- rowKey={key}
217
+ rowKey={key.toString()}
189
218
  index={index}
190
219
  checkableRows={checkableRows}
191
- checked={
192
- keyProperty &&
193
- checkState.checked.includes(data[keyProperty])
194
- ? 1
195
- : 0
196
- }
197
- expanded={
198
- !!keyProperty &&
199
- checkState.expanded.includes(data[keyProperty])
200
- }
220
+ checked={keyProperty && checkState.checked.includes(data[keyProperty]) ? 1 : 0}
221
+ expanded={!!keyProperty && checkState.expanded.includes(data[keyProperty])}
201
222
  data={data}
202
223
  hideableColumns={hideableColumns}
203
224
  keyProperty={keyProperty}
@@ -237,14 +258,8 @@ export const Table = <T extends KeyValue = KeyValue>({
237
258
  )}
238
259
  {!loading &&
239
260
  data.length === 0 &&
240
- (emptyDisplay ?? (
241
- <EmptyContent
242
- size="sm"
243
- className="bg-dimmed"
244
- message={t("datagrid.empty")}
245
- />
246
- ))}
261
+ (emptyDisplay ?? <EmptyContent size="sm" className="bg-dimmed" message={t("datagrid.empty")} />)}
247
262
  </div>
248
263
  </TableProvider>
249
264
  );
250
- };
265
+ }