react-resource-ui 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -0
- package/dist/index.cjs +236 -0
- package/dist/index.css +13 -0
- package/dist/index.d.cts +53 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +208 -0
- package/package.json +27 -0
package/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# React + TypeScript + Vite
|
|
2
|
+
|
|
3
|
+
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
|
4
|
+
|
|
5
|
+
Currently, two official plugins are available:
|
|
6
|
+
|
|
7
|
+
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
|
8
|
+
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
|
9
|
+
|
|
10
|
+
## React Compiler
|
|
11
|
+
|
|
12
|
+
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
|
13
|
+
|
|
14
|
+
## Expanding the ESLint configuration
|
|
15
|
+
|
|
16
|
+
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
export default defineConfig([
|
|
20
|
+
globalIgnores(['dist']),
|
|
21
|
+
{
|
|
22
|
+
files: ['**/*.{ts,tsx}'],
|
|
23
|
+
extends: [
|
|
24
|
+
// Other configs...
|
|
25
|
+
|
|
26
|
+
// Remove tseslint.configs.recommended and replace with this
|
|
27
|
+
tseslint.configs.recommendedTypeChecked,
|
|
28
|
+
// Alternatively, use this for stricter rules
|
|
29
|
+
tseslint.configs.strictTypeChecked,
|
|
30
|
+
// Optionally, add this for stylistic rules
|
|
31
|
+
tseslint.configs.stylisticTypeChecked,
|
|
32
|
+
|
|
33
|
+
// Other configs...
|
|
34
|
+
],
|
|
35
|
+
languageOptions: {
|
|
36
|
+
parserOptions: {
|
|
37
|
+
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
|
38
|
+
tsconfigRootDir: import.meta.dirname,
|
|
39
|
+
},
|
|
40
|
+
// other options...
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
])
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
// eslint.config.js
|
|
50
|
+
import reactX from 'eslint-plugin-react-x'
|
|
51
|
+
import reactDom from 'eslint-plugin-react-dom'
|
|
52
|
+
|
|
53
|
+
export default defineConfig([
|
|
54
|
+
globalIgnores(['dist']),
|
|
55
|
+
{
|
|
56
|
+
files: ['**/*.{ts,tsx}'],
|
|
57
|
+
extends: [
|
|
58
|
+
// Other configs...
|
|
59
|
+
// Enable lint rules for React
|
|
60
|
+
reactX.configs['recommended-typescript'],
|
|
61
|
+
// Enable lint rules for React DOM
|
|
62
|
+
reactDom.configs.recommended,
|
|
63
|
+
],
|
|
64
|
+
languageOptions: {
|
|
65
|
+
parserOptions: {
|
|
66
|
+
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
|
67
|
+
tsconfigRootDir: import.meta.dirname,
|
|
68
|
+
},
|
|
69
|
+
// other options...
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
])
|
|
73
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
DataTable: () => DataTable,
|
|
24
|
+
useResource: () => useResource
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
|
|
28
|
+
// src/hooks/useResource.ts
|
|
29
|
+
var import_react = require("react");
|
|
30
|
+
|
|
31
|
+
// src/engine/source.ts
|
|
32
|
+
function normalizeSource(source) {
|
|
33
|
+
return async function getData(params) {
|
|
34
|
+
const { page = 1, pageSize = 10 } = params;
|
|
35
|
+
if (Array.isArray(source)) {
|
|
36
|
+
const start = (page - 1) * pageSize;
|
|
37
|
+
const end = start + pageSize;
|
|
38
|
+
return source.slice(start, end);
|
|
39
|
+
}
|
|
40
|
+
if (typeof source === "string") {
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(source);
|
|
43
|
+
url.searchParams.set("page", String(page));
|
|
44
|
+
url.searchParams.set("pageSize", String(pageSize));
|
|
45
|
+
const call = await fetch(url.toString());
|
|
46
|
+
if (!call.ok) {
|
|
47
|
+
throw new Error(`Request Failed: ${call.status}`);
|
|
48
|
+
}
|
|
49
|
+
const jsonData = await call.json();
|
|
50
|
+
return jsonData;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (err instanceof Error) throw err;
|
|
53
|
+
throw new Error("Unknown error");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return source(params);
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/hooks/useResource.ts
|
|
61
|
+
function useResource(config) {
|
|
62
|
+
const pagination = config.pagination;
|
|
63
|
+
const [data, setData] = (0, import_react.useState)([]);
|
|
64
|
+
const [error, setError] = (0, import_react.useState)(null);
|
|
65
|
+
const [loading, setLoading] = (0, import_react.useState)(false);
|
|
66
|
+
const [page, setPage] = (0, import_react.useState)(1);
|
|
67
|
+
const [scrollTop, setScrollTop] = (0, import_react.useState)(0);
|
|
68
|
+
const pageSize = pagination?.pageSize ? pagination?.pageSize : 10;
|
|
69
|
+
const source = config.source;
|
|
70
|
+
const requestTracker = (0, import_react.useRef)(0);
|
|
71
|
+
const cache = (0, import_react.useRef)({});
|
|
72
|
+
const virtualization = config.virtualization?.enabled;
|
|
73
|
+
const getData = (0, import_react.useMemo)(() => normalizeSource(source), [source]);
|
|
74
|
+
const prevScrollTop = (0, import_react.useRef)(0);
|
|
75
|
+
const scrollRef = (0, import_react.useRef)(null);
|
|
76
|
+
const hasMore = (0, import_react.useRef)(true);
|
|
77
|
+
async function asyncNormalize() {
|
|
78
|
+
const params = {
|
|
79
|
+
page,
|
|
80
|
+
pageSize
|
|
81
|
+
};
|
|
82
|
+
setLoading(true);
|
|
83
|
+
requestTracker.current += 1;
|
|
84
|
+
const currentRequestId = requestTracker.current;
|
|
85
|
+
setError(null);
|
|
86
|
+
try {
|
|
87
|
+
const rawData = await getData(params);
|
|
88
|
+
if (currentRequestId !== requestTracker.current) {
|
|
89
|
+
setLoading(false);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
;
|
|
93
|
+
setLoading(false);
|
|
94
|
+
return rawData;
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (currentRequestId === requestTracker.current) {
|
|
97
|
+
if (err instanceof Error) {
|
|
98
|
+
setError(err);
|
|
99
|
+
} else {
|
|
100
|
+
setError(new Error("unknown error"));
|
|
101
|
+
}
|
|
102
|
+
setLoading(false);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async function orchestrator() {
|
|
107
|
+
const isPageMode = pagination?.type === "page";
|
|
108
|
+
prevScrollTop.current = scrollTop;
|
|
109
|
+
const cached = cache.current[page];
|
|
110
|
+
if (isPageMode) {
|
|
111
|
+
if (cached) {
|
|
112
|
+
setData(cached);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const rawData = await asyncNormalize();
|
|
117
|
+
if (!rawData) return;
|
|
118
|
+
if (rawData.length < pageSize) hasMore.current = false;
|
|
119
|
+
setData((prev) => {
|
|
120
|
+
if (isPageMode) return rawData;
|
|
121
|
+
return page === 1 ? rawData : [...prev, ...rawData];
|
|
122
|
+
});
|
|
123
|
+
if (isPageMode) {
|
|
124
|
+
cache.current[page] = rawData;
|
|
125
|
+
Object.keys(cache.current).forEach((val) => {
|
|
126
|
+
if (Math.abs(page - +val) > 1) {
|
|
127
|
+
delete cache.current[+val];
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
(0, import_react.useEffect)(() => {
|
|
133
|
+
if (!hasMore.current) return;
|
|
134
|
+
if (pagination?.type !== "infinite") return;
|
|
135
|
+
const el = scrollRef.current;
|
|
136
|
+
if (!el) return;
|
|
137
|
+
const remaining = el.scrollHeight - scrollTop - el.clientHeight;
|
|
138
|
+
if (remaining < 50 && !loading) {
|
|
139
|
+
(() => {
|
|
140
|
+
setPage((prev) => prev + 1);
|
|
141
|
+
})();
|
|
142
|
+
}
|
|
143
|
+
}, [scrollTop, pagination?.type, loading]);
|
|
144
|
+
(0, import_react.useEffect)(() => {
|
|
145
|
+
orchestrator();
|
|
146
|
+
}, [page, pageSize, source, pagination?.type]);
|
|
147
|
+
(0, import_react.useEffect)(() => {
|
|
148
|
+
if (pagination?.type === "page") {
|
|
149
|
+
(() => setScrollTop(0))();
|
|
150
|
+
}
|
|
151
|
+
}, [page, pagination?.type]);
|
|
152
|
+
(0, import_react.useEffect)(() => {
|
|
153
|
+
if (pagination?.type !== "page") {
|
|
154
|
+
if (scrollRef.current) {
|
|
155
|
+
scrollRef.current.scrollTop = prevScrollTop.current;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}, [data]);
|
|
159
|
+
let finalData = data;
|
|
160
|
+
const itemHeight = config.virtualization?.itemHeight ?? 40;
|
|
161
|
+
const containerHeight = config.virtualization?.containerHeight ?? 400;
|
|
162
|
+
const shouldVirtualize = virtualization && data.length * itemHeight > containerHeight;
|
|
163
|
+
let offsetY = 0;
|
|
164
|
+
let totalHeight = 0;
|
|
165
|
+
if (shouldVirtualize) {
|
|
166
|
+
const total = data.length;
|
|
167
|
+
const rawStart = Math.floor(scrollTop / itemHeight);
|
|
168
|
+
const startIndex = Math.max(0, rawStart - 2);
|
|
169
|
+
const visibleCount = Math.ceil(containerHeight / itemHeight);
|
|
170
|
+
const endIndex = Math.min(startIndex + visibleCount + 4, total);
|
|
171
|
+
finalData = data.slice(startIndex, endIndex);
|
|
172
|
+
offsetY = itemHeight * startIndex;
|
|
173
|
+
totalHeight = total * itemHeight;
|
|
174
|
+
}
|
|
175
|
+
return { data: finalData, loading, error, page, setPage, setScrollTop, offsetY, totalHeight, totalItems: data.length, scrollRef };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// src/components/DataTable.tsx
|
|
179
|
+
var import_react2 = require("react");
|
|
180
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
181
|
+
function DataTable(props) {
|
|
182
|
+
const { data, loading, error, page, setPage, setScrollTop, type, virtualization } = props;
|
|
183
|
+
const isFetchingRef = (0, import_react2.useRef)(false);
|
|
184
|
+
(0, import_react2.useEffect)(() => {
|
|
185
|
+
isFetchingRef.current = false;
|
|
186
|
+
}, [data]);
|
|
187
|
+
if (loading) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Loading..." });
|
|
188
|
+
if (error) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: error.message });
|
|
189
|
+
if ((props.totalItems ?? data.length) === 0) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: "No Data to create Table" });
|
|
190
|
+
const content = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("table", { children: [
|
|
191
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("tr", { children: Object.keys(data[0]).map((val) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("th", { children: val }, val)) }) }),
|
|
192
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("tbody", { children: data.map((val, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("tr", { children: Object.keys(val).map((key) => {
|
|
193
|
+
const value = val[key];
|
|
194
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("td", { children: value != null ? value.toString() : "-" }, key);
|
|
195
|
+
}) }, index)) })
|
|
196
|
+
] });
|
|
197
|
+
const offsetY = props.offsetY ?? 0;
|
|
198
|
+
const totalHeight = props.totalHeight ?? 0;
|
|
199
|
+
const finalTable = virtualization ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
200
|
+
"div",
|
|
201
|
+
{
|
|
202
|
+
ref: props.scrollRef ?? null,
|
|
203
|
+
style: { height: 400, overflowY: "auto" },
|
|
204
|
+
onScroll: (e) => {
|
|
205
|
+
setScrollTop(e.currentTarget.scrollTop);
|
|
206
|
+
},
|
|
207
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { height: totalHeight, position: "relative" }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
208
|
+
"div",
|
|
209
|
+
{
|
|
210
|
+
style: {
|
|
211
|
+
transform: `translateY(${offsetY}px)`,
|
|
212
|
+
position: "absolute",
|
|
213
|
+
top: 0,
|
|
214
|
+
left: 0,
|
|
215
|
+
right: 0
|
|
216
|
+
},
|
|
217
|
+
children: content
|
|
218
|
+
}
|
|
219
|
+
) })
|
|
220
|
+
}
|
|
221
|
+
) : content;
|
|
222
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
|
|
223
|
+
type === "page" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
|
|
224
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => setPage((prev) => Math.max(prev - 1, 1)), children: "prev" }),
|
|
225
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: page }),
|
|
226
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => setPage((prev) => prev + 1), children: "next" })
|
|
227
|
+
] }),
|
|
228
|
+
finalTable,
|
|
229
|
+
type === "loadmore" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { onClick: () => setPage((prev) => prev + 1), children: "load more" })
|
|
230
|
+
] });
|
|
231
|
+
}
|
|
232
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
233
|
+
0 && (module.exports = {
|
|
234
|
+
DataTable,
|
|
235
|
+
useResource
|
|
236
|
+
});
|
package/dist/index.css
ADDED
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
3
|
+
|
|
4
|
+
type ResourceParams = {
|
|
5
|
+
page?: number;
|
|
6
|
+
pageSize?: number;
|
|
7
|
+
};
|
|
8
|
+
type Source<T> = T[] | string | ((params: ResourceParams) => Promise<T[]>);
|
|
9
|
+
|
|
10
|
+
type PaginationConfig = {
|
|
11
|
+
type: "page" | "loadmore" | "infinite";
|
|
12
|
+
pageSize?: number;
|
|
13
|
+
};
|
|
14
|
+
type virtualizationConfig = {
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
itemHeight: number;
|
|
17
|
+
containerHeight: number;
|
|
18
|
+
};
|
|
19
|
+
type Config<T> = {
|
|
20
|
+
source: Source<T>;
|
|
21
|
+
pagination?: PaginationConfig;
|
|
22
|
+
virtualization?: virtualizationConfig;
|
|
23
|
+
};
|
|
24
|
+
declare function useResource<T>(config: Config<T>): {
|
|
25
|
+
data: T[];
|
|
26
|
+
loading: boolean;
|
|
27
|
+
error: Error | null;
|
|
28
|
+
page: number;
|
|
29
|
+
setPage: react.Dispatch<react.SetStateAction<number>>;
|
|
30
|
+
setScrollTop: react.Dispatch<react.SetStateAction<number>>;
|
|
31
|
+
offsetY: number;
|
|
32
|
+
totalHeight: number;
|
|
33
|
+
totalItems: number;
|
|
34
|
+
scrollRef: react.RefObject<HTMLDivElement | null>;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
type DataTableProps<T extends Record<string, unknown>> = {
|
|
38
|
+
data: T[];
|
|
39
|
+
loading?: boolean;
|
|
40
|
+
error?: Error | null;
|
|
41
|
+
page?: number;
|
|
42
|
+
setPage: React.Dispatch<React.SetStateAction<number>>;
|
|
43
|
+
setScrollTop: React.Dispatch<React.SetStateAction<number>>;
|
|
44
|
+
type: "page" | "loadmore" | "infinite";
|
|
45
|
+
virtualization?: boolean;
|
|
46
|
+
offsetY?: number;
|
|
47
|
+
totalHeight?: number;
|
|
48
|
+
totalItems?: number;
|
|
49
|
+
scrollRef?: React.RefObject<HTMLDivElement> | null;
|
|
50
|
+
};
|
|
51
|
+
declare function DataTable<T extends Record<string, unknown>>(props: DataTableProps<T>): react_jsx_runtime.JSX.Element;
|
|
52
|
+
|
|
53
|
+
export { DataTable, useResource };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
3
|
+
|
|
4
|
+
type ResourceParams = {
|
|
5
|
+
page?: number;
|
|
6
|
+
pageSize?: number;
|
|
7
|
+
};
|
|
8
|
+
type Source<T> = T[] | string | ((params: ResourceParams) => Promise<T[]>);
|
|
9
|
+
|
|
10
|
+
type PaginationConfig = {
|
|
11
|
+
type: "page" | "loadmore" | "infinite";
|
|
12
|
+
pageSize?: number;
|
|
13
|
+
};
|
|
14
|
+
type virtualizationConfig = {
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
itemHeight: number;
|
|
17
|
+
containerHeight: number;
|
|
18
|
+
};
|
|
19
|
+
type Config<T> = {
|
|
20
|
+
source: Source<T>;
|
|
21
|
+
pagination?: PaginationConfig;
|
|
22
|
+
virtualization?: virtualizationConfig;
|
|
23
|
+
};
|
|
24
|
+
declare function useResource<T>(config: Config<T>): {
|
|
25
|
+
data: T[];
|
|
26
|
+
loading: boolean;
|
|
27
|
+
error: Error | null;
|
|
28
|
+
page: number;
|
|
29
|
+
setPage: react.Dispatch<react.SetStateAction<number>>;
|
|
30
|
+
setScrollTop: react.Dispatch<react.SetStateAction<number>>;
|
|
31
|
+
offsetY: number;
|
|
32
|
+
totalHeight: number;
|
|
33
|
+
totalItems: number;
|
|
34
|
+
scrollRef: react.RefObject<HTMLDivElement | null>;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
type DataTableProps<T extends Record<string, unknown>> = {
|
|
38
|
+
data: T[];
|
|
39
|
+
loading?: boolean;
|
|
40
|
+
error?: Error | null;
|
|
41
|
+
page?: number;
|
|
42
|
+
setPage: React.Dispatch<React.SetStateAction<number>>;
|
|
43
|
+
setScrollTop: React.Dispatch<React.SetStateAction<number>>;
|
|
44
|
+
type: "page" | "loadmore" | "infinite";
|
|
45
|
+
virtualization?: boolean;
|
|
46
|
+
offsetY?: number;
|
|
47
|
+
totalHeight?: number;
|
|
48
|
+
totalItems?: number;
|
|
49
|
+
scrollRef?: React.RefObject<HTMLDivElement> | null;
|
|
50
|
+
};
|
|
51
|
+
declare function DataTable<T extends Record<string, unknown>>(props: DataTableProps<T>): react_jsx_runtime.JSX.Element;
|
|
52
|
+
|
|
53
|
+
export { DataTable, useResource };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// src/hooks/useResource.ts
|
|
2
|
+
import { useEffect, useState, useRef, useMemo } from "react";
|
|
3
|
+
|
|
4
|
+
// src/engine/source.ts
|
|
5
|
+
function normalizeSource(source) {
|
|
6
|
+
return async function getData(params) {
|
|
7
|
+
const { page = 1, pageSize = 10 } = params;
|
|
8
|
+
if (Array.isArray(source)) {
|
|
9
|
+
const start = (page - 1) * pageSize;
|
|
10
|
+
const end = start + pageSize;
|
|
11
|
+
return source.slice(start, end);
|
|
12
|
+
}
|
|
13
|
+
if (typeof source === "string") {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(source);
|
|
16
|
+
url.searchParams.set("page", String(page));
|
|
17
|
+
url.searchParams.set("pageSize", String(pageSize));
|
|
18
|
+
const call = await fetch(url.toString());
|
|
19
|
+
if (!call.ok) {
|
|
20
|
+
throw new Error(`Request Failed: ${call.status}`);
|
|
21
|
+
}
|
|
22
|
+
const jsonData = await call.json();
|
|
23
|
+
return jsonData;
|
|
24
|
+
} catch (err) {
|
|
25
|
+
if (err instanceof Error) throw err;
|
|
26
|
+
throw new Error("Unknown error");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return source(params);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/hooks/useResource.ts
|
|
34
|
+
function useResource(config) {
|
|
35
|
+
const pagination = config.pagination;
|
|
36
|
+
const [data, setData] = useState([]);
|
|
37
|
+
const [error, setError] = useState(null);
|
|
38
|
+
const [loading, setLoading] = useState(false);
|
|
39
|
+
const [page, setPage] = useState(1);
|
|
40
|
+
const [scrollTop, setScrollTop] = useState(0);
|
|
41
|
+
const pageSize = pagination?.pageSize ? pagination?.pageSize : 10;
|
|
42
|
+
const source = config.source;
|
|
43
|
+
const requestTracker = useRef(0);
|
|
44
|
+
const cache = useRef({});
|
|
45
|
+
const virtualization = config.virtualization?.enabled;
|
|
46
|
+
const getData = useMemo(() => normalizeSource(source), [source]);
|
|
47
|
+
const prevScrollTop = useRef(0);
|
|
48
|
+
const scrollRef = useRef(null);
|
|
49
|
+
const hasMore = useRef(true);
|
|
50
|
+
async function asyncNormalize() {
|
|
51
|
+
const params = {
|
|
52
|
+
page,
|
|
53
|
+
pageSize
|
|
54
|
+
};
|
|
55
|
+
setLoading(true);
|
|
56
|
+
requestTracker.current += 1;
|
|
57
|
+
const currentRequestId = requestTracker.current;
|
|
58
|
+
setError(null);
|
|
59
|
+
try {
|
|
60
|
+
const rawData = await getData(params);
|
|
61
|
+
if (currentRequestId !== requestTracker.current) {
|
|
62
|
+
setLoading(false);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
;
|
|
66
|
+
setLoading(false);
|
|
67
|
+
return rawData;
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (currentRequestId === requestTracker.current) {
|
|
70
|
+
if (err instanceof Error) {
|
|
71
|
+
setError(err);
|
|
72
|
+
} else {
|
|
73
|
+
setError(new Error("unknown error"));
|
|
74
|
+
}
|
|
75
|
+
setLoading(false);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function orchestrator() {
|
|
80
|
+
const isPageMode = pagination?.type === "page";
|
|
81
|
+
prevScrollTop.current = scrollTop;
|
|
82
|
+
const cached = cache.current[page];
|
|
83
|
+
if (isPageMode) {
|
|
84
|
+
if (cached) {
|
|
85
|
+
setData(cached);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const rawData = await asyncNormalize();
|
|
90
|
+
if (!rawData) return;
|
|
91
|
+
if (rawData.length < pageSize) hasMore.current = false;
|
|
92
|
+
setData((prev) => {
|
|
93
|
+
if (isPageMode) return rawData;
|
|
94
|
+
return page === 1 ? rawData : [...prev, ...rawData];
|
|
95
|
+
});
|
|
96
|
+
if (isPageMode) {
|
|
97
|
+
cache.current[page] = rawData;
|
|
98
|
+
Object.keys(cache.current).forEach((val) => {
|
|
99
|
+
if (Math.abs(page - +val) > 1) {
|
|
100
|
+
delete cache.current[+val];
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
useEffect(() => {
|
|
106
|
+
if (!hasMore.current) return;
|
|
107
|
+
if (pagination?.type !== "infinite") return;
|
|
108
|
+
const el = scrollRef.current;
|
|
109
|
+
if (!el) return;
|
|
110
|
+
const remaining = el.scrollHeight - scrollTop - el.clientHeight;
|
|
111
|
+
if (remaining < 50 && !loading) {
|
|
112
|
+
(() => {
|
|
113
|
+
setPage((prev) => prev + 1);
|
|
114
|
+
})();
|
|
115
|
+
}
|
|
116
|
+
}, [scrollTop, pagination?.type, loading]);
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
orchestrator();
|
|
119
|
+
}, [page, pageSize, source, pagination?.type]);
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
if (pagination?.type === "page") {
|
|
122
|
+
(() => setScrollTop(0))();
|
|
123
|
+
}
|
|
124
|
+
}, [page, pagination?.type]);
|
|
125
|
+
useEffect(() => {
|
|
126
|
+
if (pagination?.type !== "page") {
|
|
127
|
+
if (scrollRef.current) {
|
|
128
|
+
scrollRef.current.scrollTop = prevScrollTop.current;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}, [data]);
|
|
132
|
+
let finalData = data;
|
|
133
|
+
const itemHeight = config.virtualization?.itemHeight ?? 40;
|
|
134
|
+
const containerHeight = config.virtualization?.containerHeight ?? 400;
|
|
135
|
+
const shouldVirtualize = virtualization && data.length * itemHeight > containerHeight;
|
|
136
|
+
let offsetY = 0;
|
|
137
|
+
let totalHeight = 0;
|
|
138
|
+
if (shouldVirtualize) {
|
|
139
|
+
const total = data.length;
|
|
140
|
+
const rawStart = Math.floor(scrollTop / itemHeight);
|
|
141
|
+
const startIndex = Math.max(0, rawStart - 2);
|
|
142
|
+
const visibleCount = Math.ceil(containerHeight / itemHeight);
|
|
143
|
+
const endIndex = Math.min(startIndex + visibleCount + 4, total);
|
|
144
|
+
finalData = data.slice(startIndex, endIndex);
|
|
145
|
+
offsetY = itemHeight * startIndex;
|
|
146
|
+
totalHeight = total * itemHeight;
|
|
147
|
+
}
|
|
148
|
+
return { data: finalData, loading, error, page, setPage, setScrollTop, offsetY, totalHeight, totalItems: data.length, scrollRef };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/components/DataTable.tsx
|
|
152
|
+
import { useEffect as useEffect2, useRef as useRef2 } from "react";
|
|
153
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
154
|
+
function DataTable(props) {
|
|
155
|
+
const { data, loading, error, page, setPage, setScrollTop, type, virtualization } = props;
|
|
156
|
+
const isFetchingRef = useRef2(false);
|
|
157
|
+
useEffect2(() => {
|
|
158
|
+
isFetchingRef.current = false;
|
|
159
|
+
}, [data]);
|
|
160
|
+
if (loading) return /* @__PURE__ */ jsx("div", { children: "Loading..." });
|
|
161
|
+
if (error) return /* @__PURE__ */ jsx("div", { children: error.message });
|
|
162
|
+
if ((props.totalItems ?? data.length) === 0) return /* @__PURE__ */ jsx("p", { children: "No Data to create Table" });
|
|
163
|
+
const content = /* @__PURE__ */ jsxs("table", { children: [
|
|
164
|
+
/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: Object.keys(data[0]).map((val) => /* @__PURE__ */ jsx("th", { children: val }, val)) }) }),
|
|
165
|
+
/* @__PURE__ */ jsx("tbody", { children: data.map((val, index) => /* @__PURE__ */ jsx("tr", { children: Object.keys(val).map((key) => {
|
|
166
|
+
const value = val[key];
|
|
167
|
+
return /* @__PURE__ */ jsx("td", { children: value != null ? value.toString() : "-" }, key);
|
|
168
|
+
}) }, index)) })
|
|
169
|
+
] });
|
|
170
|
+
const offsetY = props.offsetY ?? 0;
|
|
171
|
+
const totalHeight = props.totalHeight ?? 0;
|
|
172
|
+
const finalTable = virtualization ? /* @__PURE__ */ jsx(
|
|
173
|
+
"div",
|
|
174
|
+
{
|
|
175
|
+
ref: props.scrollRef ?? null,
|
|
176
|
+
style: { height: 400, overflowY: "auto" },
|
|
177
|
+
onScroll: (e) => {
|
|
178
|
+
setScrollTop(e.currentTarget.scrollTop);
|
|
179
|
+
},
|
|
180
|
+
children: /* @__PURE__ */ jsx("div", { style: { height: totalHeight, position: "relative" }, children: /* @__PURE__ */ jsx(
|
|
181
|
+
"div",
|
|
182
|
+
{
|
|
183
|
+
style: {
|
|
184
|
+
transform: `translateY(${offsetY}px)`,
|
|
185
|
+
position: "absolute",
|
|
186
|
+
top: 0,
|
|
187
|
+
left: 0,
|
|
188
|
+
right: 0
|
|
189
|
+
},
|
|
190
|
+
children: content
|
|
191
|
+
}
|
|
192
|
+
) })
|
|
193
|
+
}
|
|
194
|
+
) : content;
|
|
195
|
+
return /* @__PURE__ */ jsxs("div", { children: [
|
|
196
|
+
type === "page" && /* @__PURE__ */ jsxs("div", { children: [
|
|
197
|
+
/* @__PURE__ */ jsx("button", { onClick: () => setPage((prev) => Math.max(prev - 1, 1)), children: "prev" }),
|
|
198
|
+
/* @__PURE__ */ jsx("span", { children: page }),
|
|
199
|
+
/* @__PURE__ */ jsx("button", { onClick: () => setPage((prev) => prev + 1), children: "next" })
|
|
200
|
+
] }),
|
|
201
|
+
finalTable,
|
|
202
|
+
type === "loadmore" && /* @__PURE__ */ jsx("button", { onClick: () => setPage((prev) => prev + 1), children: "load more" })
|
|
203
|
+
] });
|
|
204
|
+
}
|
|
205
|
+
export {
|
|
206
|
+
DataTable,
|
|
207
|
+
useResource
|
|
208
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "react-resource-ui",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A high-level data orchestration hook for React with pagination, caching, and virtualization",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"module": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"files": ["dist"],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsup src/index.ts --format esm,cjs --dts"
|
|
14
|
+
},
|
|
15
|
+
|
|
16
|
+
"peerDependencies": {
|
|
17
|
+
"react": "^18 || ^19",
|
|
18
|
+
"react-dom": "^18 || ^19"
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/react": "^19.2.14",
|
|
23
|
+
"@types/react-dom": "^19.2.3",
|
|
24
|
+
"tsup": "^8.5.1",
|
|
25
|
+
"typescript": "~5.9.3"
|
|
26
|
+
}
|
|
27
|
+
}
|