@capsitech/react-utilities 0.1.2

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 (44) hide show
  1. package/README.md +3 -0
  2. package/lib/Hooks/index.d.ts +45 -0
  3. package/lib/Hooks/index.js +98 -0
  4. package/lib/Hooks/useInfiniteScroll.d.ts +7 -0
  5. package/lib/Hooks/useInfiniteScroll.js +22 -0
  6. package/lib/Hooks/useNetworkState.d.ts +67 -0
  7. package/lib/Hooks/useNetworkState.js +41 -0
  8. package/lib/Hooks/useShortcuts.d.ts +4 -0
  9. package/lib/Hooks/useShortcuts.js +91 -0
  10. package/lib/Utilities/ApiUtility.axios.d.ts +60 -0
  11. package/lib/Utilities/ApiUtility.axios.js +305 -0
  12. package/lib/Utilities/BrowserInfo.d.ts +74 -0
  13. package/lib/Utilities/BrowserInfo.js +153 -0
  14. package/lib/Utilities/Countries.d.ts +14 -0
  15. package/lib/Utilities/Countries.js +290 -0
  16. package/lib/Utilities/CustomEventEmitter.d.ts +12 -0
  17. package/lib/Utilities/CustomEventEmitter.js +30 -0
  18. package/lib/Utilities/FastCompare.d.ts +1 -0
  19. package/lib/Utilities/FastCompare.js +128 -0
  20. package/lib/Utilities/HideablePromise.d.ts +5 -0
  21. package/lib/Utilities/HideablePromise.js +10 -0
  22. package/lib/Utilities/LoadScripts.d.ts +9 -0
  23. package/lib/Utilities/LoadScripts.js +51 -0
  24. package/lib/Utilities/MTDFraudPrevention.d.ts +28 -0
  25. package/lib/Utilities/MTDFraudPrevention.js +157 -0
  26. package/lib/Utilities/Nationalities.d.ts +5 -0
  27. package/lib/Utilities/Nationalities.js +245 -0
  28. package/lib/Utilities/RouteUtils.d.ts +120 -0
  29. package/lib/Utilities/RouteUtils.js +206 -0
  30. package/lib/Utilities/SuspenseRoute.d.ts +7 -0
  31. package/lib/Utilities/SuspenseRoute.js +10 -0
  32. package/lib/Utilities/TimeZones.d.ts +10 -0
  33. package/lib/Utilities/TimeZones.js +1069 -0
  34. package/lib/Utilities/Types.d.ts +19 -0
  35. package/lib/Utilities/Types.js +1 -0
  36. package/lib/Utilities/Utils.d.ts +174 -0
  37. package/lib/Utilities/Utils.js +331 -0
  38. package/lib/Utilities/dayjs.d.ts +18 -0
  39. package/lib/Utilities/dayjs.js +56 -0
  40. package/lib/Utilities/index.d.ts +15 -0
  41. package/lib/Utilities/index.js +15 -0
  42. package/lib/index.d.ts +2 -0
  43. package/lib/index.js +2 -0
  44. package/package.json +92 -0
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # `Capsitech.ReactUtilities`
2
+
3
+ A set of javascript utility methods
@@ -0,0 +1,45 @@
1
+ import { useEffect } 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 declare const useUpdateEffect: typeof useEffect;
10
+ /**
11
+ * React hook to persist any value between renders,
12
+ * but keeps it up-to-date if it changes.
13
+ *
14
+ * @param value the value or function to persist
15
+ */
16
+ export declare function useLatestRef<T>(value: T): import("react").MutableRefObject<T>;
17
+ /**
18
+ * useCallbackRef hook
19
+ *
20
+ * A custom hook that converts a callback to a ref to avoid triggering re-renders
21
+ * ..when passed as a prop or avoid re-executing effects when passed as a dependency
22
+ *
23
+ * @param callback The callback to write to a ref object
24
+ */
25
+ export declare const useCallbackRef: <T extends (...args: any[]) => any>(callback: T | undefined) => T;
26
+ /**
27
+ * useFirstRenderState hook
28
+ *
29
+ * Returns "true" if component is just mounted (first render), else "false".
30
+ */
31
+ export declare const useFirstRenderState: () => boolean;
32
+ /**
33
+ * React Hook that provides a declarative `setInterval`
34
+ *
35
+ * @param callback the callback to execute at interval
36
+ * @param delay the `setInterval` delay (in ms)
37
+ */
38
+ export declare function useInterval(callback: () => void, delay: number | null): void;
39
+ /**
40
+ * React hook that provides a declarative `setTimeout`
41
+ *
42
+ * @param callback the callback to run after specified delay
43
+ * @param delay the delay (in ms)
44
+ */
45
+ export declare function useTimeout(callback: Function, delay: number | null): void;
@@ -0,0 +1,98 @@
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
+ }
@@ -0,0 +1,7 @@
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 declare const useInfiniteScroll: (scrollRef: React.MutableRefObject<any>, dispatch: any) => void;
@@ -0,0 +1,22 @@
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
+ };
@@ -0,0 +1,67 @@
1
+ export interface INetworkInformation extends EventTarget {
2
+ readonly downlink: number;
3
+ readonly downlinkMax: number;
4
+ readonly effectiveType: 'slow-2g' | '2g' | '3g' | '4g';
5
+ readonly rtt: number;
6
+ readonly saveData: boolean;
7
+ readonly type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';
8
+ onChange: (event: Event) => void;
9
+ }
10
+ export interface IUseNetworkState {
11
+ /**
12
+ * @desc Whether browser connected to the network or not.
13
+ */
14
+ online: boolean | undefined;
15
+ /**
16
+ * @desc Previous value of `online` property. Helps to identify if browser
17
+ * just connected or lost connection.
18
+ */
19
+ previous: boolean | undefined;
20
+ /**
21
+ * @desc The {Date} object pointing to the moment when state change occurred.
22
+ */
23
+ since: Date | undefined;
24
+ /**
25
+ * @desc Effective bandwidth estimate in megabits per second, rounded to the
26
+ * nearest multiple of 25 kilobits per seconds.
27
+ */
28
+ downlink: INetworkInformation['downlink'] | undefined;
29
+ /**
30
+ * @desc Maximum downlink speed, in megabits per second (Mbps), for the
31
+ * underlying connection technology
32
+ */
33
+ downlinkMax: INetworkInformation['downlinkMax'] | undefined;
34
+ /**
35
+ * @desc Effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'.
36
+ * This value is determined using a combination of recently observed round-trip time
37
+ * and downlink values.
38
+ */
39
+ effectiveType: INetworkInformation['effectiveType'] | undefined;
40
+ /**
41
+ * @desc Estimated effective round-trip time of the current connection, rounded
42
+ * to the nearest multiple of 25 milliseconds
43
+ */
44
+ rtt: INetworkInformation['rtt'] | undefined;
45
+ /**
46
+ * @desc {true} if the user has set a reduced data usage option on the user agent.
47
+ */
48
+ saveData: INetworkInformation['saveData'] | undefined;
49
+ /**
50
+ * @desc The type of connection a device is using to communicate with the network.
51
+ * It will be one of the following values:
52
+ * - bluetooth
53
+ * - cellular
54
+ * - ethernet
55
+ * - none
56
+ * - wifi
57
+ * - wimax
58
+ * - other
59
+ * - unknown
60
+ */
61
+ type: INetworkInformation['type'] | undefined;
62
+ }
63
+ export declare const isBrowser: boolean;
64
+ export declare const isNavigator: boolean;
65
+ export type IHookStateInitialSetter<S> = () => S;
66
+ export type IHookStateInitAction<S> = S | IHookStateInitialSetter<S>;
67
+ export declare function useNetworkState(initialState?: IHookStateInitAction<IUseNetworkState>): IUseNetworkState;
@@ -0,0 +1,41 @@
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
+ }
@@ -0,0 +1,4 @@
1
+ export declare const useShortcuts: (shortcutKeys: string[] | string, callback: (keys: string) => void, options?: {
2
+ overrideSystem: boolean;
3
+ }) => void;
4
+ export declare function disabledEventPropagation(e: KeyboardEvent): void;
@@ -0,0 +1,91 @@
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
+ }
@@ -0,0 +1,60 @@
1
+ import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
2
+ export interface IApiResponse<T = any> {
3
+ status: boolean;
4
+ result: T;
5
+ message?: string;
6
+ errors?: {
7
+ number: number;
8
+ message: string;
9
+ suggestion: string;
10
+ exception: any;
11
+ }[];
12
+ }
13
+ export interface IApiListResult<T = any> {
14
+ totalRecords: number;
15
+ items: T[];
16
+ moreRecords?: boolean;
17
+ continuationToken?: string;
18
+ }
19
+ export interface IApiListResultWithTotal<TItem = any, TTotal = any> extends IApiListResult<TItem> {
20
+ total: TTotal;
21
+ }
22
+ export declare enum HttpMethods {
23
+ get = "get",
24
+ post = "post"
25
+ }
26
+ export declare enum FileDownloadStatus {
27
+ downloading = "downloading",
28
+ done = "done",
29
+ error = "error"
30
+ }
31
+ export type DownloadCallback = (status: FileDownloadStatus, error?: any) => void;
32
+ export interface IAxiosRequestConfigWithoutParams extends Omit<AxiosRequestConfig, 'params' | 'paramsSerializer'> {
33
+ contentType?: string;
34
+ }
35
+ declare class ApiUtilityBase {
36
+ accessToken?: string;
37
+ handleError: (error: string, errors?: any) => void;
38
+ getResponse: <T = any>(endpoint: string, params?: any, options?: IAxiosRequestConfigWithoutParams) => Promise<AxiosResponse<T, any>>;
39
+ get: <T = IApiResponse<any>>(endpoint: string, params?: any, throwErrorOn401?: boolean, options?: IAxiosRequestConfigWithoutParams) => Promise<T>;
40
+ getResult: <T = any>(endpoint: string, params?: any, throwErrorOn401?: boolean, options?: IAxiosRequestConfigWithoutParams) => Promise<T | null>;
41
+ post: <T = IApiResponse<any>>(endpoint: string, body: any, contentType?: string, options?: IAxiosRequestConfigWithoutParams) => Promise<T>;
42
+ put: <T = IApiResponse<any>>(endpoint: string, body: any, contentType?: string, options?: IAxiosRequestConfigWithoutParams) => Promise<T>;
43
+ appendFormDataValues: (form: FormData, values: any, preFix?: string) => void;
44
+ postForm: <T = IApiResponse<any>>(endpoint: string, params: any, options?: IAxiosRequestConfigWithoutParams) => Promise<IApiResponse<any> | T>;
45
+ putForm: <T = IApiResponse<any>>(endpoint: string, params: any, options?: IAxiosRequestConfigWithoutParams) => Promise<IApiResponse<any> | T>;
46
+ delete: <T = IApiResponse<any>>(endpoint: string, contentType?: string, options?: IAxiosRequestConfigWithoutParams) => Promise<T>;
47
+ private getFileName;
48
+ downloadFile: (endpoint: string, params?: any, method?: HttpMethods, options?: IAxiosRequestConfigWithoutParams) => Promise<{
49
+ status: FileDownloadStatus;
50
+ error?: any;
51
+ }>;
52
+ getAuthHeader: (contentType?: string) => any;
53
+ handleResponse: <T = IApiResponse<any>>(response: AxiosResponse<T, any>, throwErrorOn401?: boolean) => T;
54
+ handleAxiosError: <T = IApiResponse<any>>(error: AxiosError, throwErrorOn401?: boolean) => T;
55
+ handleErrorResponse: (message: any, errors?: any) => void;
56
+ _axiosOptions: (options?: IAxiosRequestConfigWithoutParams) => AxiosRequestConfig;
57
+ getBaseUrl: () => string | undefined;
58
+ }
59
+ export declare const ApiUtility: ApiUtilityBase;
60
+ export {};