@campxdev/campx-web-utils 0.1.17 → 0.1.19

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/.prettierrc ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "bracketSpacing": true,
3
+ "singleQuote": true,
4
+ "trailingComma": "all",
5
+ "useTabs": false,
6
+ "bracketSameLine": false
7
+ }
package/craco.config.js CHANGED
@@ -1,18 +1,14 @@
1
- const path = require("path");
2
- const { getLoader, loaderByName } = require("@craco/craco");
1
+ const path = require('path');
2
+ const { getLoader, loaderByName } = require('@craco/craco');
3
3
  const packages = [];
4
- packages.push(path.dirname(require.resolve("@campxdev/react-blueprint")));
4
+ packages.push(path.dirname(require.resolve('@campxdev/react-blueprint')));
5
+ packages.push(path.dirname(require.resolve('@campxdev/campx-web-utils')));
5
6
  module.exports = {
6
7
  webpack: {
7
8
  configure: (webpackConfig) => {
8
- const { isFound, match } = getLoader(
9
- webpackConfig,
10
- loaderByName("babel-loader")
11
- );
9
+ const { isFound, match } = getLoader(webpackConfig, loaderByName('babel-loader'));
12
10
  if (isFound) {
13
- const include = Array.isArray(match.loader.include)
14
- ? match.loader.include
15
- : [match.loader.include];
11
+ const include = Array.isArray(match.loader.include) ? match.loader.include : [match.loader.include];
16
12
  match.loader.include = include.concat(packages);
17
13
  }
18
14
 
package/exports.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./src/config/axios";
2
2
  export * from "./src/context/export";
3
+ export * from "./src/hooks/export";
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@campxdev/campx-web-utils",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "main": "./exports.ts",
5
5
  "private": false,
6
6
  "dependencies": {
7
- "@campxdev/react-blueprint": "^1.1.6",
7
+ "@campxdev/react-blueprint": "1.1.8",
8
8
  "@hookform/resolvers": "^3.9.0",
9
9
  "@mui/x-date-pickers": "^7.12.1",
10
10
  "@testing-library/jest-dom": "^5.14.1",
@@ -1,37 +1,26 @@
1
- import { useQuery } from "react-query";
2
- import { axios } from "./config/axios";
3
-
4
- const fetchClubRequests = () => {
5
- return axios
6
- .get(`/hrms/departments`, {
7
- headers: {
8
- "x-tenant-id": "aupulse",
9
- "X-Institution-Code": "aupulse",
10
- campx_session_key: "66a36c752e28b1200876b034",
11
- },
12
- })
13
- .then((res) => res.data);
14
- };
1
+ import { Button } from '@campxdev/react-blueprint';
2
+ import useConfirm from './hooks/useConfirm';
15
3
 
16
4
  function AppContent() {
17
- const {
18
- data: requests,
19
- isLoading,
20
- error,
21
- refetch,
22
- } = useQuery("club-requests", () => fetchClubRequests());
5
+ const isConfirm = useConfirm();
23
6
 
24
- if (isLoading) {
25
- return <div>Loading...</div>;
26
- }
7
+ const handleConfirm = async () => {
8
+ const confirm = await isConfirm({
9
+ type: 'delete',
10
+ title: 'Are you sure?',
11
+ message: 'Please confirm before submission to action description',
12
+ });
27
13
 
28
- // if (error) {
29
- // // No need to handle the error locally, it will be caught by ErrorBoundary
30
- // console.error("Error fetching club requests:", error);
31
- // throw error; // Re-throw the error to be caught by the ErrorBoundary
32
- // }
14
+ // If user cancel the action
15
+ if (!confirm) {
16
+ console.log('User cancelled the action');
17
+ return;
18
+ }
19
+ // If user confirm the action
20
+ console.log('User confirmed the action');
21
+ };
33
22
 
34
- return <></>;
23
+ return <Button onClick={handleConfirm}>Confirm</Button>;
35
24
  }
36
25
 
37
26
  export default AppContent;
@@ -1,21 +1,21 @@
1
- import Axios, { InternalAxiosRequestConfig } from "axios";
2
- import Cookies from "js-cookie";
3
- import { SnackbarStore } from "../context/SnackbarProvider";
1
+ import Axios, { InternalAxiosRequestConfig } from 'axios';
2
+ import Cookies from 'js-cookie';
3
+ import { ApplicationStore } from '../context/application-store';
4
4
 
5
- const isDevelopment = process.env.NODE_ENV == "development";
5
+ const isDevelopment = process.env.NODE_ENV == 'development';
6
6
 
7
7
  const tenantCode =
8
- window.location.hostname === "localhost"
9
- ? Cookies.get("campx_tenant")
10
- : window.location.hostname.split(".")[0];
11
- const institutionCode = window.location.pathname.split("/")[1];
8
+ window.location.hostname === 'localhost'
9
+ ? Cookies.get('campx_tenant')
10
+ : window.location.hostname.split('.')[0];
11
+ const institutionCode = window.location.pathname.split('/')[1];
12
12
 
13
13
  export const formatParams = (params: any) => {
14
14
  return Object.fromEntries(
15
15
  Object.entries(params ?? {})?.map((i) => [
16
16
  i[0],
17
- i[1] === "__empty__" ? "" : i[1],
18
- ])
17
+ i[1] === '__empty__' ? '' : i[1],
18
+ ]),
19
19
  );
20
20
  };
21
21
 
@@ -23,8 +23,8 @@ export const axios = Axios.create({
23
23
  baseURL: process.env.REACT_APP_API_HOST,
24
24
  withCredentials: true,
25
25
  headers: {
26
- "x-tenant-id": tenantCode,
27
- "x-institution-code": institutionCode,
26
+ 'x-tenant-id': tenantCode,
27
+ 'x-institution-code': institutionCode,
28
28
  },
29
29
  });
30
30
 
@@ -32,15 +32,15 @@ axios.interceptors.request.use(
32
32
  function (config: InternalAxiosRequestConfig) {
33
33
  const params = formatParams(config?.params);
34
34
 
35
- const sessionKey = Cookies.get("campx_session_key");
36
- const openPaymentsKey = Cookies.get("campx_open_payments_key");
35
+ const sessionKey = Cookies.get('campx_session_key');
36
+ const openPaymentsKey = Cookies.get('campx_open_payments_key');
37
37
 
38
38
  if (isDevelopment && sessionKey) {
39
- config.headers.set("campx_session_key", sessionKey);
39
+ config.headers.set('campx_session_key', sessionKey);
40
40
  }
41
41
 
42
42
  if (openPaymentsKey) {
43
- config.headers.set("campx_open_payments_key", openPaymentsKey);
43
+ config.headers.set('campx_open_payments_key', openPaymentsKey);
44
44
  }
45
45
 
46
46
  return {
@@ -50,7 +50,7 @@ axios.interceptors.request.use(
50
50
  },
51
51
  function (error) {
52
52
  return Promise.reject(error);
53
- }
53
+ },
54
54
  );
55
55
 
56
56
  axios.interceptors.response.use(
@@ -58,13 +58,13 @@ axios.interceptors.response.use(
58
58
  console.log(response);
59
59
  if (
60
60
  response.config.method &&
61
- ["put", "post", "delete", "patch"].includes(response.config.method) &&
61
+ ['put', 'post', 'delete', 'patch'].includes(response.config.method) &&
62
62
  [200, 201, 202].includes(response.status)
63
63
  ) {
64
- SnackbarStore.update((s) => {
65
- s.open = true;
66
- s.message = response.data.message;
67
- s.severity = "success";
64
+ ApplicationStore.update((s) => {
65
+ s.snackbar.open = true;
66
+ s.snackbar.message = response.data.message;
67
+ s.snackbar.severity = 'success';
68
68
  });
69
69
  }
70
70
 
@@ -72,24 +72,24 @@ axios.interceptors.response.use(
72
72
  },
73
73
  function (err) {
74
74
  if ([400, 422].includes(err.response.status)) {
75
- SnackbarStore.update((s) => {
76
- s.open = true;
77
- s.message = err.response.data.message || "Bad Request";
78
- s.severity = "error";
75
+ ApplicationStore.update((s) => {
76
+ s.snackbar.open = true;
77
+ s.snackbar.message = err.response.data.message || 'Bad Request';
78
+ s.snackbar.severity = 'error';
79
79
  });
80
80
  }
81
81
  if (
82
82
  err.response.config.method &&
83
- ["put", "post", "delete", "patch"].includes(err.response.config.method) &&
83
+ ['put', 'post', 'delete', 'patch'].includes(err.response.config.method) &&
84
84
  [404].includes(err.response.status)
85
85
  ) {
86
- SnackbarStore.update((s) => {
87
- s.open = true;
88
- s.message = err.response.data.message;
89
- s.severity = "error";
86
+ ApplicationStore.update((s) => {
87
+ s.snackbar.open = true;
88
+ s.snackbar.message = err.response.data.message;
89
+ s.snackbar.severity = 'error';
90
90
  });
91
91
  }
92
92
 
93
93
  return Promise.reject(err);
94
- }
94
+ },
95
95
  );
@@ -0,0 +1,70 @@
1
+ import { ConfirmDialog, ConfirmDialogType } from '@campxdev/react-blueprint';
2
+ import { createContext, ReactNode } from 'react';
3
+ import { ApplicationStore } from './application-store';
4
+
5
+ interface ConfirmStateProps {
6
+ showConfirmDialog: (
7
+ title: string,
8
+ message: string,
9
+ onConfirm: () => void,
10
+ onCancel: () => void,
11
+ type?: ConfirmDialogType,
12
+ ) => void;
13
+ }
14
+
15
+ const ConfirmContext = createContext<ConfirmStateProps>({
16
+ showConfirmDialog: () => {},
17
+ });
18
+
19
+ export const ConfirmDialogProvider = ({
20
+ children,
21
+ }: {
22
+ children: ReactNode;
23
+ }) => {
24
+ const confirmDialog = ApplicationStore.useState((s) => s.confirmDialog);
25
+
26
+ const showConfirmDialog = (
27
+ title: string,
28
+ message: string,
29
+ onConfirm: () => void,
30
+ onCancel: () => void,
31
+ type: ConfirmDialogType = 'confirm',
32
+ ) => {
33
+ ApplicationStore.update((s) => {
34
+ s.confirmDialog = {
35
+ isOpen: true,
36
+ title,
37
+ message,
38
+ onConfirm,
39
+ onCancel,
40
+ type,
41
+ };
42
+ });
43
+ };
44
+
45
+ const handleCloseDialog = () => {
46
+ ApplicationStore.update((s) => {
47
+ s.confirmDialog.isOpen = false;
48
+ });
49
+ };
50
+
51
+ return (
52
+ <ConfirmContext.Provider value={{ showConfirmDialog }}>
53
+ {children}
54
+ <ConfirmDialog
55
+ isOpen={confirmDialog.isOpen}
56
+ title={confirmDialog.title}
57
+ message={confirmDialog.message}
58
+ type={confirmDialog.type}
59
+ onConfirm={() => {
60
+ confirmDialog.onConfirm();
61
+ handleCloseDialog();
62
+ }}
63
+ onCancel={() => {
64
+ confirmDialog.onCancel();
65
+ handleCloseDialog();
66
+ }}
67
+ />
68
+ </ConfirmContext.Provider>
69
+ );
70
+ };
@@ -1,22 +1,13 @@
1
- import { lightTheme, MuiThemeProvider } from "@campxdev/react-blueprint";
2
- import { LocalizationProvider } from "@mui/x-date-pickers";
3
- import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFnsV3";
4
- import Cookies from "js-cookie";
5
- import { ReactNode, useEffect } from "react";
6
- import { QueryClient, QueryClientProvider } from "react-query";
7
- import { BrowserRouter } from "react-router-dom";
8
- import { ErrorBoundary } from "./export";
9
- import { SnackbarProvider } from "./SnackbarProvider";
1
+ import { lightTheme, MuiThemeProvider } from '@campxdev/react-blueprint';
2
+ import Cookies from 'js-cookie';
3
+ import { ReactNode, useEffect } from 'react';
4
+ import { QueryClient, QueryClientProvider } from 'react-query';
5
+ import { BrowserRouter } from 'react-router-dom';
6
+ import { ConfirmDialogProvider } from './ConfirmDialogProvider';
7
+ import { ErrorBoundary } from './export';
8
+ import { SnackbarProvider } from './SnackbarProvider';
10
9
 
11
- export const Providers = ({
12
- children,
13
- basename,
14
- theme = lightTheme,
15
- }: {
16
- children: ReactNode;
17
- basename?: string;
18
- theme?: any;
19
- }) => {
10
+ export const Providers = ({ children, basename, theme = lightTheme }: { children: ReactNode; basename?: string; theme?: any }) => {
20
11
  const queryClient = new QueryClient({
21
12
  defaultOptions: {
22
13
  queries: {
@@ -27,17 +18,12 @@ export const Providers = ({
27
18
  },
28
19
  });
29
20
 
30
- var tenantCode =
31
- window.location.hostname === "localhost"
32
- ? Cookies.get("campx_tenant")
33
- : window.location.hostname.split(".")[0];
21
+ var tenantCode = window.location.hostname === 'localhost' ? Cookies.get('campx_tenant') : window.location.hostname.split('.')[0];
34
22
  var institutionCode =
35
- window.location.pathname.split("/")[1] !== ""
36
- ? window.location.pathname.split("/")[1]
37
- : Cookies.get("campx_institution");
38
- var baseName = tenantCode && institutionCode ? `/${institutionCode}` : "/";
23
+ window.location.pathname.split('/')[1] !== '' ? window.location.pathname.split('/')[1] : Cookies.get('campx_institution');
24
+ var baseName = tenantCode && institutionCode ? `/${institutionCode}` : '/';
39
25
  useEffect(() => {
40
- if (window.location.pathname === "/" && institutionCode && tenantCode) {
26
+ if (window.location.pathname === '/' && institutionCode && tenantCode) {
41
27
  window.location.replace(window.location.origin + `/${institutionCode}`);
42
28
  }
43
29
  }, []);
@@ -47,9 +33,9 @@ export const Providers = ({
47
33
  <QueryClientProvider client={queryClient}>
48
34
  <MuiThemeProvider theme={theme}>
49
35
  <SnackbarProvider>
50
- <LocalizationProvider dateAdapter={AdapterDateFns}>
36
+ <ConfirmDialogProvider>
51
37
  <ErrorBoundary>{children}</ErrorBoundary>
52
- </LocalizationProvider>
38
+ </ConfirmDialogProvider>
53
39
  </SnackbarProvider>
54
40
  </MuiThemeProvider>
55
41
  </QueryClientProvider>
@@ -1,31 +1,26 @@
1
- import { Severity, Snackbar } from "@campxdev/react-blueprint";
2
- import { Store } from "pullstate";
3
- import { createContext, ReactNode } from "react";
1
+ import { Severity, Snackbar } from '@campxdev/react-blueprint';
2
+ import { createContext, ReactNode } from 'react';
3
+ import { ApplicationStore } from './application-store';
4
4
 
5
5
  interface SnackbarContextProps {
6
6
  showSnackbar: (message: string, severity?: Severity) => void;
7
7
  }
8
8
 
9
9
  const SnackbarContext = createContext<SnackbarContextProps | undefined>(
10
- undefined
10
+ undefined,
11
11
  );
12
12
 
13
13
  interface SnackbarProviderProps {
14
14
  children: ReactNode;
15
15
  }
16
- export const SnackbarStore = new Store({
17
- open: false,
18
- message: "",
19
- severity: "success" as Severity,
20
- });
21
16
 
22
17
  export const SnackbarProvider = ({ children }: SnackbarProviderProps) => {
23
- const snackbar = SnackbarStore.useState((s) => s);
24
- const showSnackbar = (message: string, severity: Severity = "info") => {
25
- SnackbarStore.update((s) => {
26
- s.open = true;
27
- s.message = message;
28
- s.severity = severity;
18
+ const snackbar = ApplicationStore.useState((s) => s.snackbar);
19
+ const showSnackbar = (message: string, severity: Severity = 'info') => {
20
+ ApplicationStore.update((s) => {
21
+ s.snackbar.open = true;
22
+ s.snackbar.message = message;
23
+ s.snackbar.severity = severity;
29
24
  });
30
25
  };
31
26
  return (
@@ -37,8 +32,8 @@ export const SnackbarProvider = ({ children }: SnackbarProviderProps) => {
37
32
  severity={snackbar.severity}
38
33
  autoHideDuration={1500}
39
34
  onClose={() => {
40
- SnackbarStore.update((s) => {
41
- s.open = false;
35
+ ApplicationStore.update((s) => {
36
+ s.snackbar.open = false;
42
37
  });
43
38
  }}
44
39
  />
@@ -1,12 +1,39 @@
1
- import { Store } from "pullstate";
1
+ import { ConfirmDialogType, Severity } from '@campxdev/react-blueprint';
2
+ import { Store } from 'pullstate';
2
3
 
3
4
  export type ApplicationStoreType = {
4
5
  isLoginDialogOpen: boolean;
6
+ snackbar: {
7
+ open: boolean;
8
+ message: string;
9
+ severity: Severity;
10
+ };
11
+ confirmDialog: {
12
+ isOpen: boolean;
13
+ title: string;
14
+ message: string;
15
+ onConfirm: () => void;
16
+ onCancel: () => void;
17
+ type: ConfirmDialogType;
18
+ };
5
19
  };
6
20
 
7
21
  export const initialApplicationState: ApplicationStoreType = {
8
22
  isLoginDialogOpen: false,
23
+ snackbar: {
24
+ open: false,
25
+ message: '',
26
+ severity: 'success',
27
+ },
28
+ confirmDialog: {
29
+ isOpen: false,
30
+ title: '',
31
+ message: '',
32
+ onConfirm: () => {},
33
+ onCancel: () => {},
34
+ type: 'confirm',
35
+ },
9
36
  };
10
37
  export const ApplicationStore = new Store<ApplicationStoreType>(
11
- initialApplicationState
38
+ initialApplicationState,
12
39
  );
@@ -1,4 +1,4 @@
1
- export * from "./application-store";
2
- export * from "./ErrorBoundary/ErrorBoundary";
3
- export * from "./Providers";
4
- export * from "./SnackbarProvider";
1
+ export * from './application-store';
2
+ export * from './ErrorBoundary/ErrorBoundary';
3
+ export * from './Providers';
4
+ export * from './SnackbarProvider';
@@ -0,0 +1 @@
1
+ export * from "./useConfirm";
@@ -0,0 +1,51 @@
1
+ import { ConfirmDialogType } from '@campxdev/react-blueprint';
2
+ import { ApplicationStore } from '../context/application-store';
3
+
4
+ const defaultConfirmDialogState = {
5
+ isOpen: false,
6
+ title: '',
7
+ message: '',
8
+ type: 'confirm' as ConfirmDialogType,
9
+ onConfirm: () => {},
10
+ onCancel: () => {},
11
+ };
12
+
13
+ const useConfirm = () => {
14
+ const isConfirmed = ({
15
+ title,
16
+ message,
17
+ type = 'confirm',
18
+ }: {
19
+ title: string;
20
+ message: string;
21
+ type?: ConfirmDialogType;
22
+ }): Promise<boolean> =>
23
+ new Promise((resolve) => {
24
+ ApplicationStore.update((s) => {
25
+ s.confirmDialog = {
26
+ isOpen: true,
27
+ title,
28
+ message,
29
+ type,
30
+ onConfirm: () => {
31
+ resolve(true);
32
+ resetDialog();
33
+ },
34
+ onCancel: () => {
35
+ resolve(false);
36
+ resetDialog();
37
+ },
38
+ };
39
+ });
40
+ });
41
+
42
+ const resetDialog = () => {
43
+ ApplicationStore.update((s) => {
44
+ s.confirmDialog = defaultConfirmDialogState;
45
+ });
46
+ };
47
+
48
+ return isConfirmed;
49
+ };
50
+
51
+ export default useConfirm;
package/tsconfig.json CHANGED
@@ -1,11 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "target": "es5",
4
- "lib": [
5
- "dom",
6
- "dom.iterable",
7
- "esnext"
8
- ],
4
+ "lib": ["dom", "dom.iterable", "esnext"],
9
5
  "allowJs": true,
10
6
  "skipLibCheck": true,
11
7
  "esModuleInterop": true,
@@ -18,13 +14,9 @@
18
14
  "resolveJsonModule": true,
19
15
  "isolatedModules": true,
20
16
  "noEmit": true,
21
- "jsx": "react-jsx"
17
+ "jsx": "react-jsx",
18
+ "types": ["node"]
22
19
  },
23
- "include": [
24
- "src",
25
- "./types"
26
- ],
27
- "exclude": [
28
- "node_modules"
29
- ]
20
+ "include": ["src", "./types"],
21
+ "exclude": ["node_modules", ".yalc"]
30
22
  }