@capsitech/react-utilities 0.1.6 → 0.1.7

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/lib/logo.png ADDED
Binary file
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@capsitech/react-utilities",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "A set of javascript utility methods",
5
- "main": "lib/index.js",
6
- "jsnext:main": "lib/index.js",
7
- "types": "lib/index.d.ts",
5
+ "main": "lib/index.cjs",
8
6
  "module": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "import": "./lib/index.js",
12
+ "require": "./lib/index.cjs"
13
+ }
14
+ },
9
15
  "files": [
10
16
  "lib",
11
17
  "README.md",
@@ -31,7 +37,7 @@
31
37
  },
32
38
  "scripts": {
33
39
  "clean": "rimraf lib",
34
- "build": "yarn clean && tsc --project ./tsconfig.json --module es2015 --outDir ./lib -d",
40
+ "build": "yarn clean && vite build",
35
41
  "build:publish": "yarn && npm version patch && yarn build && npm publish",
36
42
  "start": "storybook dev -p 6006"
37
43
  },
@@ -44,7 +50,8 @@
44
50
  "file-saver": "^2.0.5",
45
51
  "qs": "^6.14.0",
46
52
  "react": ">=18",
47
- "react-dom": ">=18"
53
+ "react-dom": ">=18",
54
+ "react-router-dom": "^7.8.1"
48
55
  },
49
56
  "devDependencies": {
50
57
  "@storybook/addon-docs": "^9.1.2",
@@ -54,6 +61,7 @@
54
61
  "@types/lodash": "4.17.20",
55
62
  "@types/qs": "^6",
56
63
  "@types/react": "^18.3.12",
64
+ "@vitejs/plugin-react": "^5.0.2",
57
65
  "axios": "^1.11.0",
58
66
  "file-saver": "^2.0.5",
59
67
  "qs": "^6.14.0",
@@ -62,7 +70,9 @@
62
70
  "react-router-dom": "^7.8.1",
63
71
  "rimraf": "6.0.1",
64
72
  "storybook": "^9.1.2",
65
- "typescript": "5.8.3"
73
+ "typescript": "5.8.3",
74
+ "vite": "^7.1.4",
75
+ "vite-plugin-dts": "^4.5.4"
66
76
  },
67
77
  "browserslist": {
68
78
  "production": [
@@ -1,29 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import React from "react";
3
- const isSuspenseComponent = (component) => typeof component === "object" &&
4
- component &&
5
- component.hasOwnProperty("$$typeof") &&
6
- component.hasOwnProperty("_payload") &&
7
- component.hasOwnProperty("_init");
8
- export const SuspenseRoute = ({ children: Component, label = "Loading components...", fallback: FallbackComponent, }) => {
9
- if (isSuspenseComponent(Component)) {
10
- if (!FallbackComponent)
11
- FallbackComponent = SuspenseRouteFallback;
12
- return _jsx(React.Suspense, { fallback: _jsx(FallbackComponent, { label: label }), children: _jsx(Component, {}) });
13
- }
14
- return (_jsx(Component, {}));
15
- };
16
- const SuspenseRouteFallback = ({ label = "Loading components..." }) => {
17
- return _jsx("div", { style: {
18
- position: 'fixed',
19
- top: 0,
20
- left: 0,
21
- width: '100%',
22
- height: '100%',
23
- backgroundColor: 'rgba(0, 0, 0, 0.3)',
24
- zIndex: 9999,
25
- display: 'flex',
26
- justifyContent: 'center',
27
- alignItems: 'center'
28
- }, children: label });
29
- };
@@ -1 +0,0 @@
1
- export * from './SuspenseRoute';
@@ -1,98 +0,0 @@
1
- import { useCallback, useEffect, useRef } from 'react';
2
- export * from './useInfiniteScroll';
3
- export * from './useNetworkState';
4
- export * from './useShortcuts';
5
- /**
6
- * React effect hook that invokes only on update.
7
- * It doesn't invoke on mount
8
- */
9
- export const useUpdateEffect = (effect, deps) => {
10
- const mounted = useRef(false);
11
- useEffect(() => {
12
- if (mounted.current) {
13
- return effect();
14
- }
15
- mounted.current = true;
16
- return undefined;
17
- // eslint-disable-next-line react-hooks/exhaustive-deps
18
- }, deps);
19
- return mounted.current;
20
- };
21
- /**
22
- * React hook to persist any value between renders,
23
- * but keeps it up-to-date if it changes.
24
- *
25
- * @param value the value or function to persist
26
- */
27
- export function useLatestRef(value) {
28
- const ref = useRef(value);
29
- useEffect(() => {
30
- ref.current = value;
31
- }, [value]);
32
- return ref;
33
- }
34
- /**
35
- * useCallbackRef hook
36
- *
37
- * A custom hook that converts a callback to a ref to avoid triggering re-renders
38
- * ..when passed as a prop or avoid re-executing effects when passed as a dependency
39
- *
40
- * @param callback The callback to write to a ref object
41
- */
42
- export const useCallbackRef = (callback) => {
43
- const callbackRef = useRef(callback);
44
- useEffect(() => {
45
- callbackRef.current = callback;
46
- });
47
- return useCallback(((...args) => {
48
- return callbackRef.current?.(...args);
49
- }), []);
50
- };
51
- /**
52
- * useFirstRenderState hook
53
- *
54
- * Returns "true" if component is just mounted (first render), else "false".
55
- */
56
- export const useFirstRenderState = () => {
57
- const isFirst = useRef(true);
58
- if (isFirst.current) {
59
- isFirst.current = false;
60
- return true;
61
- }
62
- return isFirst.current;
63
- };
64
- /**
65
- * React Hook that provides a declarative `setInterval`
66
- *
67
- * @param callback the callback to execute at interval
68
- * @param delay the `setInterval` delay (in ms)
69
- */
70
- export function useInterval(callback, delay) {
71
- const savedCallback = useLatestRef(callback);
72
- useEffect(() => {
73
- const tick = () => {
74
- savedCallback.current?.();
75
- };
76
- if (delay !== null) {
77
- const id = setInterval(tick, delay);
78
- return () => clearInterval(id);
79
- }
80
- }, [delay, savedCallback]);
81
- }
82
- /**
83
- * React hook that provides a declarative `setTimeout`
84
- *
85
- * @param callback the callback to run after specified delay
86
- * @param delay the delay (in ms)
87
- */
88
- export function useTimeout(callback, delay) {
89
- const savedCallback = useLatestRef(callback);
90
- useEffect(() => {
91
- if (delay == null)
92
- return;
93
- const timeoutId = setTimeout(() => {
94
- savedCallback.current?.();
95
- }, delay);
96
- return () => clearTimeout(timeoutId);
97
- }, [delay, savedCallback]);
98
- }
@@ -1,22 +0,0 @@
1
- import React from 'react';
2
- /**
3
- * Infinite scrolling with intersection observer
4
- * @param scrollRef Reference object for observe bottom boundary
5
- * @param dispatch Trigger an action that updates the page number
6
- */
7
- export const useInfiniteScroll = (scrollRef, dispatch) => {
8
- const scrollObserver = React.useCallback((node) => {
9
- new IntersectionObserver((entries) => {
10
- entries.forEach((en) => {
11
- if (en.intersectionRatio > 0) {
12
- dispatch({ type: 'next-page' });
13
- }
14
- });
15
- }).observe(node);
16
- }, [dispatch]);
17
- React.useEffect(() => {
18
- if (scrollRef.current) {
19
- scrollObserver(scrollRef.current);
20
- }
21
- }, [scrollObserver, scrollRef]);
22
- };
@@ -1,41 +0,0 @@
1
- import React from 'react';
2
- export const isBrowser = typeof window !== 'undefined';
3
- export const isNavigator = typeof navigator !== 'undefined';
4
- const nav = isNavigator ? navigator : undefined;
5
- const conn = nav && (nav.connection || nav.mozConnection || nav.webkitConnection);
6
- function getConnectionState(previousState) {
7
- const online = nav?.onLine;
8
- const previousOnline = previousState?.online;
9
- return {
10
- online,
11
- previous: previousOnline,
12
- since: online !== previousOnline ? new Date() : previousState?.since,
13
- downlink: conn?.downlink,
14
- downlinkMax: conn?.downlinkMax,
15
- effectiveType: conn?.effectiveType,
16
- rtt: conn?.rtt,
17
- saveData: conn?.saveData,
18
- type: conn?.type,
19
- };
20
- }
21
- export function useNetworkState(initialState) {
22
- const [state, setState] = React.useState(initialState ?? getConnectionState);
23
- React.useEffect(() => {
24
- const handleStateChange = () => {
25
- setState(getConnectionState);
26
- };
27
- window.addEventListener('online', handleStateChange, { passive: true });
28
- window.addEventListener('offline', handleStateChange, { passive: true });
29
- if (conn) {
30
- window.addEventListener('change', handleStateChange, { passive: true });
31
- }
32
- return () => {
33
- window.removeEventListener('online', handleStateChange);
34
- window.removeEventListener('offline', handleStateChange);
35
- if (conn) {
36
- window.removeEventListener('change', handleStateChange);
37
- }
38
- };
39
- }, []);
40
- return state;
41
- }
@@ -1,91 +0,0 @@
1
- import React from 'react';
2
- const blacklistedTargets = ['INPUT', 'TEXTAREA', 'SELECT'];
3
- const keysReducer = (state, action) => {
4
- switch (action.type) {
5
- case 'set-key-down':
6
- const keydownState = { ...state, [action.key]: true };
7
- return keydownState;
8
- case 'set-key-up':
9
- const keyUpState = { ...state, [action.key]: false };
10
- return keyUpState;
11
- case 'reset-keys':
12
- const resetState = { ...action.data };
13
- return resetState;
14
- default:
15
- return state;
16
- }
17
- };
18
- export const useShortcuts = (shortcutKeys, callback, options) => {
19
- if (!Array.isArray(shortcutKeys))
20
- throw new Error('The first parameter to `useShortcuts` must be an ordered array of `KeyboardEvent.key` strings.');
21
- if (!shortcutKeys.length)
22
- throw new Error('The first parameter to `useShortcuts` must contain atleast one `KeyboardEvent.key` string.');
23
- if (!callback || typeof callback !== 'function')
24
- throw new Error('The second parameter to `useShortcuts` must be a function that will be envoked when the keys are pressed.');
25
- const { overrideSystem } = options || {};
26
- const initalKeyMapping = shortcutKeys.reduce((currentKeys, key) => {
27
- currentKeys[key.toLowerCase()] = false;
28
- return currentKeys;
29
- }, {});
30
- const [keys, setKeys] = React.useReducer(keysReducer, initalKeyMapping);
31
- const keydownListener = React.useCallback((assignedKey) => (keydownEvent) => {
32
- const loweredKey = assignedKey.toLowerCase();
33
- if (keydownEvent.repeat)
34
- return;
35
- if (blacklistedTargets.includes(keydownEvent.target.tagName))
36
- return;
37
- if (loweredKey !== keydownEvent.key.toLowerCase())
38
- return;
39
- if (keys[loweredKey] === undefined)
40
- return;
41
- if (overrideSystem) {
42
- keydownEvent.preventDefault();
43
- disabledEventPropagation(keydownEvent);
44
- }
45
- setKeys({ type: 'set-key-down', key: loweredKey });
46
- return false;
47
- }, [keys, overrideSystem]);
48
- const keyupListener = React.useCallback((assignedKey) => (keyupEvent) => {
49
- const raisedKey = assignedKey.toLowerCase();
50
- if (blacklistedTargets.includes(keyupEvent.target.tagName))
51
- return;
52
- if (keyupEvent.key.toLowerCase() !== raisedKey)
53
- return;
54
- if (keys[raisedKey] === undefined)
55
- return;
56
- if (overrideSystem) {
57
- keyupEvent.preventDefault();
58
- disabledEventPropagation(keyupEvent);
59
- }
60
- setKeys({ type: 'set-key-up', key: raisedKey });
61
- return false;
62
- }, [keys, overrideSystem]);
63
- React.useEffect(() => {
64
- //console.log('keys', keys);
65
- if (!Object.values(keys).filter((value) => !value).length) {
66
- callback(keys);
67
- setKeys({ type: 'reset-keys', data: initalKeyMapping });
68
- }
69
- else {
70
- setKeys({ type: '' });
71
- }
72
- }, [callback, keys]);
73
- React.useEffect(() => {
74
- shortcutKeys.forEach((k) => window.addEventListener('keydown', keydownListener(k)));
75
- return () => shortcutKeys.forEach((k) => window.removeEventListener('keydown', keydownListener(k)));
76
- }, []);
77
- React.useEffect(() => {
78
- shortcutKeys.forEach((k) => window.addEventListener('keyup', keyupListener(k)));
79
- return () => shortcutKeys.forEach((k) => window.removeEventListener('keyup', keyupListener(k)));
80
- }, []);
81
- };
82
- export function disabledEventPropagation(e) {
83
- if (e) {
84
- if (e.stopPropagation) {
85
- e.stopPropagation();
86
- }
87
- else if (window.event) {
88
- window.event.cancelBubble = true;
89
- }
90
- }
91
- }
@@ -1,305 +0,0 @@
1
- import Axios from 'axios';
2
- import { saveAs } from 'file-saver';
3
- import { stringify } from 'qs';
4
- export var HttpMethods;
5
- (function (HttpMethods) {
6
- HttpMethods["get"] = "get";
7
- HttpMethods["post"] = "post";
8
- })(HttpMethods || (HttpMethods = {}));
9
- export var FileDownloadStatus;
10
- (function (FileDownloadStatus) {
11
- FileDownloadStatus["downloading"] = "downloading";
12
- FileDownloadStatus["done"] = "done";
13
- FileDownloadStatus["error"] = "error";
14
- })(FileDownloadStatus || (FileDownloadStatus = {}));
15
- class ApiUtilityBase {
16
- accessToken;
17
- handleError = (error, errors) => { };
18
- // private getParams = (params?: any) => {
19
- // if (params) {
20
- // for (const key in params) {
21
- // if (params[key] == null || params[key] === undefined || params[key] === '')
22
- // delete params[key];
23
- // }
24
- // }
25
- // return params;
26
- // };
27
- getResponse = async (endpoint, params, options) => {
28
- return await Axios.get(endpoint, {
29
- params,
30
- paramsSerializer: {
31
- serialize: (p, o) => {
32
- return stringify(params, {
33
- arrayFormat: 'indices',
34
- allowDots: true,
35
- skipNulls: true,
36
- });
37
- },
38
- },
39
- ...this._axiosOptions(options || {}),
40
- });
41
- };
42
- get = async (endpoint, params, throwErrorOn401, options) => {
43
- const response = await this.getResponse(endpoint, params, options);
44
- const data = this.handleResponse(response, throwErrorOn401);
45
- return data;
46
- };
47
- getResult = async (endpoint, params, throwErrorOn401, options) => {
48
- try {
49
- const data = await this.get(endpoint, params, undefined, options);
50
- if (data.status) {
51
- return data.result;
52
- }
53
- else {
54
- this.handleErrorResponse(data.message, data.errors);
55
- }
56
- }
57
- catch (error) {
58
- if (error.isAxiosError)
59
- this.handleAxiosError(error, throwErrorOn401);
60
- else
61
- this.handleResponse(error, throwErrorOn401);
62
- }
63
- return null;
64
- };
65
- post = async (endpoint, body, contentType, options) => {
66
- try {
67
- const response = await Axios.post(endpoint, body, this._axiosOptions({ contentType, ...(options || {}) }));
68
- const data = this.handleResponse(response);
69
- return data;
70
- }
71
- catch (ex) {
72
- if (ex?.isAxiosError) {
73
- return this.handleAxiosError(ex);
74
- }
75
- }
76
- return {};
77
- };
78
- put = async (endpoint, body, contentType, options) => {
79
- try {
80
- const response = await Axios.put(endpoint, body, this._axiosOptions({ contentType, ...(options || {}) }));
81
- const data = this.handleResponse(response);
82
- return data;
83
- }
84
- catch (ex) {
85
- if (ex?.isAxiosError) {
86
- return this.handleAxiosError(ex);
87
- }
88
- }
89
- return {};
90
- };
91
- appendFormDataValues = (form, values, preFix) => {
92
- if (!preFix || preFix.length <= 0)
93
- preFix = '';
94
- //check if given object is a string/number/boolean then add directly to the list with prefix
95
- if ((typeof values !== 'function' && typeof values !== 'object' && typeof values !== 'symbol') || values instanceof File) {
96
- if (values && preFix) {
97
- form.append(preFix, values);
98
- }
99
- return;
100
- }
101
- for (const key in values) {
102
- //prepare a field name
103
- const fieldName = `${preFix}${preFix && !preFix.endsWith('.') ? '.' : ''}${key}`;
104
- if (values[key] instanceof FileList) {
105
- const fileList = values[key];
106
- for (let fIndex = 0; fIndex < fileList.length; fIndex++) {
107
- form.append(`${fieldName}[${fIndex}]`, fileList[fIndex]);
108
- }
109
- }
110
- else {
111
- if (Array.isArray(values[key])) {
112
- values[key].forEach((el, idx) => {
113
- this.appendFormDataValues(form, el, `${fieldName}[${idx}]`);
114
- });
115
- }
116
- else {
117
- if (typeof values[key] === 'object') {
118
- this.appendFormDataValues(form, values[key], fieldName);
119
- }
120
- else if (values[key]) {
121
- form.append(fieldName, values[key]);
122
- }
123
- }
124
- }
125
- }
126
- };
127
- postForm = async (endpoint, params, options) => {
128
- let formData = new FormData();
129
- if (params instanceof FormData) {
130
- formData = params;
131
- }
132
- else {
133
- this.appendFormDataValues(formData, params);
134
- }
135
- try {
136
- const response = await Axios.post(endpoint, formData, this._axiosOptions({ contentType: 'multipart/form-data', ...(options || {}) }));
137
- const data = this.handleResponse(response);
138
- return data;
139
- }
140
- catch (ex) {
141
- if (ex?.isAxiosError) {
142
- return this.handleAxiosError(ex);
143
- }
144
- }
145
- return {};
146
- };
147
- putForm = async (endpoint, params, options) => {
148
- let formData = new FormData();
149
- if (params instanceof FormData) {
150
- formData = params;
151
- }
152
- else {
153
- this.appendFormDataValues(formData, params);
154
- }
155
- try {
156
- const response = await Axios.putForm(endpoint, formData, this._axiosOptions({ contentType: 'multipart/form-data', ...(options || {}) }));
157
- const data = this.handleResponse(response);
158
- return data;
159
- }
160
- catch (ex) {
161
- if (ex?.isAxiosError) {
162
- return this.handleAxiosError(ex);
163
- }
164
- }
165
- return {};
166
- };
167
- delete = async (endpoint, contentType, options) => {
168
- const response = await Axios.delete(endpoint, this._axiosOptions({ contentType, ...(options || {}) }));
169
- const data = this.handleResponse(response);
170
- return data;
171
- };
172
- getFileName = (contentDispositionValue) => {
173
- var filename = undefined;
174
- if (contentDispositionValue && contentDispositionValue.indexOf('attachment') !== -1) {
175
- var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
176
- var matches = filenameRegex.exec(contentDispositionValue);
177
- if (matches != null && matches[1]) {
178
- filename = matches[1].replace(/['"]/g, '');
179
- }
180
- }
181
- return filename;
182
- };
183
- downloadFile = async (endpoint, params, method, options) => {
184
- let response;
185
- const headers = {};
186
- // return authorization header with jwt token
187
- const token = this.accessToken; // || AuthService.getAuthToken();
188
- if (token) {
189
- headers['Authorization'] = `Bearer ${token}`;
190
- }
191
- const axiosOptions = { headers, ...(options || {}) };
192
- if (method === HttpMethods.post) {
193
- response = Axios.post(endpoint, params, {
194
- ...this._axiosOptions(axiosOptions),
195
- responseType: 'blob',
196
- });
197
- }
198
- else {
199
- response = Axios.get(endpoint, {
200
- params,
201
- paramsSerializer: {
202
- serialize: (p, o) => {
203
- return stringify(params, {
204
- arrayFormat: 'indices',
205
- allowDots: true,
206
- skipNulls: true,
207
- });
208
- },
209
- },
210
- ...this._axiosOptions(axiosOptions),
211
- responseType: 'blob',
212
- });
213
- }
214
- try {
215
- const result_1 = await response;
216
- //extract file name from Content-Disposition header
217
- const fileName = this.getFileName(result_1.headers.get('Content-Disposition'));
218
- //invoke 'Save As' dialog
219
- saveAs(result_1.data, fileName);
220
- return { status: FileDownloadStatus.done };
221
- }
222
- catch (error) {
223
- if (error.isAxiosError) {
224
- this.handleResponse(error.response);
225
- }
226
- else
227
- this.handleResponse(error);
228
- if (error.response) {
229
- return {
230
- status: FileDownloadStatus.error,
231
- error: error.response.status,
232
- };
233
- }
234
- else {
235
- return { status: FileDownloadStatus.error, error: error.message };
236
- }
237
- }
238
- };
239
- getAuthHeader = (contentType) => {
240
- const headers = {
241
- 'Content-Type': contentType || 'application/json',
242
- Accept: 'application/json',
243
- };
244
- // return authorization header with jwt token
245
- const token = this.accessToken; //||AuthService.getAuthToken();
246
- if (token) {
247
- headers['Authorization'] = `Bearer ${token}`;
248
- }
249
- return headers;
250
- };
251
- handleResponse = (response, throwErrorOn401) => {
252
- if (!response) {
253
- if (this.handleError)
254
- this.handleError('No response from the server, please try after some time.');
255
- }
256
- else if ([401, 403].indexOf(response.status) !== -1) {
257
- if (throwErrorOn401) {
258
- throw response;
259
- }
260
- else {
261
- console.error('401 Unauthorized or 403 Forbidden response returned from api');
262
- // // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
263
- // AuthService.logout();
264
- // window.location.reload();
265
- }
266
- }
267
- return response?.data;
268
- };
269
- handleAxiosError = (error, throwErrorOn401) => {
270
- if (throwErrorOn401 && error.response?.status === 401)
271
- throw error;
272
- else if (error.response?.status === 400) {
273
- const data = error.response.data;
274
- if (data && data.errors) {
275
- const arr = [];
276
- for (const key in data.errors) {
277
- if (data.errors[key] && data.errors[key].length > 0) {
278
- arr.push(data.errors[key][0]);
279
- }
280
- }
281
- return {
282
- result: null,
283
- status: false,
284
- message: arr.length > 0 ? arr[0] : '',
285
- errors: arr,
286
- };
287
- }
288
- }
289
- return {};
290
- };
291
- handleErrorResponse = (message, errors) => {
292
- if (this.handleError)
293
- this.handleError(message, errors);
294
- };
295
- _axiosOptions = (options) => {
296
- const { contentType, headers, ...rest } = options || {};
297
- return {
298
- headers: headers || this.getAuthHeader(contentType),
299
- baseURL: this.getBaseUrl(),
300
- ...rest,
301
- };
302
- };
303
- getBaseUrl = () => process.env.REACT_APP_API_URL; //EnvUtils.getEnv('REACT_APP_API_URL');
304
- }
305
- export const ApiUtility = new ApiUtilityBase();