@@ -374,4 +390,4 @@ const History = (props: Props)=> {
);
};
-export default History;
\ No newline at end of file
+export default History;
diff --git a/src/client/components/workspace/HistoryContainer.tsx b/src/client/components/workspace/HistoryContainer.tsx
index 87c2edf97..6fe7e68b5 100644
--- a/src/client/components/workspace/HistoryContainer.tsx
+++ b/src/client/components/workspace/HistoryContainer.tsx
@@ -1,129 +1,92 @@
import React from 'react';
-import { connect, useSelector } from 'react-redux';
-
-import * as HistorySlice from '../../toolkit-refactor/slices/historySlice';
-import { fieldsReplaced } from '../../toolkit-refactor/slices/newRequestFieldsSlice';
+import { type ReqRes } from '~/types';
+import { useAppSelector, useAppDispatch } from '../../rtk/store';
+import * as HistorySlice from '../../rtk/slices/historySlice';
+import { fieldsReplaced } from '../../rtk/slices/newRequestFieldsSlice';
import {
newRequestCookiesSet,
newRequestStreamsSet,
newRequestBodySet,
newRequestHeadersSet,
-} from '../../toolkit-refactor/slices/newRequestSlice';
+} from '../../rtk/slices/newRequestSlice';
import HistoryDate from './HistoryDate';
import ClearHistoryBtn from './buttons/ClearHistoryBtn';
-import { Dispatch } from 'redux';
-
-import { $TSFixMe,
- ReqRes,
- NewRequestBody,
- CookieOrHeader,
- NewRequestStreams,
- NewRequestFields } from '../../../types'
-
-import { RootState } from '../../toolkit-refactor/store';
-
-interface NewRequestCookiesSet {
- cookiesArr: CookieOrHeader[];
- count: number;
-}
-
-interface NewRequestHeadersSet {
- headersArr: CookieOrHeader[];
- count: number;
-};;
-
-interface Props {
- history: [],
- historyCleared: () => void,
- historyDeleted: string,
- fieldsReplaced: (obj: {}) => void,
- newRequestHeadersSet: (obj: NewRequestHeadersSet) => void,
- newRequestCookiesSet: (obj: NewRequestCookiesSet) => void,
- newRequestBodySet: (obj: NewRequestBody) => void,
- newRequestStreamsSet: NewRequestStreams,
- className: string
-};
-/**@todo switch to hooks? */
-const mapStateToProps = (store: RootState) => ({
- history: store.history,
- newRequestFields: store.newRequestFields,
- newRequestStreams: store.newRequest.newRequestStreams,
-});
-
-/**@todo switch to hooks? */
-const mapDispatchToProps = (dispatch: Dispatch) => ({
- historyCleared: () => {
- dispatch(HistorySlice.historyCleared());
- },
- historyDeleted: (reqRes: ReqRes) => {
- dispatch(HistorySlice.historyDeleted(reqRes));
- },
- newRequestHeadersSet: (requestHeadersObj: $TSFixMe) => {
- dispatch(newRequestHeadersSet(requestHeadersObj));
- },
- fieldsReplaced: (requestFields: $TSFixMe) => {
- dispatch(fieldsReplaced(requestFields));
- },
- newRequestBodySet: (requestBodyObj: $TSFixMe) => {
- dispatch(newRequestBodySet(requestBodyObj));
- },
- newRequestCookiesSet: (requestCookiesObj: $TSFixMe) => {
- dispatch(newRequestCookiesSet(requestCookiesObj));
- },
- newRequestStreamsSet: (requestStreamsObj: $TSFixMe) => {
- dispatch(newRequestStreamsSet(requestStreamsObj));
- },
-});
-
-const HistoryContainer = (props: Props) => {
- const {
- history,
- historyCleared,
- historyDeleted,
- fieldsReplaced,
- newRequestHeadersSet,
- newRequestCookiesSet,
- newRequestBodySet,
- newRequestStreamsSet,
- } = props;
-
- const isDark = useSelector((store: { ui: { isDark: boolean } }) => store.ui.isDark);
-
- // history is already sorted by created_at from getHistory
- const historyDates = history.map((date: Date, index: number): JSX.Element => (
-
- ));
+const HistoryContainer = () => {
+ const history = useAppSelector((store) => store.history);
+ const newFields = useAppSelector((store) => store.newRequestFields);
+ const isDark = useAppSelector((store) => store.ui.isDark);
+ const dispatch = useAppDispatch();
return (
-
+ {
+ dispatch(HistorySlice.historyCleared());
+ }}
+ />
- {historyDates}
+
+
+ {history.map((item, i) => (
+ /**
+ * Previous comment: History is already sorted by created_at from
+ * getHistory.
+ *
+ * ---
+ *
+ * @todo 2023-08-31 - This is almost certainly a bad component design,
+ * but no time to redesign it.
+ *
+ * HistoryDate can call useAppDispatch, and then wire up any callbacks
+ * it needs itself. On the flipside of lifting state up, you should
+ * also "tamp" state down as far down as you can, to avoid needless
+ * re-renders and make sure any useEffect calls in downstream
+ * components don't run way more than intended
+ */
+ {
+ dispatch(HistorySlice.historyCleared());
+ }}
+ historyDeleted={(r: ReqRes) => {
+ dispatch(HistorySlice.historyDeleted(r));
+ }}
+ fieldsReplaced={(requestFields) => {
+ dispatch(fieldsReplaced(requestFields));
+ }}
+ newRequestHeadersSet={(requestHeadersObj) => {
+ dispatch(newRequestHeadersSet(requestHeadersObj));
+ }}
+ newRequestCookiesSet={(requestCookiesObj) => {
+ dispatch(newRequestCookiesSet(requestCookiesObj));
+ }}
+ newRequestBodySet={(requestBodyObj) => {
+ dispatch(newRequestBodySet(requestBodyObj));
+ }}
+ newRequestStreamsSet={(stream) => {
+ dispatch(newRequestStreamsSet(stream));
+ }}
+ />
+ ))}
+
);
};
-export default connect(mapStateToProps, mapDispatchToProps)(HistoryContainer);
\ No newline at end of file
+export default HistoryContainer;
diff --git a/src/client/components/workspace/HistoryDate.tsx b/src/client/components/workspace/HistoryDate.tsx
index 5c41b367b..fde17e7df 100644
--- a/src/client/components/workspace/HistoryDate.tsx
+++ b/src/client/components/workspace/HistoryDate.tsx
@@ -1,34 +1,42 @@
-import React, { Component } from 'react';
+import React from 'react';
import { isYesterday, isToday, parseISO, parse, format } from 'date-fns';
-import History from './History.tsx';
+import History from './History';
import {
- NewRequestBody,
- CookieOrHeader,
- NewRequestStreams,
+ NewRequestStreams,
NewRequestFields,
NewRequestBodySet,
NewRequestHeadersSet,
NewRequestCookiesSet,
- FieldsReplaced
-} from '../../../types'
-
+ ReqRes,
+} from '~/types';
+import { type HistoryItem } from '../../rtk/slices/historySlice';
interface Props {
- history: object[],
- historyCleared: () => void,
- historyDeleted: string,
- fieldsReplaced: FieldsReplaced,
- newRequestHeadersSet: NewRequestHeadersSet,
- newRequestCookiesSet: NewRequestCookiesSet,
- newRequestBodySet: NewRequestBodySet,
- newRequestStreamsSet: NewRequestStreams,
- newRequestFields: NewRequestFields,
- className: string,
- content: {
- date: Date
- },
-};
+ history: HistoryItem[];
+ historyCleared: () => void;
+ historyDeleted: (reqRes: ReqRes) => void;
+ fieldsReplaced: (newField: NewRequestFields) => void;
+ newRequestHeadersSet: NewRequestHeadersSet;
+ newRequestCookiesSet: NewRequestCookiesSet;
+ newRequestBodySet: NewRequestBodySet;
+ newRequestStreamsSet: (newStream: NewRequestStreams) => void;
+ newRequestFields: NewRequestFields;
+ className: string;
+ content: HistoryItem;
+}
+
+function calculateDateString(item: HistoryItem): string {
+ const date = parse(item.date, 'MM/dd/yyyy', new Date());
+
+ if (isToday(date)) {
+ return 'Today';
+ } else if (isYesterday(date)) {
+ return 'Yesterday';
+ } else {
+ return format(date, 'MMM d, yyyy');
+ }
+}
export default function HistoryDate(props: Props) {
const {
@@ -40,49 +48,32 @@ export default function HistoryDate(props: Props) {
newRequestBodySet,
newRequestStreamsSet,
newRequestFields,
- content
+ content,
} = props;
- function focusOnForm(event: any) {
- const composerUrlField: any = document.querySelector('.composer_url_input');
- composerUrlField.focus();
- }
-
- const current: any = history.find(
- (a: any) => a.date === content.date
- );
- let date: any = parse(current.date, 'MM/dd/yyyy', new Date());
- // let date = parseISO(current.date)
- if (isToday(date)) {
- date = 'Today';
- } // If the date matches todays date render the word "Today"
- else if (isYesterday(date)) {
- date = 'Yesterday';
- } else {
- date = format(date, 'MMM d, yyyy');
- }
-
- const histArray = current.history.map((history: [], i: number) => {
- return (
-
- );
- });
+ const current = history.find((a) => a.date === content.date);
+ const date = current !== undefined ? calculateDateString(current) : null;
return (
{date}
- {histArray}
+
+ {current?.history.map((history, i) => {
+ return (
+
+ );
+ })}
);
diff --git a/src/client/components/workspace/HistoryOrWorkspaceContainer.tsx b/src/client/components/workspace/HistoryOrWorkspaceContainer.tsx
index e9c6d1429..7625fc4ec 100644
--- a/src/client/components/workspace/HistoryOrWorkspaceContainer.tsx
+++ b/src/client/components/workspace/HistoryOrWorkspaceContainer.tsx
@@ -1,31 +1,39 @@
-import * as React from 'react';
-import { useSelector } from 'react-redux';
+import React, { useState } from 'react';
+
// Import local components
import WorkspaceContainer from './WorkspaceContainer';
import HistoryContainer from './HistoryContainer';
+
// Import MUI components and icons
-import { Box, Tabs, Tab, Button } from '@mui/material';
+import { Box, Tabs, Tab } from '@mui/material';
import { AccessTime, Work } from '@mui/icons-material';
-import { WorkspaceContainerProps } from '../../../types';
+import { type $NotUsed, type WorkspaceContainerProps } from '~/types';
-interface TabPanelProps {
+/**
+ * Not sure if this is overkill, but the previous implementation had support for
+ * passing in extra props for the div. Went ahead and typed it super-precisely
+ */
+type TabPanelProps = Omit
, 'children'> & {
children?: React.ReactNode;
index: number;
- value: number;
-}
-
-function TabPanel(props: TabPanelProps) {
- const { children, value, index, ...other } = props;
+ activeIndex: number;
+};
+function TabPanel({
+ children,
+ activeIndex,
+ index,
+ ...delegatedProps
+}: TabPanelProps) {
return (
- {value === index && (
+ {activeIndex === index && (
{children}
@@ -38,16 +46,19 @@ function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
- };
+ } as const;
}
export default function HistoryOrWorkspaceContainer(
props: WorkspaceContainerProps
) {
- const [value, setValue] = React.useState(0);
+ const [activeTabIndex, setActiveTabIndex] = useState(0);
- const handleChange = (event: React.SyntheticEvent, newValue: number) => {
- setValue(newValue);
+ // According to MUI, the second argument will default to type number when
+ // possible; skeeves me out that they don't support type parameters for this,
+ // and you have to cast newValue from "any" to "number" yourself
+ const onMuiTabIndexChange = (_: $NotUsed, newValue: number) => {
+ setActiveTabIndex(newValue);
};
return (
@@ -60,8 +71,8 @@ export default function HistoryOrWorkspaceContainer(
>
+
}
{...a11yProps(1)}
@@ -84,11 +96,13 @@ export default function HistoryOrWorkspaceContainer(
/>
-
+
+
-
-
+
+
+
);
diff --git a/src/client/components/workspace/WorkspaceCollectionElement.jsx b/src/client/components/workspace/WorkspaceCollectionElement.jsx
index f70e145e8..e896c6256 100644
--- a/src/client/components/workspace/WorkspaceCollectionElement.jsx
+++ b/src/client/components/workspace/WorkspaceCollectionElement.jsx
@@ -1,31 +1,33 @@
/** Also not legacy */
import React, { useState } from 'react';
-import { useSelector } from 'react-redux';
-import connectionController from '../../controllers/reqResController';
-import webrtcPeerController from '../../controllers/webrtcPeerController';
-import { responseDataSaved } from '../../toolkit-refactor/slices/reqResSlice';
-// import { fieldsReplaced } from '../../toolkit-refactor/slices/newRequestFieldsSlice';
+import { useAppSelector, useAppDispatch } from '../../rtk/store';
+import { responseDataSaved } from '../../rtk/slices/reqResSlice';
+// import { fieldsReplaced } from '~/toolkit/slices/newRequestFieldsSlice';
+import {
+ setResponsePaneActiveTab,
+ setSidebarActiveTab,
+} from '../../rtk/slices/uiSlice';
// import {
// newRequestSSESet,
// newRequestCookiesSet,
// newRequestStreamsSet,
// newRequestBodySet,
// newRequestHeadersSet,
-// } from '../../toolkit-refactor/slices/newRequestSlice';
-import {
- setResponsePaneActiveTab,
- setSidebarActiveTab,
-} from '../../toolkit-refactor/slices/uiSlice';
+// } from '~/toolkit/slices/newRequestSlice';
+
+import connectionController from '~/controllers/reqResController';
+import webrtcPeerController from '~/controllers/webrtcPeerController';
-import { useAppDispatch } from '../../toolkit-refactor/store';
const WorkspaceCollectionElement = (props) => {
const [webRTCSend, setWebRTCSend] = useState(false);
const [showDetails, setShowDetails] = useState(false);
const dispatch = useAppDispatch();
- const currentResponse = useSelector((store) => store.reqRes.currentResponse);
+ const currentResponse = useAppSelector(
+ (store) => store.reqRes.currentResponse
+ );
const {
content,
@@ -65,7 +67,10 @@ const WorkspaceCollectionElement = (props) => {
>
{network === 'webrtc' ? 'WebRTC' : request.method}
-
+
{url ? url : request.webRTCDataChannel + ' Channel'}
@@ -191,7 +196,7 @@ const WorkspaceCollectionElement = (props) => {
)}
{/* VIEW RESPONSE BUTTON */}
- {(connection !== 'uninitialized') && (
+ {connection !== 'uninitialized' && (
{
View Response
)}
- {(webRTCSend) && (
+ {webRTCSend && (
({
- reqResArray: store.reqRes.reqResArray,
-});
-
-/**@todo change to use hooks? */
-const mapDispatchToProps = (dispatch: AppDispatch) => ({
- reqResItemDeleted: (reqRes: ReqRes) => {
- dispatch(reqResItemDeleted(reqRes));
- },
- reqResUpdated: (reqRes: ReqRes) => {
- dispatch(reqResUpdated(reqRes));
- },
-});
+import ReqResCtrl from '~/controllers/reqResController';
+import { ReqRes } from '~/types';
-const WorkspaceCollectionsContainer = (props: $TSFixMe) => {
- const { reqResArray, reqResItemDeleted, updated, displaySchedule } = props;
+type Props = {
+ displaySchedule: boolean;
+};
- /**@todo maybe access functions (last two) directly from container instead of passing through props? */
- const reqResMapped = reqResArray.map((reqRes: ReqRes, index: $TSFixMe) => {
- return (
-
- );
- });
+const WorkspaceCollectionsContainer = ({ displaySchedule }: Props) => {
+ const reqResArray = useAppSelector((store) => store.reqRes.reqResArray);
+ const isDark = useAppSelector((store) => store.ui.isDark);
+ const dispatch = useAppDispatch();
const runCollectionTest = () => {
ReqResCtrl.runCollectionTest(reqResArray);
};
- const isDark = useSelector((store: RootState) => store.ui.isDark);
+
+ const deleteReqRes = (reqRes: ReqRes) => {
+ dispatch(reqResItemDeleted(reqRes));
+ };
return (
@@ -67,9 +42,21 @@ const WorkspaceCollectionsContainer = (props: $TSFixMe) => {
)}
- {reqResMapped.reverse()}
+
+ {reqResArray
+ .map((reqRes, index) => (
+
+ ))
+ .reverse()}
+
);
};
-export default connect(mapStateToProps, mapDispatchToProps)(WorkspaceCollectionsContainer);
+export default WorkspaceCollectionsContainer;
diff --git a/src/client/components/workspace/WorkspaceContainer.tsx b/src/client/components/workspace/WorkspaceContainer.tsx
index 6f1508b68..3aece1dd7 100644
--- a/src/client/components/workspace/WorkspaceContainer.tsx
+++ b/src/client/components/workspace/WorkspaceContainer.tsx
@@ -5,14 +5,14 @@
import React from 'react';
// Local components
-import WorkspaceContainerButtons from './buttons/WorkspaceContainerButtons';
+import WorkspaceContainerButtons from '~/components/workspace/buttons/WorkspaceContainerButtons';
import WorkspaceSelect from './WorkspaceSelect';
import DeleteWorkspaceButton from './buttons/DeleteWorkspaceButton';
import ImportExportWorkspaceButton from './buttons/ImportExportWorkspaceButton';
// MUI components and SVG icons
import { Box, Typography, Divider } from '@mui/material';
-import { WorkspaceContainerProps } from '../../../types';
+import { type WorkspaceContainerProps } from '~/types';
export default function WorkspaceContainer(props: WorkspaceContainerProps) {
return (
@@ -29,6 +29,7 @@ export default function WorkspaceContainer(props: WorkspaceContainerProps) {
+
Requests
diff --git a/src/client/components/workspace/WorkspaceContextMenu.tsx b/src/client/components/workspace/WorkspaceContextMenu.tsx
index 115434aef..29bcb3b64 100644
--- a/src/client/components/workspace/WorkspaceContextMenu.tsx
+++ b/src/client/components/workspace/WorkspaceContextMenu.tsx
@@ -1,23 +1,25 @@
-import React from 'react';
-import { useDispatch } from 'react-redux';
+import React, { useState } from 'react';
+
+import { useAppDispatch } from '../../rtk/store';
+import { reqResReplaced } from '../../rtk/slices/reqResSlice';
+
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
-import { reqResReplaced } from '../../toolkit-refactor/slices/reqResSlice';
+type MousePosition = {
+ mouseX: number;
+ mouseY: number;
+};
export default function WorkspaceContextMenu({ id, name, reqResArray }) {
- const dispatch = useDispatch();
-
- const [contextMenu, setContextMenu] = React.useState<{
- mouseX: number;
- mouseY: number;
- } | null>(null);
+ const [menuPosition, setMenuPosition] = useState(null);
+ const dispatch = useAppDispatch();
const handleContextMenu = (event: React.MouseEvent) => {
event.preventDefault();
- setContextMenu(
- contextMenu === null
+ setMenuPosition(
+ menuPosition === null
? {
mouseX: event.clientX + 2,
mouseY: event.clientY - 6,
@@ -30,7 +32,7 @@ export default function WorkspaceContextMenu({ id, name, reqResArray }) {
};
const handleClose = () => {
- setContextMenu(null);
+ setMenuPosition(null);
};
//
{name}
diff --git a/src/client/components/workspace/WorkspaceSelect.tsx b/src/client/components/workspace/WorkspaceSelect.tsx
index 96c65045e..b8fdc9a1f 100644
--- a/src/client/components/workspace/WorkspaceSelect.tsx
+++ b/src/client/components/workspace/WorkspaceSelect.tsx
@@ -1,9 +1,8 @@
import React from 'react';
-import { Collection, ReqRes, WorkspaceContainerProps } from '../../../types';
+import { useAppSelector, useAppDispatch } from '../../rtk/store';
+import { reqResReplaced } from '../../rtk/slices/reqResSlice';
-import { useSelector, useDispatch } from 'react-redux';
-
-import { reqResReplaced } from '../../toolkit-refactor/slices/reqResSlice';
+import { type ReqRes, type WorkspaceContainerProps } from '~/types';
import {
Box,
@@ -13,13 +12,12 @@ import {
FormHelperText,
SelectChangeEvent,
} from '@mui/material';
-import { RootState } from '../../toolkit-refactor/store';
export default function WorkspaceSelect({
currentWorkspaceId,
setWorkspace,
}: WorkspaceContainerProps) {
- const dispatch = useDispatch();
+ const dispatch = useAppDispatch();
const handleWorkspaceChange = (event: SelectChangeEvent) => {
setWorkspace(event.target.value as string);
@@ -29,9 +27,7 @@ export default function WorkspaceSelect({
dispatch(reqResReplaced(reqResArray));
};
- const workspaces: Collection[] = useSelector(
- (store: RootState) => store.collections
- );
+ const workspaces = useAppSelector((store) => store.collections);
const menuItems =
workspaces.length > 0
diff --git a/src/client/components/workspace/buttons/ClearHistoryBtn.tsx b/src/client/components/workspace/buttons/ClearHistoryBtn.tsx
index d4ca3568c..581b13456 100644
--- a/src/client/components/workspace/buttons/ClearHistoryBtn.tsx
+++ b/src/client/components/workspace/buttons/ClearHistoryBtn.tsx
@@ -1,42 +1,54 @@
-import React, { useEffect } from 'react';
-import { useSelector } from 'react-redux';
-import historyController from '../../../controllers/historyController';
-
-import { WindowExt, WindowAPI } from '../../../../types'
-import { RootState } from '../../../toolkit-refactor/store';
+import React, { useEffect, useRef } from 'react';
+import { useAppSelector } from '../../../rtk/store';
+import historyController from '~/controllers/historyController';
+import { type WindowExt } from '~/types';
// utilizing API we created in preload.js for node-free IPC communication
-const { api } = window as any;
+const { api } = window as unknown as WindowExt;
interface Props {
- historyCleared: () => void
-};
-
-const ClearHistoryBtn = (props: Props): JSX.Element => {
- const { historyCleared } = props;
-
- // cleanup api.receive event listener on dismount
+ historyCleared: () => void;
+}
+
+const ClearHistoryBtn = ({ historyCleared }: Props) => {
+ const isDark = useAppSelector((state) => state.ui.isDark);
+
+ /**
+ * It doesn't seem that the below effect should re-run if historyCleared
+ * changes its memory reference each render. This is a quick and dirty way
+ * of implementing the upcoming useEffectEvent hook to make sure there's no
+ * need to specify historyCleared in the dependency array
+ */
+ const historyClearedRef = useRef(historyCleared);
+ useEffect(() => {
+ historyClearedRef.current = historyCleared;
+ }, [historyCleared]);
+
+ /**
+ * @todo 2023-08-31 According to the previous comment, this effect does set up
+ * a subscription, which does need to be cleaned up on unmount. However, the
+ * api.receive method does not give you an unsubscribe callback as its return
+ * value. Update api.receive so that it lets you unsubscribe, and then
+ * add a cleanup function in this effect that calls the returned unsubscribe
+ * callback.
+ */
useEffect(() => {
api.receive('clear-history-response', (res: { response: number }) => {
// a response of 0 from main means user has selected 'confirm'
if (res.response === 0) {
historyController.clearHistoryFromIndexedDb();
- historyCleared();
+ historyClearedRef.current();
}
});
}, []);
- const isDark = useSelector((state: RootState) => state.ui.isDark);
-
- const handleClick = () => {
- api.send('confirm-clear-history');
- };
return (
api.send('confirm-clear-history')}
className={`ml-0 mt-3 mb-3 button is-small is-primary ${
isDark ? '' : 'is-outlined'
} button-padding-verticals`}
- onClick={handleClick}
>
Clear History
diff --git a/src/client/components/workspace/buttons/DeleteWorkspaceButton.tsx b/src/client/components/workspace/buttons/DeleteWorkspaceButton.tsx
index cec61abc6..074ddafd0 100644
--- a/src/client/components/workspace/buttons/DeleteWorkspaceButton.tsx
+++ b/src/client/components/workspace/buttons/DeleteWorkspaceButton.tsx
@@ -1,22 +1,20 @@
import React from 'react';
-import { useDispatch, useSelector } from 'react-redux';
+import { useAppSelector, useAppDispatch } from '../../../rtk/store';
+import { collectionDeleted } from '../../../rtk/slices/collectionsSlice';
-import { collectionDeleted } from '../../../toolkit-refactor/slices/collectionsSlice';
+import { type Collection, type WorkspaceContainerProps } from '~/types';
+import collectionsController from '~/controllers/collectionsController';
import ClearRoundedIcon from '@mui/icons-material/ClearRounded';
-import collectionsController from '../../../controllers/collectionsController';
import { Button } from '@mui/material';
-import { SwellTooltip } from '../../customMuiStyles/tooltip';
-import { Collection, WorkspaceContainerProps } from '../../../../types';
-import { RootState } from '../../../toolkit-refactor/store';
+import { SwellTooltip } from '~/components/customMuiStyles/tooltip';
export default function DeleteRequestButton({
currentWorkspaceId,
setWorkspace,
}: WorkspaceContainerProps) {
- const dispatch = useDispatch();
- // Grab all of the workspaces from the Redux store. Hopefully this is O(1)...
- const allWorkspaces = useSelector((store: RootState) => store.collections);
+ const allWorkspaces = useAppSelector((store) => store.collections);
+ const dispatch = useAppDispatch();
const currentWorkspace = (): Collection => {
const workspace: Collection | undefined = allWorkspaces.find(
diff --git a/src/client/components/workspace/buttons/ImportExportWorkspaceButton.tsx b/src/client/components/workspace/buttons/ImportExportWorkspaceButton.tsx
index 201e85650..48dd04098 100644
--- a/src/client/components/workspace/buttons/ImportExportWorkspaceButton.tsx
+++ b/src/client/components/workspace/buttons/ImportExportWorkspaceButton.tsx
@@ -1,8 +1,9 @@
import React from 'react';
+
import { Button } from '@mui/material';
import ImportExportIcon from '@mui/icons-material/ImportExport';
import ImportExportWorkspaceModal from '../modals/import-export-workspace/ImportExportWorkspaceModal';
-import { SwellTooltip } from '../../customMuiStyles/tooltip';
+import { SwellTooltip } from '~/components/customMuiStyles/tooltip';
export default function ImportExportWorkspaceButton() {
const [open, setOpen] = React.useState(false);
diff --git a/src/client/components/workspace/buttons/WorkspaceContainerButtons.tsx b/src/client/components/workspace/buttons/WorkspaceContainerButtons.tsx
index 09c744353..c1c389f84 100644
--- a/src/client/components/workspace/buttons/WorkspaceContainerButtons.tsx
+++ b/src/client/components/workspace/buttons/WorkspaceContainerButtons.tsx
@@ -1,20 +1,22 @@
import React, { useState } from 'react';
-import { useSelector } from 'react-redux';
-import ReqResCtrl from '../../../controllers/reqResController';
+import { useAppSelector } from '../../../rtk/store';
+import ReqResCtrl from '~/controllers/reqResController';
+
import WorkspaceCollectionsContainer from '../WorkspaceCollectionsContainer';
-import SaveWorkspaceModal from '../modals/SaveWorkspaceModal';
-// Import MUI components
+import SaveWorkspaceModal from '~/components/workspace/modals/SaveWorkspaceModal';
-export default function WorkspaceContainerButtons () {
+export default function WorkspaceContainerButtons() {
const [showModal, setShowModal] = useState(false);
- const isDark = useSelector((store: { ui: { isDark: boolean }}) => store.ui.isDark);
+ const isDark = useAppSelector((state) => state.ui.isDark);
return (
{/* NAV BAR */}
{
@@ -26,7 +28,9 @@ export default function WorkspaceContainerButtons () {
{
@@ -37,9 +41,9 @@ export default function WorkspaceContainerButtons () {
-
+
{/* REQUEST CARDS */}
);
-}
\ No newline at end of file
+}
diff --git a/src/client/components/workspace/modals/SaveModalSavedWorkspaces.tsx b/src/client/components/workspace/modals/SaveModalSavedWorkspaces.tsx
index 02ff11869..b074e6730 100644
--- a/src/client/components/workspace/modals/SaveModalSavedWorkspaces.tsx
+++ b/src/client/components/workspace/modals/SaveModalSavedWorkspaces.tsx
@@ -3,9 +3,9 @@
import React from 'react';
interface Props {
- name: string,
- inputID: string,
- updateCollection: (name: string, inputID: string) => void
+ name: string;
+ inputID: string;
+ updateCollection: (name: string, inputID: string) => void;
}
function SaveModalSavedWorkspaces({ name, inputID, updateCollection }: Props) {
diff --git a/src/client/components/workspace/modals/SaveWorkspaceModal.tsx b/src/client/components/workspace/modals/SaveWorkspaceModal.tsx
index 535dee429..ed36c3882 100644
--- a/src/client/components/workspace/modals/SaveWorkspaceModal.tsx
+++ b/src/client/components/workspace/modals/SaveWorkspaceModal.tsx
@@ -2,32 +2,36 @@
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import React, { useState } from 'react';
-import { useSelector, useDispatch } from 'react-redux';
import { v4 as uuid } from 'uuid';
-import collectionsController from '../../../controllers/collectionsController';
-import SaveModalSavedWorkspaces from './SaveModalSavedWorkspaces';
-import { ReqRes } from '../../../../../src/types'
-import { RootState } from '../../../toolkit-refactor/store';
+import { useAppDispatch, useAppSelector } from '../../../rtk/store';
import {
collectionUpdated,
collectionAdded,
-} from '../../../toolkit-refactor/slices/collectionsSlice';
+} from '../../../rtk/slices/collectionsSlice';
+
+import { type ReqRes } from '~/types';
+import collectionsController from '~/controllers/collectionsController';
+
+import SaveModalSavedWorkspaces from './SaveModalSavedWorkspaces';
interface modalSwitch {
- showModal: boolean,
- setShowModal: (showSwitch: boolean) => void
-};
+ showModal: boolean;
+ setShowModal: (showSwitch: boolean) => void;
+}
-export default function SaveWorkspaceModal({ showModal, setShowModal }: modalSwitch): JSX.Element {
- const dispatch = useDispatch();
+export default function SaveWorkspaceModal({
+ showModal,
+ setShowModal,
+}: modalSwitch): JSX.Element {
+ const dispatch = useAppDispatch();
// LOCAL STATE HOOKS
const [input, setInput] = useState('');
const [collectionNameErrorStyles, setCollectionNameErrorStyles] =
useState(false);
- // PULL elements FROM store
- const reqResArray = useSelector((store: RootState) => store.reqRes.reqResArray);
- const collections = useSelector((store: RootState) => store.collections);
+
+ const reqResArray = useAppSelector((store) => store.reqRes.reqResArray);
+ const collections = useAppSelector((store) => store.collections);
const saveCollection = (inputName: string): void => {
const clonedArray = JSON.parse(JSON.stringify(reqResArray));
@@ -164,4 +168,4 @@ export default function SaveWorkspaceModal({ showModal, setShowModal }: modalSwi
)}
);
-}
\ No newline at end of file
+}
diff --git a/src/client/components/workspace/modals/export-workspace/ExportWorkspaceModal.tsx b/src/client/components/workspace/modals/export-workspace/ExportWorkspaceModal.tsx
index 096fdb887..a63544765 100644
--- a/src/client/components/workspace/modals/export-workspace/ExportWorkspaceModal.tsx
+++ b/src/client/components/workspace/modals/export-workspace/ExportWorkspaceModal.tsx
@@ -1,13 +1,13 @@
-import * as React from 'react';
-import { useSelector } from 'react-redux';
+import React from 'react';
+import { useAppSelector } from '../../../../rtk/store';
+import collectionsController from '~/controllers/collectionsController';
+
import Backdrop from '@mui/material/Backdrop';
import Box from '@mui/material/Box';
import { Button } from '@mui/material';
import Modal from '@mui/material/Modal';
import Fade from '@mui/material/Fade';
import Typography from '@mui/material/Typography';
-import collectionsController from '../../../../controllers/collectionsController';
-import { RootState } from '../../../../toolkit-refactor/store';
const style = {
display: 'flex',
@@ -25,8 +25,8 @@ const style = {
};
export default function ExportWorkspaceModal({ open, handleClose }) {
- const localWorkspaces = useSelector((store: RootState) => store.collections);
- const isDark = useSelector((store: RootState) => store.ui.isDark);
+ const localWorkspaces = useAppSelector((store) => store.collections);
+ const isDark = useAppSelector((state) => state.ui.isDark);
return (
{
setExportToLocalFilesList(!exportToLocalFilesList);
};
- let workspaces = useLiveQuery(() => db.collections.toArray());
-
- const localWorkspaces = useSelector((store: RootState) => store.collections);
+ const localWorkspaces = useAppSelector((store) => store.collections);
+ const workspaces = useLiveQuery(() => db.collections.toArray());
const importFileClick = () => {
collectionsController.importCollection(localWorkspaces);
diff --git a/src/client/components/workspace/modals/import-workspace/ImportWorkspaceModal.tsx b/src/client/components/workspace/modals/import-workspace/ImportWorkspaceModal.tsx
index 22653ec75..e67063b1f 100644
--- a/src/client/components/workspace/modals/import-workspace/ImportWorkspaceModal.tsx
+++ b/src/client/components/workspace/modals/import-workspace/ImportWorkspaceModal.tsx
@@ -1,15 +1,16 @@
-import * as React from 'react';
+import React from 'react';
+import { useLiveQuery } from 'dexie-react-hooks';
+
+import { useAppSelector } from '../../../../rtk/store';
+import collectionsController from '~/controllers/collectionsController';
+import db from '~/db';
+
import Backdrop from '@mui/material/Backdrop';
-import { useSelector } from 'react-redux';
import Box from '@mui/material/Box';
import { Button } from '@mui/material';
import Modal from '@mui/material/Modal';
import Fade from '@mui/material/Fade';
import Typography from '@mui/material/Typography';
-import collectionsController from '../../../../controllers/collectionsController';
-import db from '../../../../db';
-import { useLiveQuery } from 'dexie-react-hooks';
-import { RootState } from '../../../../toolkit-refactor/store';
const style = {
display: 'flex',
@@ -26,12 +27,15 @@ const style = {
justifyContent: 'space-around',
};
-export default function ImportWorkspaceModal({ open, handleClose }): JSX.Element{
+export default function ImportWorkspaceModal({
+ open,
+ handleClose,
+}): JSX.Element {
let files = useLiveQuery(() => db.files.toArray());
console.log(files);
- const localWorkspaces = useSelector((store: RootState) => store.collections);
- const isDark = useSelector((state: RootState) => state.ui.isDark);
+ const localWorkspaces = useAppSelector((store) => store.collections);
+ const isDark = useAppSelector((state) => state.ui.isDark);
const swellReposContent = (files ?? []).map((file) => (
{file.repository.full_name}
@@ -74,81 +78,3 @@ export default function ImportWorkspaceModal({ open, handleClose }): JSX.Element
);
}
-
-
-// import * as React from 'react';
-// import Backdrop from '@mui/material/Backdrop';
-// import { useSelector } from 'react-redux';
-// import Box from '@mui/material/Box';
-// import { Button } from '@mui/material';
-// import Modal from '@mui/material/Modal';
-// import Fade from '@mui/material/Fade';
-// import Typography from '@mui/material/Typography';
-// import collectionsController from '../../../../controllers/collectionsController';
-// import db from '../../../../db';
-// import { useLiveQuery } from 'dexie-react-hooks';
-// import { RootState } from '../../../../toolkit-refactor/store';
-
-// const style = {
-// display: 'flex',
-// flexDirection: 'row',
-// alignItems: 'center',
-// position: 'absolute',
-// top: '50%',
-// left: '50%',
-// transform: 'translate(-50%, -50%)',
-// width: 400,
-// bgcolor: 'background.paper',
-// boxShadow: 24,
-// p: 1,
-// justifyContent: 'space-around',
-// };
-
-// export default function ImportWorkspaceModal({ open, handleClose }) {
-// let files = useLiveQuery(() => db.files.toArray());
-// console.log(files);
-
-// const localWorkspaces = useSelector((store: RootState) => store.collections);
-// const isDark = useSelector((state: RootState) => state.ui.isDark);
-
-// const swellReposContent = (files ?? []).map((file) => (
-// {file.repository.full_name}
-// ));
-
-// return (
-//
-//
-//
-//
-// Import from
-//
-//
-// collectionsController.importCollection(localWorkspaces)
-// }
-// >
-// Files
-//
-// {swellReposContent}
-//
-//
-//
-// );
-// }
-
diff --git a/src/client/controllers/LoadTestController.ts b/src/client/controllers/LoadTestController.ts
index 978c8407e..f95e0fb13 100644
--- a/src/client/controllers/LoadTestController.ts
+++ b/src/client/controllers/LoadTestController.ts
@@ -4,15 +4,12 @@
* as well as updating the application state (store) with the processed results.
*/
-import store from '../toolkit-refactor/store';
-import { appDispatch } from '../toolkit-refactor/store';
-import {
- responseDataSaved,
- reqResUpdated,
-} from '../toolkit-refactor/slices/reqResSlice';
-import { ReqRes, ReqResResponse, WindowExt } from '../../types';
+import store, { appDispatch } from '../rtk/store';
+import { responseDataSaved, reqResUpdated } from '../rtk/slices/reqResSlice';
+import { graphUpdated } from '../rtk/slices/graphPointsSlice';
+
+import { type ReqRes, type ReqResResponse, type WindowExt } from '~/types';
import { LoadTestResult } from '../components/main/sharedComponents/stressTest/LoadTest';
-import { graphUpdated } from '../toolkit-refactor/slices/graphPointsSlice';
const { api } = window as unknown as WindowExt;
diff --git a/src/client/controllers/collectionsController.ts b/src/client/controllers/collectionsController.ts
index 0544ca658..e2eb3b8b2 100644
--- a/src/client/controllers/collectionsController.ts
+++ b/src/client/controllers/collectionsController.ts
@@ -1,10 +1,9 @@
import { v4 as uuid } from 'uuid';
-import db from '../db';
+import db from '~/db';
-import { appDispatch } from '../toolkit-refactor/store';
-import { collectionsReplaced } from '../toolkit-refactor/slices/collectionsSlice';
-
-import { Collection, WindowAPI, WindowExt } from '../../types';
+import { appDispatch } from '../rtk/store';
+import { collectionsReplaced } from '../rtk/slices/collectionsSlice';
+import { type Collection, type WindowAPI, type WindowExt } from '~/types';
const { api }: { api: WindowAPI } = window as unknown as WindowExt;
diff --git a/src/client/controllers/graphQLController.ts b/src/client/controllers/graphQLController.ts
index b83db2568..e02916308 100644
--- a/src/client/controllers/graphQLController.ts
+++ b/src/client/controllers/graphQLController.ts
@@ -9,21 +9,17 @@ import { createClient } from 'graphql-ws';
import { buildClientSchema, printSchema, IntrospectionQuery } from 'graphql';
import {
- ReqRes,
- GraphQLResponse,
- Cookie,
- CookieOrHeader,
- WindowExt,
-} from '../../types';
-
-import Store from '../toolkit-refactor/store';
-import { appDispatch } from '../toolkit-refactor/store';
-import { introspectionDataChanged } from '../toolkit-refactor/slices/introspectionDataSlice';
-import {
- responseDataSaved,
- reqResUpdated,
-} from '../toolkit-refactor/slices/reqResSlice';
-import { graphUpdated } from '../toolkit-refactor/slices/graphPointsSlice';
+ type ReqRes,
+ type GraphQLResponse,
+ type Cookie,
+ type CookieOrHeader,
+ type WindowExt,
+} from '~/types';
+
+import Store, { appDispatch } from '../rtk/store';
+import { introspectionDataChanged } from '../rtk/slices/introspectionDataSlice';
+import { responseDataSaved, reqResUpdated } from '../rtk/slices/reqResSlice';
+import { graphUpdated } from '../rtk/slices/graphPointsSlice';
const { api } = window as unknown as WindowExt;
diff --git a/src/client/controllers/grpcController.ts b/src/client/controllers/grpcController.ts
index cd0de8e61..2a78c7a9c 100644
--- a/src/client/controllers/grpcController.ts
+++ b/src/client/controllers/grpcController.ts
@@ -1,58 +1,55 @@
-import {
- WindowExt,
- NewRequestStreams,
- $TSFixMe
- } from '../../types';
+import { type WindowExt, type NewRequestStreams, type $TSFixMe } from '~/types';
-import { appDispatch } from '../toolkit-refactor/store';
-const { api } = window as unknown as WindowExt;
+import { appDispatch } from '../rtk/store';
+import { newRequestStreamsSet } from '../rtk/slices/newRequestSlice';
-import { newRequestStreamsSet } from '../toolkit-refactor/slices/newRequestSlice';
+const { api } = window as unknown as WindowExt;
const grpcController: $TSFixMe = {
+ protoParserReturn(newRequestStreams: NewRequestStreams): void {
+ try {
+ // Set up the listener when for parsed protos entered into textFieldArea
+ api.removeAllListeners('protoParserFunc-return');
- protoParserReturn(newRequestStreams: NewRequestStreams): void {
-
- try {
- // Set up the listener when for parsed protos entered into textFieldArea
- api.removeAllListeners('protoParserFunc-return');
-
- api.receive('protoParserFunc-return', async function parsedProtoRes(data: string) {
- try{
- const result: $TSFixMe = await JSON.parse(data)
-
- const services = result.serviceArr ? result.serviceArr : null;
- const protoPath = result.protoPath ? result.protoPath : null;
- const streamsArr = [newRequestStreams.streamsArr[0]];
- const streamContent = [''];
-
- const updatedNewRequestStream: NewRequestStreams = {
- ...newRequestStreams,
- selectedPackage: null,
- selectedService: null,
- selectedRequest: null,
- selectedStreamingType: null,
- selectedServiceObj: null,
- services,
- protoPath,
- streamsArr,
- streamContent,
- count: 10,
- }
-
- appDispatch(newRequestStreamsSet(updatedNewRequestStream))
- } catch (err) {
- console.log(err)
- }
- });
- } catch(err) {
- console.error(err)
+ api.receive(
+ 'protoParserFunc-return',
+ async function parsedProtoRes(data: string) {
+ try {
+ const result: $TSFixMe = await JSON.parse(data);
+
+ const services = result.serviceArr ? result.serviceArr : null;
+ const protoPath = result.protoPath ? result.protoPath : null;
+ const streamsArr = [newRequestStreams.streamsArr[0]];
+ const streamContent = [''];
+
+ const updatedNewRequestStream: NewRequestStreams = {
+ ...newRequestStreams,
+ selectedPackage: null,
+ selectedService: null,
+ selectedRequest: null,
+ selectedStreamingType: null,
+ selectedServiceObj: null,
+ services,
+ protoPath,
+ streamsArr,
+ streamContent,
+ count: 10,
+ };
+
+ appDispatch(newRequestStreamsSet(updatedNewRequestStream));
+ } catch (err) {
+ console.log(err);
+ }
}
- },
- sendParserData(data: string): void {
- api.send('protoParserFunc-request', data);
- },
- importProto(newRequestStreams: $TSFixMe): void {
+ );
+ } catch (err) {
+ console.error(err);
+ }
+ },
+ sendParserData(data: string): void {
+ api.send('protoParserFunc-request', data);
+ },
+ importProto(newRequestStreams: $TSFixMe): void {
// clear all stream bodies except first one upon clicking on import proto file
const streamsArr = [newRequestStreams.streamsArr[0]];
const streamContent = [''];
@@ -60,7 +57,7 @@ const grpcController: $TSFixMe = {
// reset selected package name, service, request, streaming type & protoContent
if (newRequestStreams.protoContent !== null) {
- const updatedNewRequestStream: NewRequestStreams = {
+ const updatedNewRequestStream: NewRequestStreams = {
...newRequestStreams,
selectedPackage: null,
selectedService: null,
@@ -72,29 +69,32 @@ const grpcController: $TSFixMe = {
streamContent,
count: 1,
};
- appDispatch(newRequestStreamsSet(updatedNewRequestStream))
+ appDispatch(newRequestStreamsSet(updatedNewRequestStream));
}
-
+
// listens for imported proto content from main process
- api.receive('proto-info', async (proto: $TSFixMe, unparsedProtoObj:$TSFixMe) => {
- try {
- const readProto = await JSON.parse(proto);
- const parsedProto = await JSON.parse(unparsedProtoObj)
-
-
- const updatedNewRequestStream: NewRequestStreams = {
- ...newRequestStreams,
- protoContent: readProto,
- services: parsedProto.serviceArr,
- protoPath: parsedProto.protoPath,
- };
- appDispatch(newRequestStreamsSet(updatedNewRequestStream))
- } catch (err) {
- throw new Error('Error receiving parsed uploaded proto');
- }
- });
+ api.receive(
+ 'proto-info',
+ async (proto: $TSFixMe, unparsedProtoObj: $TSFixMe) => {
+ try {
+ const readProto = await JSON.parse(proto);
+ const parsedProto = await JSON.parse(unparsedProtoObj);
+
+ const updatedNewRequestStream: NewRequestStreams = {
+ ...newRequestStreams,
+ protoContent: readProto,
+ services: parsedProto.serviceArr,
+ protoPath: parsedProto.protoPath,
+ };
+ appDispatch(newRequestStreamsSet(updatedNewRequestStream));
+ } catch (err) {
+ throw new Error('Error receiving parsed uploaded proto');
+ }
+ }
+ );
api.send('import-proto');
- }
-}
+ },
+};
+
+export default grpcController;
-export default grpcController;
\ No newline at end of file
diff --git a/src/client/controllers/historyController.ts b/src/client/controllers/historyController.ts
index 2344c3187..7ebe060b8 100644
--- a/src/client/controllers/historyController.ts
+++ b/src/client/controllers/historyController.ts
@@ -1,18 +1,19 @@
import { format, parse } from 'date-fns';
-import db from '../db';
+import db from '~/db';
-import { appDispatch } from '../toolkit-refactor/store';
-import { historySet } from '../toolkit-refactor/slices/historySlice';
-import { setSidebarActiveTab } from '../toolkit-refactor/slices/uiSlice';
-import { fieldsReplaced } from '../toolkit-refactor/slices/newRequestFieldsSlice';
+import { appDispatch } from '../rtk/store';
+import { historySet } from '../rtk/slices/historySlice';
+import { setSidebarActiveTab } from '../rtk/slices/uiSlice';
+import { fieldsReplaced } from '../rtk/slices/newRequestFieldsSlice';
import {
- newRequestSSESet, newRequestCookiesSet,
- newRequestStreamsSet, newRequestBodySet,
- newRequestHeadersSet
-} from '../toolkit-refactor/slices/newRequestSlice';
-
-import { ReqRes, $TSFixMe } from '../../types';
+ newRequestSSESet,
+ newRequestCookiesSet,
+ newRequestStreamsSet,
+ newRequestBodySet,
+ newRequestHeadersSet,
+} from '../rtk/slices/newRequestSlice';
+import { type ReqRes, type $TSFixMe } from '~/types';
const historyController = {
addHistoryToIndexedDb(reqRes: ReqRes): void {
@@ -144,7 +145,7 @@ const historyController = {
let headerDeeperCopy;
if (content.request.headers) {
- headerDeeperCopy = structuredClone(content.request.headers)
+ headerDeeperCopy = structuredClone(content.request.headers);
headerDeeperCopy.push({
id: content.request.headers.length + 1,
active: false,
@@ -156,7 +157,7 @@ const historyController = {
let cookieDeeperCopy;
if (content.request.cookies && !/ws/.test(content.protocol)) {
- cookieDeeperCopy = structuredClone(content.request.cookies)
+ cookieDeeperCopy = structuredClone(content.request.cookies);
cookieDeeperCopy.push({
id: content.request.cookies.length + 1,
active: false,
@@ -192,8 +193,8 @@ const historyController = {
appDispatch(newRequestSSESet(content.request.isSSE));
if (content && content.gRPC) {
- const streamsDeepCopy = structuredClone(content.streamsArr)//JSON.parse(JSON.stringify(content.streamsArr));
- const contentsDeepCopy = structuredClone(content.streamsContent)//JSON.parse(JSON.stringify(content.streamContent));
+ const streamsDeepCopy = structuredClone(content.streamsArr); //JSON.parse(JSON.stringify(content.streamsArr));
+ const contentsDeepCopy = structuredClone(content.streamsContent); //JSON.parse(JSON.stringify(content.streamContent));
// construct the streams obj from passed in history content & set state in store
const requestStreamsObj = {
@@ -215,7 +216,7 @@ const historyController = {
}
appDispatch(setSidebarActiveTab('composer'));
- }
+ },
};
export default historyController;
diff --git a/src/client/controllers/openApiController.ts b/src/client/controllers/openApiController.ts
index 11c4a3d6a..e31e11853 100644
--- a/src/client/controllers/openApiController.ts
+++ b/src/client/controllers/openApiController.ts
@@ -1,30 +1,25 @@
-const YAML = require('yamljs');
-import {
- WindowExt,
- $TSFixMe
- } from '../../types';
+import { type WindowExt, type $TSFixMe } from '~/types';
+import { appDispatch } from '../rtk/store';
+import { openApiRequestsReplaced } from '../rtk/slices/newRequestOpenApiSlice';
-import { appDispatch } from '../toolkit-refactor/store';
const { api } = window as unknown as WindowExt;
-import { openApiRequestsReplaced } from '../toolkit-refactor/slices/newRequestOpenApiSlice'
const openApiController: $TSFixMe = {
+ importDocument(): void {
+ api.removeAllListeners('openapi-info');
+ api.receive('openapi-info', async (data_in: $TSFixMe) => {
+ try {
+ appDispatch(openApiRequestsReplaced(data_in));
+ } catch (err) {
+ // If swell ever gets big enough, this needs to be built out
+ console.log('Error in openAPI Controller: ', err);
+ }
+ });
+ },
+ sendDocument(): void {
+ api.send('import-openapi');
+ },
+};
- importDocument(): void {
- api.removeAllListeners('openapi-info');
- api.receive('openapi-info', async (data_in: $TSFixMe) => {
- try {
+export default openApiController;
- appDispatch(openApiRequestsReplaced(data_in));
- } catch (err) {
- // If swell ever gets big enough, this needs to be built out
- console.log('Error in openAPI Controller: ', err)
- }
- })
- },
- sendDocument(): void {
- api.send('import-openapi');
- },
-}
-
-export default openApiController;
\ No newline at end of file
diff --git a/src/client/controllers/reqResController.ts b/src/client/controllers/reqResController.ts
index cdcaed0a2..ab9c9e91a 100644
--- a/src/client/controllers/reqResController.ts
+++ b/src/client/controllers/reqResController.ts
@@ -1,20 +1,20 @@
-import Store from '../toolkit-refactor/store';
-import { appDispatch } from '../toolkit-refactor/store';
+import Store, { appDispatch } from '../rtk/store';
import {
responseDataSaved,
reqResUpdated,
reqResReplaced,
reqResCleared,
-} from '../toolkit-refactor/slices/reqResSlice';
+} from '../rtk/slices/reqResSlice';
+
import {
groupCleared,
graphCleared,
graphUpdated,
-} from '../toolkit-refactor/slices/graphPointsSlice';
+} from '../rtk/slices/graphPointsSlice';
import graphQLController from './graphQLController';
-import { Protocol, ReqRes, WindowExt } from '../../types';
+import { type Protocol, type ReqRes, type WindowExt } from '~/types';
const { api } = window as unknown as WindowExt;
diff --git a/src/client/controllers/webrtcPeerController.ts b/src/client/controllers/webrtcPeerController.ts
index 626529729..860740e7f 100644
--- a/src/client/controllers/webrtcPeerController.ts
+++ b/src/client/controllers/webrtcPeerController.ts
@@ -1,16 +1,18 @@
-import store, { appDispatch } from '../toolkit-refactor/store';
+import store, { appDispatch } from '../rtk/store';
+import { responseDataSaved } from '../rtk/slices/reqResSlice';
import {
newRequestWebRTCSet,
newRequestWebRTCOfferSet,
-} from '../toolkit-refactor/slices/newRequestSlice';
+} from '../rtk/slices/newRequestSlice';
+
import {
- ReqRes,
- RequestWebRTC,
- RequestWebRTCText,
- ResponseWebRTC,
- ResponseWebRTCText,
-} from '../../types';
-import { responseDataSaved } from '../toolkit-refactor/slices/reqResSlice';
+ type ReqRes,
+ type RequestWebRTC,
+ type RequestWebRTCText,
+ type ResponseWebRTC,
+ type ResponseWebRTCText,
+} from '~/types';
+
const webrtcPeerController = {
createPeerConnection: async (
newRequestWebRTC: RequestWebRTC
@@ -72,7 +74,7 @@ const webrtcPeerController = {
} else if (newRequestWebRTC.webRTCDataChannel === 'Text') {
let localStream = peerConnection.createDataChannel('textChannel');
localStream.onopen = () => console.log('data channel opened');
- localStream.onclose = () => console.log('data channel closed')
+ localStream.onclose = () => console.log('data channel closed');
appDispatch(
newRequestWebRTCSet({
@@ -174,11 +176,10 @@ const webrtcPeerController = {
let state = store.getState();
if (state.reqRes.currentResponse.response) {
- let newWebRTCMessages =
- (state.reqRes.currentResponse.response).webRTCMessages.concat(
- messageObject
- );
- let request = state.reqRes.currentResponse.request
+ let newWebRTCMessages = ((
+ state.reqRes.currentResponse.response
+ )).webRTCMessages.concat(messageObject);
+ let request = state.reqRes.currentResponse.request;
appDispatch(
responseDataSaved({
...reqRes,
diff --git a/src/client/hooks/useDropdownState.ts b/src/client/hooks/useDropdownState.ts
new file mode 100644
index 000000000..f104b84d4
--- /dev/null
+++ b/src/client/hooks/useDropdownState.ts
@@ -0,0 +1,67 @@
+/**
+ * @file Defines reusable logic for managing dropdown state for several
+ * components throughout the application.
+ *
+ * Is this the right abstraction? I dunno, but the basic version of the code
+ * was copy-and-pasted seven different times throughout the codebase before I
+ * extracted it out into a custom hook and cleaned it up for performance.
+ *
+ * Realistically, the better solution would be to create a reusable Dropdown
+ * component that can then be composed around all the other components that are
+ * consuming this hook right now.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export default function useDropdownState() {
+ /**
+ * Very deliberately not exposing the raw setDropdownIsOpen state dispatch
+ * outside this hook. The state should only be updated in a handful of
+ * prescribed ways, which are defined via the exposed useCallback functions.
+ */
+ const [dropdownIsOpen, setDropdownIsOpen] = useState(false);
+ const dropdownRef = useRef(null);
+
+ /**
+ * Applying useCallback to make sure that their memory references don't
+ * change. This logic is used in a lot of places, and I don't want this hook
+ * suddenly breaking useEffect calls or any component memoization (not that
+ * there is any, I think)
+ */
+ const closeDropdown = useCallback(() => {
+ setDropdownIsOpen(false);
+ }, []);
+
+ const toggleDropdown = useCallback(() => {
+ setDropdownIsOpen((current) => !current);
+ }, []);
+
+ // Adds listeners for auto-closing an open dropdown if you click outside it
+ useEffect(() => {
+ const onParentClick = (event: MouseEvent) => {
+ const shouldClose =
+ event.target instanceof HTMLElement &&
+ !dropdownRef.current?.contains(event.target);
+
+ if (shouldClose) {
+ closeDropdown();
+ }
+ };
+
+ document.addEventListener('click', onParentClick);
+ return () => document.removeEventListener('click', onParentClick);
+
+ /**
+ * 2023-08-31 - Please do not remove closeDropdown from the dependency
+ * array. This is the proper way of doing things; if the linter config
+ * weren't busted, it would yell at you for trying to remove the value
+ */
+ }, [closeDropdown]);
+
+ return {
+ dropdownIsOpen,
+ dropdownRef,
+ closeDropdown,
+ toggleDropdown,
+ } as const;
+}
+
diff --git a/src/client/toolkit-refactor/rootReducer.ts b/src/client/rtk/rootReducer.ts
similarity index 82%
rename from src/client/toolkit-refactor/rootReducer.ts
rename to src/client/rtk/rootReducer.ts
index dbe479ac3..16fc1e2ce 100644
--- a/src/client/toolkit-refactor/rootReducer.ts
+++ b/src/client/rtk/rootReducer.ts
@@ -12,10 +12,6 @@ import IntrospectionDataReducer from './slices/introspectionDataSlice';
import WarningMessageReducer from './slices/warningMessageSlice';
import MockServerReducer from './slices/mockServerSlice';
-// Note: There was previously a currentTab prop in the Redux store; it wasn't
-// used anywhere, and there was no info about it other than it was a string. We
-// dropped it from the store, but it might make sense to add it back at some
-// point
const rootReducer = combineReducers({
history: HistoryReducer,
newRequest: NewRequestReducer,
diff --git a/src/client/toolkit-refactor/slices/collectionsSlice.ts b/src/client/rtk/slices/collectionsSlice.ts
similarity index 97%
rename from src/client/toolkit-refactor/slices/collectionsSlice.ts
rename to src/client/rtk/slices/collectionsSlice.ts
index 347d6e2be..db75f942e 100644
--- a/src/client/toolkit-refactor/slices/collectionsSlice.ts
+++ b/src/client/rtk/slices/collectionsSlice.ts
@@ -6,7 +6,7 @@
* cause elements to be skipped.
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
-import { Collection, $NotUsed } from '../../../types';
+import { type Collection, type $NotUsed } from '~/types';
const initialState: Collection[] = [];
diff --git a/src/client/toolkit-refactor/slices/graphPointsSlice.ts b/src/client/rtk/slices/graphPointsSlice.ts
similarity index 98%
rename from src/client/toolkit-refactor/slices/graphPointsSlice.ts
rename to src/client/rtk/slices/graphPointsSlice.ts
index 4ad0b8a28..ee1b3a50e 100644
--- a/src/client/toolkit-refactor/slices/graphPointsSlice.ts
+++ b/src/client/rtk/slices/graphPointsSlice.ts
@@ -1,5 +1,5 @@
import { createAction, createSlice, PayloadAction } from '@reduxjs/toolkit';
-import { ReqRes } from '../../../types';
+import { type ReqRes } from '~/types';
/**
* Keeps track of the current color to use with UI_SAFE_COLORS
diff --git a/src/client/toolkit-refactor/slices/historySlice.ts b/src/client/rtk/slices/historySlice.ts
similarity index 94%
rename from src/client/toolkit-refactor/slices/historySlice.ts
rename to src/client/rtk/slices/historySlice.ts
index 02aa39e06..b7088a736 100644
--- a/src/client/toolkit-refactor/slices/historySlice.ts
+++ b/src/client/rtk/slices/historySlice.ts
@@ -1,12 +1,10 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { reqResItemAdded } from './reqResSlice';
-import { $NotUsed, ReqRes } from '../../../types';
+import { type $NotUsed, type ReqRes } from '~/types';
import { format, parseISO } from 'date-fns';
-import { WritableDraft } from 'immer/dist/internal';
-import produce from 'immer';
-type HistoryItem = {
+export type HistoryItem = {
/**
* A date for a specific history item. Stored as string so that value is fully
* JSON-serializable; format seems to be MM/dd/yyyy
diff --git a/src/client/toolkit-refactor/slices/introspectionDataSlice.ts b/src/client/rtk/slices/introspectionDataSlice.ts
similarity index 91%
rename from src/client/toolkit-refactor/slices/introspectionDataSlice.ts
rename to src/client/rtk/slices/introspectionDataSlice.ts
index 647aada39..824cf3b64 100644
--- a/src/client/toolkit-refactor/slices/introspectionDataSlice.ts
+++ b/src/client/rtk/slices/introspectionDataSlice.ts
@@ -2,7 +2,7 @@
* @file Slice for managing introspection data from GraphQL.
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
-import { $NotUsed, IntrospectionData } from '../../../types';
+import { $NotUsed, IntrospectionData } from '~/types';
const initialState: IntrospectionData = {
schemaSDL: null,
diff --git a/src/client/toolkit-refactor/slices/mockServerSlice.ts b/src/client/rtk/slices/mockServerSlice.ts
similarity index 100%
rename from src/client/toolkit-refactor/slices/mockServerSlice.ts
rename to src/client/rtk/slices/mockServerSlice.ts
diff --git a/src/client/toolkit-refactor/slices/newRequestFieldsSlice.ts b/src/client/rtk/slices/newRequestFieldsSlice.ts
similarity index 97%
rename from src/client/toolkit-refactor/slices/newRequestFieldsSlice.ts
rename to src/client/rtk/slices/newRequestFieldsSlice.ts
index 7346c08c1..11f89f13d 100644
--- a/src/client/toolkit-refactor/slices/newRequestFieldsSlice.ts
+++ b/src/client/rtk/slices/newRequestFieldsSlice.ts
@@ -8,7 +8,7 @@
*
* @todo refactor request type state into a single state with descrete options
*/
-import { NewRequestFields } from '../../../types';
+import { type NewRequestFields } from '~/types';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { composerFieldsReset } from './newRequestSlice';
@@ -95,7 +95,7 @@ const newRequestFieldsSlice = createSlice({
...initialState,
url: '',
method: 'GET',
- network: 'openapi',
+ network: 'openApi',
};
}
case 'grpc': {
diff --git a/src/client/toolkit-refactor/slices/newRequestOpenApiSlice.ts b/src/client/rtk/slices/newRequestOpenApiSlice.ts
similarity index 99%
rename from src/client/toolkit-refactor/slices/newRequestOpenApiSlice.ts
rename to src/client/rtk/slices/newRequestOpenApiSlice.ts
index bafdffc64..a30d44d88 100644
--- a/src/client/toolkit-refactor/slices/newRequestOpenApiSlice.ts
+++ b/src/client/rtk/slices/newRequestOpenApiSlice.ts
@@ -10,7 +10,7 @@
import { assertTypeExhaustion } from '../../../helpers';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { compose } from 'redux';
-import { $NotUsed, $TSFixMe } from '../../../types';
+import { type $NotUsed, type $TSFixMe } from '~/types';
/**
* Describes a single element within the NewRequestOpenApi type's array of
@@ -103,7 +103,7 @@ const newRequestOpenApiSlice = createSlice({
/**
* This is for removing servers from the openAPI composer. Specifically,
- * the OpenAPIServerForm.tsx. It isn't working as intended, and would be
+ * the OpenAPIServerForm.tsx. It isn't working as intended, and would be
* great to get up and running
*/
serversRemovedByIndex(state, action: PayloadAction) {
diff --git a/src/client/toolkit-refactor/slices/newRequestSlice.ts b/src/client/rtk/slices/newRequestSlice.ts
similarity index 88%
rename from src/client/toolkit-refactor/slices/newRequestSlice.ts
rename to src/client/rtk/slices/newRequestSlice.ts
index 09f8d5515..4b87e92b8 100644
--- a/src/client/toolkit-refactor/slices/newRequestSlice.ts
+++ b/src/client/rtk/slices/newRequestSlice.ts
@@ -1,10 +1,10 @@
/**
- * @file Defines the slice for the new requests
+ * @file Defines the Redux slice for processing new requests (e.g., request
+ * body and header information).
*
- * slice contains request body and header information
- *
- * @todo should be combined with new Request fields slice as the data related to constructing
- * each request is associated
+ * @todo This should probably be combined with the Request fields slice, as all
+ * the data is highly interrelated. The fields slice has a Redux extra reducer
+ * set up to listen for changes here, too.
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
@@ -15,9 +15,9 @@ import {
NewRequestSSE,
CookieOrHeader,
RequestWebRTC,
-} from '../../../types';
+} from '~/types';
-type NewRequestStore = {
+export type NewRequestState = {
newRequestHeaders: {
headersArr: CookieOrHeader[];
count: number;
@@ -30,10 +30,9 @@ type NewRequestStore = {
newRequestBody: NewRequestBody;
newRequestSSE: NewRequestSSE;
newRequestWebRTC: RequestWebRTC;
-
};
-const initialState: NewRequestStore = {
+const initialState: NewRequestState = {
newRequestHeaders: {
headersArr: [],
count: 0,
@@ -47,7 +46,7 @@ const initialState: NewRequestStore = {
bodyIsNew: false,
},
newRequestStreams: {
- streamsArr: [],
+ streamsArr: [],
count: 0,
streamContent: [],
selectedPackage: null,
@@ -79,7 +78,7 @@ const initialState: NewRequestStore = {
webRTCLocalStream: null,
webRTCRemoteStream: null,
webRTCMessages: [],
- }
+ },
};
const newRequestSlice = createSlice({
@@ -89,7 +88,7 @@ const newRequestSlice = createSlice({
//Before toolkit conversion was SET_NEW_REQUEST_HEADERS or setNewRequestHeaders
newRequestHeadersSet: (
state,
- action: PayloadAction
+ action: PayloadAction
) => {
state.newRequestHeaders = action.payload;
},
@@ -106,7 +105,6 @@ const newRequestSlice = createSlice({
state.newRequestWebRTC.webRTCOffer = action.payload;
},
-
//Before toolkit conversion was SET_NEW_REQUEST_STREAMS or setNewRequestStreams
newRequestStreamsSet: (state, action: PayloadAction) => {
state.newRequestStreams = action.payload;
@@ -115,7 +113,7 @@ const newRequestSlice = createSlice({
//Before toolkit conversion was SET_NEW_REQUEST_COOKIES or setNewRequestCookies
newRequestCookiesSet: (
state,
- action: PayloadAction
+ action: PayloadAction
) => {
state.newRequestCookies = action.payload;
},
@@ -134,8 +132,8 @@ const newRequestSlice = createSlice({
newRequestContentByProtocol: (
state,
action: PayloadAction
- ): NewRequestStore => {
- const composeNewRequestStore = (bodyType: string): NewRequestStore => {
+ ): NewRequestState => {
+ const composeNewRequestStore = (bodyType: string): NewRequestState => {
return {
...initialState,
newRequestBody: {
diff --git a/src/client/toolkit-refactor/slices/reqResSlice.ts b/src/client/rtk/slices/reqResSlice.ts
similarity index 98%
rename from src/client/toolkit-refactor/slices/reqResSlice.ts
rename to src/client/rtk/slices/reqResSlice.ts
index ca050680c..8226de5ba 100644
--- a/src/client/toolkit-refactor/slices/reqResSlice.ts
+++ b/src/client/rtk/slices/reqResSlice.ts
@@ -3,9 +3,9 @@
* arrays and associated values.
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
-import { ReqRes } from '../../../types';
+import { type ReqRes } from '~/types';
-/**
+/**
* @todo based on current useage type def is innaccurate or incomplete
* currentReponse stores the last returned ReqRes type
* in theory currentResponse property is unnessecary as the last element in the
diff --git a/src/client/toolkit-refactor/slices/uiSlice.ts b/src/client/rtk/slices/uiSlice.ts
similarity index 87%
rename from src/client/toolkit-refactor/slices/uiSlice.ts
rename to src/client/rtk/slices/uiSlice.ts
index 2b96f7070..e176bb2cc 100644
--- a/src/client/toolkit-refactor/slices/uiSlice.ts
+++ b/src/client/rtk/slices/uiSlice.ts
@@ -20,8 +20,13 @@ interface UiState {
}
const initialState: UiState = {
- sidebarActiveTab: 'composer',
+ /**
+ * @todo 2023-08-31 - From a cursory glance, it seems that the value of this
+ * property will only ever be "workspace". Not sure if there was ever any
+ * intention to add support for other values, too.
+ */
workspaceActiveTab: 'workspace',
+ sidebarActiveTab: 'composer',
responsePaneActiveTab: 'events',
isDark: false,
};
diff --git a/src/client/toolkit-refactor/slices/warningMessageSlice.ts b/src/client/rtk/slices/warningMessageSlice.ts
similarity index 66%
rename from src/client/toolkit-refactor/slices/warningMessageSlice.ts
rename to src/client/rtk/slices/warningMessageSlice.ts
index deb0005d8..051904071 100644
--- a/src/client/toolkit-refactor/slices/warningMessageSlice.ts
+++ b/src/client/rtk/slices/warningMessageSlice.ts
@@ -3,18 +3,9 @@
* object and associated values.
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
-import { $NotUsed } from '../../../types';
+import { type $NotUsed } from '~/types';
-//define type for warning message object
-
-// //from test file
-// const fakeWarningMessage = {
-// err: `you can't do this to me`,
-// };
-// if (warningMessage.uri) { //so warning message obj has uri property??
-// {warningMessage ? {warningMessage.body}
: null} //has body property??
-
-type WarningMessage = Partial<{
+export type WarningMessage = Partial<{
err: string;
uri: string;
body: string;
diff --git a/src/client/rtk/store.ts b/src/client/rtk/store.ts
new file mode 100644
index 000000000..552006469
--- /dev/null
+++ b/src/client/rtk/store.ts
@@ -0,0 +1,76 @@
+/**
+ * Defines the top-level Redux store that should be used throughout the entire
+ * app for global state, as well as any related utiliites.
+ * {@link https://redux-toolkit.js.org/}
+ *
+ * Please do not put any arbitrary state values in here. useState and useReducer
+ * can be used for state that only belongs to one component. Form state should
+ * almost never go in here. Redux state is still global state, and even when you
+ * opt into Redux's Flux Standard Actions approach, it can be hard to debug.
+ *
+ * Also, please do not use the raw useSelector or useDispatch hooks from the
+ * react-redux library. These are not type-safe. Use the useAppSelector and
+ * useAppDispatch hooks exported here. They work the same, but have type safety.
+ *
+ * Reminder: all values in a Redux store must be JSON-serializable values in
+ * order to be proper. Only these types are valid (defined recursively):
+ * - Strings
+ * - Numbers
+ * - Booleans
+ * - null
+ * - Arrays of JSON values
+ * - Objects of JSON values (instantiated objects like Date are not allowed)
+ *
+ * All other values (including undefined and functions) are not valid.
+ *
+ * @todo With that said, parts of the Redux store still have Date objects, and
+ * by default, Redux will yell at you. In practice, it shouldn't cause problems
+ * (trying to access a Date object as a string will automatically call its
+ * .toString method on it), but because Redux doesn't know that, it'll keep
+ * yelling. All Dates should be replaced with date strings or timestamp numbers
+ */
+import { configureStore } from '@reduxjs/toolkit';
+import rootReducer from './rootReducer';
+import {
+ type TypedUseSelectorHook,
+ useSelector,
+ useDispatch,
+} from 'react-redux';
+
+/**
+ * The top-level redux store.
+ */
+const store = configureStore({
+ reducer: rootReducer,
+ devTools: process.env.NODE_ENV !== 'production',
+ middleware: (getDefaultMiddleware) =>
+ getDefaultMiddleware({
+ /**
+ * @todo Remove any non-serializable values from the store (namely,
+ * replace Date objects with strings/numbers), and flip this to true.
+ */
+ serializableCheck: false,
+ }),
+});
+
+export type RootState = ReturnType;
+export type AppDispatch = typeof store.dispatch;
+
+/**
+ * The Redux store's dispatch function, exposed directly; needed for files that
+ * are not React function components.
+ */
+export const appDispatch = store.dispatch;
+
+/**
+ * A type-safe version of React-Redux's useDispatch hook.
+ */
+export const useAppDispatch: () => AppDispatch = useDispatch;
+
+/**
+ * A type-safe version of React-Redux's useSelector hook.
+ */
+export const useAppSelector: TypedUseSelectorHook = useSelector;
+
+export default store;
+
diff --git a/src/client/toolkit-refactor/store.ts b/src/client/toolkit-refactor/store.ts
deleted file mode 100644
index 36fdaf681..000000000
--- a/src/client/toolkit-refactor/store.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Defines the top-level Redux store that should be used throughout the entire
- * app for non-model data.
- * {@link https://redux-toolkit.js.org/}
- *
- * Please do not put temporary form state in the store. All of that can be done
- * with local state management, via things like React hooks and the Context API.
- *
- * @todo Replace all instances of Date objects in the Redux store with timestamp
- * strings. Redux will complain that the data isn't serializable, because Dates
- * aren't part of the JSON spec, but when you call JSON.stringify on an object
- * that contains Dates, they'll automatically have their .toString method
- * called, turning them into timestamp strings.
- *
- * So basically, the data technically is serializable, but Redux can't tell that
- * and will keep yelling at you in the console until all the Dates are replaced.
- */
-import { configureStore } from '@reduxjs/toolkit';
-import { useDispatch } from 'react-redux';
-import rootReducer from './rootReducer';
-
-/**
- * The top-level redux store. serializableCheck was previously turned off, which
- * stops Redux from complaining at you, but the Redux store should only have
- * serializable JSON values where possible.
- *
- * @todo Remove any non-serializable values from the store (namely, replace
- * Date objects with Date strings).
- */
-const store = configureStore({
- reducer: rootReducer,
- devTools: process.env.NODE_ENV !== 'production',
- middleware: (getDefaultMiddleware) =>
- getDefaultMiddleware({
- serializableCheck: false,
- }),
-});
-
-export type RootState = ReturnType;
-export type AppDispatch = typeof store.dispatch;
-
-/**
- * A type-safe version of React-Redux's useDispatch hook.
- */
-export const useAppDispatch: () => AppDispatch = useDispatch;
-
-/**
- * The Redux store's dispatch function, exposed directly; needed for files that
- * are not React functional components.
- */
-export const appDispatch = store.dispatch;
-export default store;
-
diff --git a/src/index.js b/src/index.js
index 7e3d2fc35..e4f4c48fe 100644
--- a/src/index.js
+++ b/src/index.js
@@ -4,10 +4,10 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
-import { Provider } from 'react-redux';
+import { Provider as ReduxProvider } from 'react-redux';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import App from './client/components/App';
-import store from './client/toolkit-refactor/store';
+import store from '~/toolkit/store';
import { CssBaseline } from '@mui/material';
@@ -46,26 +46,37 @@ default-src 'self' http://localhost:3000 ws://localhost:3000 https://api.github.
child-src 'none';
`;
- //
- const otherMeta = document.createElement('otherMeta')
- otherMeta.content = ` `
- //meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'; script-src 'self' 'unsafe-eval'"
+//
+const otherMeta = document.createElement('otherMeta');
+otherMeta.content = ` `;
+//meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'; script-src 'self' 'unsafe-eval'"
head.appendChild(meta);
// Render the app
const container = document.getElementById('root');
-const rt = createRoot(container);
+if (container === null) {
+ throw new Error('Missing root container');
+}
-// Created this method to allow Redux State to be accessible in Integration testing
-window.getReduxState = () => store.getState();
+const reactRoot = createRoot(container);
+/**
+ * @todo This line is only needed for the integration testing, so it should be
+ * moved to those files. As a general tip, directly modifying the global scope
+ * is far less safer than accessing a value through a JS module, and has more
+ * security risks.
+ *
+ * Moving this into the files also gives Jest the chance to clean up this setup
+ * step afterwards (via beforeAll/afterAll).
+ */
+window.getReduxState = () => store.getState();
-rt.render(
+reactRoot.render(
-
+
-
+
);
diff --git a/src/types.ts b/src/types.ts
index d8c0065c5..bf55a7263 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,8 +1,19 @@
/**
* @file Defines a collection of types that are meant to be used through the
- * TypeScript application. Not all types need to be here, especially if some
- * type information only makes sense for internal implementations, but most of
- * them should be here.
+ * TypeScript application.
+ *
+ * Warning to new developers: having every single type in one file is a very bad
+ * anti-pattern. Types should be co-located as closely to where they're used as
+ * possible. For example, if a type is most relevant for only a specific Slice
+ * in a Redux store, that type should be defined there, and exported if
+ * necessary.
+ *
+ * That way, everything related to each other is in one file, and if you ever
+ * need to delete a feature, you can safely delete that one file without
+ * needing to hunt anything down.
+ *
+ * @todo Start breaking this file up and put the types where they're used. As of
+ * 2023-08-30, this file is 400+ lines long; it is impossible to read.
*/
import { GraphQLSchema } from 'graphql';
@@ -93,34 +104,6 @@ export interface ValidationMessage {
json?: string;
}
-export interface MainContainerProps {
- // state
- currentTab?: string;
- reqResArray: ReqRes[];
- newRequestFields: NewRequestFields;
- newRequestHeaders: NewRequestHeaders;
- newRequestStreams: NewRequestStreams;
- newRequestBody: NewRequestBody;
- newRequestCookies: NewRequestCookies;
- newRequestSSE: NewRequestSSE;
- warningMessage: any;
- introspectionData: IntrospectionData;
-
- // reducers
- reqResItemAdded: (reqRes: ReqRes) => any;
- setWarningMessage: (message: ValidationMessage) => any;
- newRequestHeadersSet: NewRequestHeadersSet;
- newRequestStreamsSet: () => any;
- fieldsReplaced: () => any;
- newRequestBodySet: NewRequestBodySet;
- newTestContentSet: () => any;
- newRequestCookiesSet: NewRequestCookiesSet;
- newRequestSSESet: (arg: boolean) => any;
- openApiRequestsReplaced: () => any;
- composerFieldsReset: () => any;
- setWorkspaceActiveTab: (arg: string) => any;
-}
-
export interface GraphQLResponse {
reqResObj: ReqRes;
@@ -322,6 +305,7 @@ export interface RequestWebRTCVideo {
webRTCpeerConnection: RTCPeerConnection | null;
webRTCLocalStream: MediaStream | null;
webRTCRemoteStream: MediaStream | null;
+ method?: string;
}
export interface RequestWebRTCText {
@@ -335,6 +319,7 @@ export interface RequestWebRTCText {
webRTCLocalStream: RTCDataChannel | null;
webRTCRemoteStream: RTCDataChannel | null;
webRTCMessages: WebMessages[];
+ method?: string;
}
export interface NewRequestSSE {
diff --git a/test/__tests__/collectionsSliceTest.js b/test/__tests__/collectionsSliceTest.js
index 2cdde1282..deb8195a7 100644
--- a/test/__tests__/collectionsSliceTest.js
+++ b/test/__tests__/collectionsSliceTest.js
@@ -5,125 +5,156 @@
* be due to the actual slice syntax using if statements without a default return case.
*/
-import collectionsSliceReducer,
- { collectionsReplaced,
- collectionDeleted,
- collectionAdded,
- collectionUpdated } from '../../src/client/toolkit-refactor/slices/collectionsSlice';
+import collectionsSliceReducer, {
+ collectionsReplaced,
+ collectionDeleted,
+ collectionAdded,
+ collectionUpdated,
+} from '../../src/client/rtk/slices/collectionsSlice';
describe('collectionsSliceReducer', () => {
- let initialState;
+ let initialState;
- beforeEach(() => {
- initialState = [{
- id: 1,
- name: 'collectionTestOne',
- createdAt: '2022-01-01T00:00:00.000Z',
- modifiedAt: '2023-02-01T00:00:00.000Z',
- reqResArray: [{
- id: 123
- }],
- reqResRequest: [{
- body: 'reqResRequest collections test one'
- }]
- }];
- });
+ beforeEach(() => {
+ initialState = [
+ {
+ id: 1,
+ name: 'collectionTestOne',
+ createdAt: '2022-01-01T00:00:00.000Z',
+ modifiedAt: '2023-02-01T00:00:00.000Z',
+ reqResArray: [
+ {
+ id: 123,
+ },
+ ],
+ reqResRequest: [
+ {
+ body: 'reqResRequest collections test one',
+ },
+ ],
+ },
+ ];
+ });
- describe('collectionsReplaced', () => {
- it('should replace the current collections obj with a new one', () => {
- const newCollectionState = [{
- id: 2,
- name: 'collectionTestTwo',
- createdAt: '2022-01-01T00:00:00.000Z',
- modifiedAt: '2023-02-01T00:00:00.000Z',
- reqResArray: [{
- id: 321
- }],
- reqResRequest: [{
- body: 'reqResRequest collections test two'
- }]
- }];
+ describe('collectionsReplaced', () => {
+ it('should replace the current collections obj with a new one', () => {
+ const newCollectionState = [
+ {
+ id: 2,
+ name: 'collectionTestTwo',
+ createdAt: '2022-01-01T00:00:00.000Z',
+ modifiedAt: '2023-02-01T00:00:00.000Z',
+ reqResArray: [
+ {
+ id: 321,
+ },
+ ],
+ reqResRequest: [
+ {
+ body: 'reqResRequest collections test two',
+ },
+ ],
+ },
+ ];
- const newState = collectionsSliceReducer(
- initialState,
- collectionsReplaced(newCollectionState)
- );
+ const newState = collectionsSliceReducer(
+ initialState,
+ collectionsReplaced(newCollectionState)
+ );
- expect(newState).toBe(newCollectionState);
- });
+ expect(newState).toBe(newCollectionState);
});
+ });
- describe('collectionDeleted', () => {
- it('should delete the requested collection object by ID and position index', () => {
- const newCollectionState = [{
- id: 2,
- name: 'collectionTestTwo',
- createdAt: '2022-01-01T00:00:00.000Z',
- modifiedAt: '2023-02-01T00:00:00.000Z',
- reqResArray: [{
- id: 321
- }],
- reqResRequest: [{
- body: 'reqResRequest collections test two'
- }]
- }];
- initialState.push(newCollectionState);
- const newState = collectionsSliceReducer(
- initialState,
- collectionDeleted(initialState[0])
- );
+ describe('collectionDeleted', () => {
+ it('should delete the requested collection object by ID and position index', () => {
+ const newCollectionState = [
+ {
+ id: 2,
+ name: 'collectionTestTwo',
+ createdAt: '2022-01-01T00:00:00.000Z',
+ modifiedAt: '2023-02-01T00:00:00.000Z',
+ reqResArray: [
+ {
+ id: 321,
+ },
+ ],
+ reqResRequest: [
+ {
+ body: 'reqResRequest collections test two',
+ },
+ ],
+ },
+ ];
+ initialState.push(newCollectionState);
+ const newState = collectionsSliceReducer(
+ initialState,
+ collectionDeleted(initialState[0])
+ );
- expect(newState.length).toBe(1);
- });
- })
+ expect(newState.length).toBe(1);
+ });
+ });
- describe('collectionAdded', () => {
- it('should add a new collections object to the beginning of the state', () => {
- const newCollectionState = [{
- id: 2,
- name: 'collectionTestTwo',
- createdAt: '2022-01-01T00:00:00.000Z',
- modifiedAt: '2023-02-01T00:00:00.000Z',
- reqResArray: [{
- id: 321
- }],
- reqResRequest: [{
- body: 'reqResRequest collections test two'
- }]
- }];
+ describe('collectionAdded', () => {
+ it('should add a new collections object to the beginning of the state', () => {
+ const newCollectionState = [
+ {
+ id: 2,
+ name: 'collectionTestTwo',
+ createdAt: '2022-01-01T00:00:00.000Z',
+ modifiedAt: '2023-02-01T00:00:00.000Z',
+ reqResArray: [
+ {
+ id: 321,
+ },
+ ],
+ reqResRequest: [
+ {
+ body: 'reqResRequest collections test two',
+ },
+ ],
+ },
+ ];
- const newState = collectionsSliceReducer(
- initialState,
- collectionAdded(newCollectionState)
- );
+ const newState = collectionsSliceReducer(
+ initialState,
+ collectionAdded(newCollectionState)
+ );
- expect(newState[0]).toBe(newCollectionState);
- });
+ expect(newState[0]).toBe(newCollectionState);
});
+ });
- describe('collectionsUpdated', () => {
- it('should update the request collection object by ID', () => {
- const newCollectionState = [{
- id: 2,
- name: 'collectionTestOne',
- createdAt: '2022-01-01T00:00:00.000Z',
- modifiedAt: '2023-02-01T00:00:00.000Z',
- reqResArray: [{
- id: 321
- }],
- reqResRequest: [{
- body: 'reqResRequest collections test two'
- }]
- }];
+ describe('collectionsUpdated', () => {
+ it('should update the request collection object by ID', () => {
+ const newCollectionState = [
+ {
+ id: 2,
+ name: 'collectionTestOne',
+ createdAt: '2022-01-01T00:00:00.000Z',
+ modifiedAt: '2023-02-01T00:00:00.000Z',
+ reqResArray: [
+ {
+ id: 321,
+ },
+ ],
+ reqResRequest: [
+ {
+ body: 'reqResRequest collections test two',
+ },
+ ],
+ },
+ ];
- const newState = collectionsSliceReducer(
- initialState,
- collectionUpdated(newCollectionState[0])
- );
+ const newState = collectionsSliceReducer(
+ initialState,
+ collectionUpdated(newCollectionState[0])
+ );
- expect(newState[0]).toBe(newCollectionState[0]);
- expect(newState.length).toBe(1);
-
- });
+ expect(newState[0]).toBe(newCollectionState[0]);
+ expect(newState.length).toBe(1);
});
-});
\ No newline at end of file
+ });
+});
+
diff --git a/test/__tests__/graphQLcontrollerTest.js b/test/__tests__/graphQLcontrollerTest.js
index 23b5c7df7..428b6204f 100644
--- a/test/__tests__/graphQLcontrollerTest.js
+++ b/test/__tests__/graphQLcontrollerTest.js
@@ -61,10 +61,10 @@ describe('graphQLController', () => {
describe('introspect', () => {
// mock the store
- jest.mock('../../src/client/toolkit-refactor/store');
+ jest.mock('../../src/client/rtk/store');
// mock the get
- jest.mock('../../src/client/toolkit-refactor/store', () => ({
+ jest.mock('../../src/client/rtk/store', () => ({
appDispatch: jest.fn(),
}));
diff --git a/test/__tests__/historyControllerTest.js b/test/__tests__/historyControllerTest.js
index d5e2c0dc7..48c098f07 100644
--- a/test/__tests__/historyControllerTest.js
+++ b/test/__tests__/historyControllerTest.js
@@ -1,10 +1,10 @@
import db from '../../src/client/db';
import historyController from '../../src/client/controllers/historyController';
-import { appDispatch } from '../../src/client/toolkit-refactor/store';
-import { historySet } from '../../src/client/toolkit-refactor/slices/historySlice';
+import { appDispatch } from '../../src/client/rtk/store';
+import { historySet } from '../../src/client/rtk/slices/historySlice';
jest.mock('../../src/client/db');
-jest.mock('../../src/client/toolkit-refactor/store');
+jest.mock('../../src/client/rtk/store');
describe('historyController', () => {
beforeEach(() => {
@@ -13,7 +13,12 @@ describe('historyController', () => {
describe('addHistoryToIndexedDb', () => {
it('adds a req/res to the db', () => {
- const reqRes = { id: '1', request: {}, response: {}, createdAt: new Date() };
+ const reqRes = {
+ id: '1',
+ request: {},
+ response: {},
+ createdAt: new Date(),
+ };
db.table.mockReturnValue({
put: jest.fn().mockResolvedValue(null),
@@ -56,7 +61,12 @@ describe('historyController', () => {
describe('getHistory', () => {
xit('gets req/res history from the db and dispatches them to the store', async () => {
- const reqRes = { id: '1', request: {}, response: {}, createdAt: new Date() };
+ const reqRes = {
+ id: '1',
+ request: {},
+ response: {},
+ createdAt: new Date(),
+ };
const history = [reqRes];
db.table.mockReturnValue({
@@ -87,7 +97,11 @@ describe('historyController', () => {
await historyController.getHistory();
- expect(console.error).toHaveBeenCalledWith('Error in getHistory', 'error');
+ expect(console.error).toHaveBeenCalledWith(
+ 'Error in getHistory',
+ 'error'
+ );
});
});
-});
\ No newline at end of file
+});
+
diff --git a/test/__tests__/historySliceTest.js b/test/__tests__/historySliceTest.js
index 51c87d027..a659b3a0d 100644
--- a/test/__tests__/historySliceTest.js
+++ b/test/__tests__/historySliceTest.js
@@ -8,7 +8,7 @@ import historySliceReducer, {
historyCleared,
historySet,
historyDeleted,
-} from '../../src/client/toolkit-refactor/slices/historySlice';
+} from '../../src/client/rtk/slices/historySlice';
describe('HistorySlice', () => {
let initialState;
@@ -60,15 +60,23 @@ describe('HistorySlice', () => {
describe('historyDeleted', () => {
xit('should delete the specified item from the history', () => {
- const action = { payload: { id: 1, createdAt: '2022-01-01T00:00:00.000Z' } };
- const newState = historySliceReducer(initialState, historyDeleted(action.payload));
+ const action = {
+ payload: { id: 1, createdAt: '2022-01-01T00:00:00.000Z' },
+ };
+ const newState = historySliceReducer(
+ initialState,
+ historyDeleted(action.payload)
+ );
const expectedState = [];
expect(newState).toEqual(expectedState);
});
it('should update the history when an item is deleted', () => {
const action = { payload: historyItem };
- const newState = historySliceReducer(initialState, historyDeleted(action.payload));
+ const newState = historySliceReducer(
+ initialState,
+ historyDeleted(action.payload)
+ );
const expectedState = [
{
date: '01/01/2022',
@@ -108,30 +116,31 @@ describe('HistorySlice', () => {
});
it('should add a new item to an existing history', () => {
- const newItem = {
- id: 3,
- createdAt: '2022-01-01T00:00:00.000Z',
- };
-
- const action = { payload: newItem };
- const newState = historySliceReducer(initialState, action);
- const expectedState = [
- {
- date: '01/01/2022',
- history: [
- {
- id: 3,
- createdAt: '2022-01-01T00:00:00.000Z',
- },
- {
- id: 1,
- createdAt: '2022-01-01T00:00:00.000Z',
- },
- ],
+ const newItem = {
+ id: 3,
+ createdAt: '2022-01-01T00:00:00.000Z',
+ };
+
+ const action = { payload: newItem };
+ const newState = historySliceReducer(initialState, action);
+ const expectedState = [
+ {
+ date: '01/01/2022',
+ history: [
+ {
+ id: 3,
+ createdAt: '2022-01-01T00:00:00.000Z',
},
- ];
-
- expect(newState).toEqual(expectedState);
- });
- });
- });
\ No newline at end of file
+ {
+ id: 1,
+ createdAt: '2022-01-01T00:00:00.000Z',
+ },
+ ],
+ },
+ ];
+
+ expect(newState).toEqual(expectedState);
+ });
+ });
+});
+
diff --git a/test/__tests__/introspectionDataSliceTest.js b/test/__tests__/introspectionDataSliceTest.js
index 1ad380cca..24d4f666b 100644
--- a/test/__tests__/introspectionDataSliceTest.js
+++ b/test/__tests__/introspectionDataSliceTest.js
@@ -4,21 +4,22 @@
* unless the slice itself was updated/edge cases found.
*/
-import IntrospectionDataReducer,
- { initialState,
- introspectionDataChanged } from '../../src/client/toolkit-refactor/slices/introspectionDataSlice';
+import IntrospectionDataReducer, {
+ initialState,
+ introspectionDataChanged,
+} from '../../src/client/rtk/slices/introspectionDataSlice';
describe('introspectionDataSlice', () => {
- it('state should be updated via new information received', () => {
- const testIntrospectionData = {
- schemaSDL: 'test one',
- clientSchema: {
- name: 'graphQL Schema name test',
- id: 1
- }
- }
- const action = introspectionDataChanged(testIntrospectionData);
- const sliceInitialState = IntrospectionDataReducer(initialState, action);
- expect(sliceInitialState).toBe(testIntrospectionData);
- });
-});
\ No newline at end of file
+ it('state should be updated via new information received', () => {
+ const testIntrospectionData = {
+ schemaSDL: 'test one',
+ clientSchema: {
+ name: 'graphQL Schema name test',
+ id: 1,
+ },
+ };
+ const action = introspectionDataChanged(testIntrospectionData);
+ const sliceInitialState = IntrospectionDataReducer(initialState, action);
+ expect(sliceInitialState).toBe(testIntrospectionData);
+ });
+});
diff --git a/test/__tests__/loadTestControllerTest.js b/test/__tests__/loadTestControllerTest.js
index bc4ee97fe..c9a4a430d 100644
--- a/test/__tests__/loadTestControllerTest.js
+++ b/test/__tests__/loadTestControllerTest.js
@@ -1,15 +1,15 @@
-import store, { appDispatch } from '../../src/client/toolkit-refactor/store';
+import store, { appDispatch } from '../../src/client/rtk/store';
+import { graphUpdated } from '../../src/client/rtk/slices/graphPointsSlice';
import {
responseDataSaved,
reqResUpdated,
-} from '../../src/client/toolkit-refactor/slices/reqResSlice';
-// import { ReqRes } from '../../types';
-import { LoadTestController } from '../../src/client/controllers/LoadTestController';
-// import { LoadTestResult } from '../components/main/new-request/stressTest/LoadTest';
-import { graphUpdated } from '../../src/client/toolkit-refactor/slices/graphPointsSlice';
+} from '../../src/client/rtk/slices/reqResSlice';
+
+import LoadTestController from '../../src/client/controllers/LoadTestController';
+import { LoadTestResult } from '../components/main/new-request/stressTest/LoadTest';
// mock the store
-jest.mock('../../src/client/toolkit-refactor/store');
+jest.mock('../../src/client/rtk/store');
describe('LoadTestController', () => {
// make sure to clear the mock before each test
@@ -92,3 +92,4 @@ describe('LoadTestController', () => {
});
});
});
+
diff --git a/test/__tests__/mockServerSliceTest.js b/test/__tests__/mockServerSliceTest.js
index cf09a2bb9..c761ff8f1 100644
--- a/test/__tests__/mockServerSliceTest.js
+++ b/test/__tests__/mockServerSliceTest.js
@@ -1,25 +1,27 @@
-/**
+/**
* @file Test to determine if the mockServerSlice reducer switches work.
* @todo - Check for possible edge cases
* Covereage is all at 100%, so possibly no need to update testing
* unless the slice itself was updated/edge cases found.
* **/
-import mockServerReducer,
- { initialState,
- startServer,
- stopServer } from '../../src/client/toolkit-refactor/slices/mockServerSlice';
+import mockServerReducer, {
+ initialState,
+ startServer,
+ stopServer,
+} from '../../src/client/rtk/slices/mockServerSlice';
describe('mockServerSlice', () => {
- it('state should be updated on server start', () => {
- const action = startServer();
- const sliceNewState = mockServerReducer(initialState, action);
- expect(sliceNewState.isServerStarted).toBe(true);
- });
+ it('state should be updated on server start', () => {
+ const action = startServer();
+ const sliceNewState = mockServerReducer(initialState, action);
+ expect(sliceNewState.isServerStarted).toBe(true);
+ });
+
+ it('state should be updated on server stop', () => {
+ const action = stopServer();
+ const sliceNewState = mockServerReducer(initialState, action);
+ expect(sliceNewState.isServerStarted).toBe(false);
+ });
+});
- it('state should be updated on server stop', () => {
- const action = stopServer();
- const sliceNewState = mockServerReducer(initialState, action);
- expect(sliceNewState.isServerStarted).toBe(false);
- });
-});
\ No newline at end of file
diff --git a/test/__tests__/newReqOpenApiSliceTest.js b/test/__tests__/newReqOpenApiSliceTest.js
index 5d1cc8c8d..365a24c52 100644
--- a/test/__tests__/newReqOpenApiSliceTest.js
+++ b/test/__tests__/newReqOpenApiSliceTest.js
@@ -3,11 +3,12 @@
* @todo - Look into increasing testing coverage to 100% across the board. The last test needs to be fixed as well.
*/
-import newRequestOpenApiReducer,
- { newServerAdded,
- newParameterAdded,
- serversRemovedByIndex,
- requestBodyUpdated } from '../../src/client/toolkit-refactor/slices/newRequestOpenApiSlice';
+import newRequestOpenApiReducer, {
+ newServerAdded,
+ newParameterAdded,
+ serversRemovedByIndex,
+ requestBodyUpdated,
+} from '../../src/client/rtk/slices/newRequestOpenApiSlice';
describe('newRequestOpenApiSlice', () => {
let initialState;
@@ -61,37 +62,39 @@ describe('newRequestOpenApiSlice', () => {
const state = newRequestOpenApiReducer(initialState, action);
expect(state.openApiReqArray).toHaveLength(2);
- expect(state.openApiReqArray[0].reqServers).toContain('https://example.org');
+ expect(state.openApiReqArray[0].reqServers).toContain(
+ 'https://example.org'
+ );
});
});
describe('serversRemovedByIndex', () => {
it('deletes a server given the appropriate request', () => {
//Here just in case, but dont' believe the below initialState and actionPayloadTest are needed for this test
- // const initialState = {
- // openApiMetadata: {
- // info: {},
- // tags: [],
- // serverUrls: ['https://example.com', 'https://example.org'],
- // },
- // openApiReqArray: [
- // {
- // request: {
- // id: 1,
- // },
- // headers: [],
- // urls: ['https://example.com/test'],
- // endpoint: '/test',
- // reqServers: ['https://example.com'],
- // serverIds: [0],
- // cookies: '',
- // method: 'get',
- // body: '',
- // mediaType: '',
- // rawType: '',
- // },
- // ],
- // };
+ // const initialState = {
+ // openApiMetadata: {
+ // info: {},
+ // tags: [],
+ // serverUrls: ['https://example.com', 'https://example.org'],
+ // },
+ // openApiReqArray: [
+ // {
+ // request: {
+ // id: 1,
+ // },
+ // headers: [],
+ // urls: ['https://example.com/test'],
+ // endpoint: '/test',
+ // reqServers: ['https://example.com'],
+ // serverIds: [0],
+ // cookies: '',
+ // method: 'get',
+ // body: '',
+ // mediaType: '',
+ // rawType: '',
+ // },
+ // ],
+ // };
// const newServer = {
// request: {
// id: 1,
@@ -119,7 +122,9 @@ describe('newRequestOpenApiSlice', () => {
const state = newRequestOpenApiReducer(initialState, action);
expect(state.openApiReqArray).toHaveLength(1);
- expect(state.openApiReqArray[0].reqServers[0]).toContain('https://example.com');
+ expect(state.openApiReqArray[0].reqServers[0]).toContain(
+ 'https://example.com'
+ );
});
});
@@ -129,12 +134,14 @@ describe('newRequestOpenApiSlice', () => {
id: 1,
location: 'header',
name: 'testHeaderParameter',
- value: 333
+ value: 333,
};
let action = newParameterAdded(newParams);
let newState = newRequestOpenApiReducer(initialState, action);
- expect(newState.openApiReqArray[0].headers[0].name).toEqual(newParams.value);
+ expect(newState.openApiReqArray[0].headers[0].name).toEqual(
+ newParams.value
+ );
newParams.location = 'cookie';
action = newParameterAdded(newParams);
@@ -144,14 +151,15 @@ describe('newRequestOpenApiSlice', () => {
newParams.location = 'query';
action = newParameterAdded(newParams);
newState = newRequestOpenApiReducer(initialState, action);
- expect(newState.openApiReqArray[0].urls[0]).toContain('testHeaderParameter=333');
+ expect(newState.openApiReqArray[0].urls[0]).toContain(
+ 'testHeaderParameter=333'
+ );
newParams.location = 'path';
newParams.name = 'example';
action = newParameterAdded(newParams);
newState = newRequestOpenApiReducer(initialState, action);
expect(newState.openApiReqArray[0].urls[0]).toContain(newParams.value);
-
});
});
@@ -162,8 +170,8 @@ describe('newRequestOpenApiSlice', () => {
const newMediaInfo = {
requestId: 1,
mediaType: 'test123',
- requestBody: 'anyTest321'
- }
+ requestBody: 'anyTest321',
+ };
const action = requestBodyUpdated(newMediaInfo);
const state = newRequestOpenApiReducer(initialState, action);
@@ -171,4 +179,4 @@ describe('newRequestOpenApiSlice', () => {
expect(state.openApiReqArray.length).toEqual(2);
});
});
-});
\ No newline at end of file
+});
diff --git a/test/__tests__/newRequestFieldsSliceTest.js b/test/__tests__/newRequestFieldsSliceTest.js
index b5c82a866..cf48595a6 100644
--- a/test/__tests__/newRequestFieldsSliceTest.js
+++ b/test/__tests__/newRequestFieldsSliceTest.js
@@ -4,141 +4,170 @@
* @todo - Look into increasing test coverage across the boad to 100%
*/
-import newRequestFieldsReducer,
- { fieldsReplaced,
- newTestContentSet,
- newRequestFieldsByProtocol } from '../../src/client/toolkit-refactor/slices/newRequestFieldsSlice';
+import newRequestFieldsReducer, {
+ fieldsReplaced,
+ newTestContentSet,
+ newRequestFieldsByProtocol,
+} from '../../src/client/rtk/slices/newRequestFieldsSlice';
describe('newRequestFieldsSlice', () => {
- let initialState;
-
- beforeEach(() => {
- initialState = {
- protocol: '',
- method: 'GET',
- network: 'rest',
- url: 'http://',
- restUrl: 'http://',
- wsUrl: 'ws://',
- gqlUrl: 'https://',
- grpcUrl: '',
- webrtcUrl: '',
- graphQL: false,
- gRPC: false,
- tRPC: false,
- ws: false,
- openapi: false,
- webrtc: false,
- webhook: false,
- testContent: '',
- testResults: [],
- openapiReqObj: {},
- };
- });
-
- describe('fieldsReplaced', () => {
- it('should replace fields in the request', () => {
- let testState = {
- ...initialState,
- method: 'POST',
- wsURL: 'wsL//test',
- tRPC: true,
- testResults: ['testOne'],
- openapiReqObj: {testTwo: 'obj testTwo'}
- }
-
- const action = fieldsReplaced(testState);
- const newState = newRequestFieldsReducer(initialState, action);
- expect(newState).toBe(testState);
- });
+ let initialState;
+
+ beforeEach(() => {
+ initialState = {
+ protocol: '',
+ method: 'GET',
+ network: 'rest',
+ url: 'http://',
+ restUrl: 'http://',
+ wsUrl: 'ws://',
+ gqlUrl: 'https://',
+ grpcUrl: '',
+ webrtcUrl: '',
+ graphQL: false,
+ gRPC: false,
+ tRPC: false,
+ ws: false,
+ openapi: false,
+ webrtc: false,
+ webhook: false,
+ testContent: '',
+ testResults: [],
+ openapiReqObj: {},
+ };
+ });
+
+ describe('fieldsReplaced', () => {
+ it('should replace fields in the request', () => {
+ let testState = {
+ ...initialState,
+ method: 'POST',
+ wsURL: 'wsL//test',
+ tRPC: true,
+ testResults: ['testOne'],
+ openapiReqObj: { testTwo: 'obj testTwo' },
+ };
+
+ const action = fieldsReplaced(testState);
+ const newState = newRequestFieldsReducer(initialState, action);
+ expect(newState).toBe(testState);
});
+ });
- describe('newTestContentSet', () => {
- it('should replace test content field based on user input', () => {
- const action = newTestContentSet('testingContentSet');
- const newState = newRequestFieldsReducer(initialState, action);
- expect(newState.testContent).toEqual(action.payload);
- });
+ describe('newTestContentSet', () => {
+ it('should replace test content field based on user input', () => {
+ const action = newTestContentSet('testingContentSet');
+ const newState = newRequestFieldsReducer(initialState, action);
+ expect(newState.testContent).toEqual(action.payload);
});
+ });
+
+ //The below test syntax can be updated for DRY.
+ describe('newRequestFieldsByProtocol', () => {
+ it('should update the request fields based on given protocol', () => {
+ let expected = {
+ ...initialState,
+ url: initialState.restUrl,
+ tRPC: true,
+ };
+
+ //Testing tRPC
+ expected.method = 'Query/Mutate';
+ let result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('tRPC')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing graphQL
+ expected.url = initialState.gqlUrl;
+ expected.tRPC = false;
+ expected.graphQL = true;
+ expected.method = 'QUERY';
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('graphQL')
+ );
+ expect(result).toEqual(expected);
- //The below test syntax can be updated for DRY.
- describe('newRequestFieldsByProtocol', () => {
- it('should update the request fields based on given protocol', () => {
- let expected = {
- ...initialState,
- url: initialState.restUrl,
- tRPC: true,
- };
-
- //Testing tRPC
- expected.method = 'Query/Mutate';
- let result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('tRPC'));
- expect(result).toEqual(expected);
-
- //Testing graphQL
- expected.url = initialState.gqlUrl;
- expected.tRPC = false;
- expected.graphQL = true;
- expected.method = 'QUERY';
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('graphQL'));
- expect(result).toEqual(expected);
-
- //Testing rest
- expected.url = 'http://';
- expected.graphQL = false;
- expected.method = 'GET';
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('rest'));
- expect(result).toEqual(expected);
-
- //Testing openAPI
- expected.url = '';
- expected.method = 'GET';
- expected.network = 'openapi';
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('openapi'));
- expect(result).toEqual(expected);
-
- //Testing gRPC
- expected.url = initialState.grpcUrl;
- expected.method = '';
- expected.network = initialState.network;
- expected.gRPC = true;
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('grpc'));
- expect(result).toEqual(expected);
-
- //Testing ws
- expected.url = initialState.wsUrl;
- expected.method = '';
- expected.network = 'ws';
- expected.gRPC = false;
- //Maybe I'm misunderstanding, but in the slice they have ws as false?
- //Changing to false here to pass the test and move-on.
- expected.ws = false;
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('ws'));
- expect(result).toEqual(expected);
-
- //Testing webrtc
- expected.url = initialState.webrtcUrl;
- expected.method = 'WebRTC';
- expected.network = initialState.network;
- expected.ws = false;
- expected.webrtc = true;
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('webrtc'));
- expect(result).toEqual(expected);
-
- //Testing webrtc
- expected.url = '';
- expected.method = 'Webhook';
- expected.webrtc = false;
- expected.webhook = true;
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('webhook'));
- expect(result).toEqual(expected);
-
- //Testing mock
- expected.url = '';
- expected.method = 'GET';
- expected.webhook = false;
- result = newRequestFieldsReducer(initialState, newRequestFieldsByProtocol('mock'));
- expect(result).toEqual(expected);
- });
+ //Testing rest
+ expected.url = 'http://';
+ expected.graphQL = false;
+ expected.method = 'GET';
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('rest')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing openAPI
+ expected.url = '';
+ expected.method = 'GET';
+ expected.network = 'openapi';
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('openapi')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing gRPC
+ expected.url = initialState.grpcUrl;
+ expected.method = '';
+ expected.network = initialState.network;
+ expected.gRPC = true;
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('grpc')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing ws
+ expected.url = initialState.wsUrl;
+ expected.method = '';
+ expected.network = 'ws';
+ expected.gRPC = false;
+ //Maybe I'm misunderstanding, but in the slice they have ws as false?
+ //Changing to false here to pass the test and move-on.
+ expected.ws = false;
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('ws')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing webrtc
+ expected.url = initialState.webrtcUrl;
+ expected.method = 'WebRTC';
+ expected.network = initialState.network;
+ expected.ws = false;
+ expected.webrtc = true;
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('webrtc')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing webrtc
+ expected.url = '';
+ expected.method = 'Webhook';
+ expected.webrtc = false;
+ expected.webhook = true;
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('webhook')
+ );
+ expect(result).toEqual(expected);
+
+ //Testing mock
+ expected.url = '';
+ expected.method = 'GET';
+ expected.webhook = false;
+ result = newRequestFieldsReducer(
+ initialState,
+ newRequestFieldsByProtocol('mock')
+ );
+ expect(result).toEqual(expected);
});
-});
\ No newline at end of file
+ });
+});
+
diff --git a/test/__tests__/newRequestSliceTest.js b/test/__tests__/newRequestSliceTest.js
index ecf009417..6d2a825db 100644
--- a/test/__tests__/newRequestSliceTest.js
+++ b/test/__tests__/newRequestSliceTest.js
@@ -15,7 +15,7 @@ import newRequestReducer, {
newRequestContentByProtocol,
newRequestWebRTCSet,
newRequestWebRTCOfferSet,
-} from '../../src/client/toolkit-refactor/slices/newRequestSlice';
+} from '../../src/client/rtk/slices/newRequestSlice';
describe('newRequestSlice', () => {
let initialState;
@@ -195,7 +195,7 @@ describe('newRequestSlice', () => {
newRequestContentByProtocol('grpc')
);
expect(result).toEqual(expected);
-
+
expected.newRequestBody.bodyType = 'none';
result = newRequestReducer(
initialState,
@@ -225,19 +225,20 @@ describe('newRequestSlice', () => {
webRTCLocalStream: null,
webRTCRemoteStream: null,
webRTCMessages: [],
- }
- const action = newRequestWebRTCSet(newWebRTCRequest)
+ };
+ const action = newRequestWebRTCSet(newWebRTCRequest);
const newState = newRequestReducer(initialState, action);
expect(newState.newRequestWebRTC).toBe(newWebRTCRequest);
- })
- })
+ });
+ });
describe('newRequestWebRTCOfferSet', () => {
it('should set new WebRTC offer', () => {
- const offerString = 'newOfferSDP'
- const action = newRequestWebRTCOfferSet(offerString)
+ const offerString = 'newOfferSDP';
+ const action = newRequestWebRTCOfferSet(offerString);
const newState = newRequestReducer(initialState, action);
expect(newState.newRequestWebRTC.webRTCOffer).toBe(offerString);
- })
- })
+ });
+ });
});
+
diff --git a/test/__tests__/reqResControllerTest.js b/test/__tests__/reqResControllerTest.js
index cedaa4afc..9e78a5c4c 100644
--- a/test/__tests__/reqResControllerTest.js
+++ b/test/__tests__/reqResControllerTest.js
@@ -1,13 +1,8 @@
-import store from '../../src/client/toolkit-refactor/store';
-
-import {
- reqResReplaced,
-} from '../../src/client/toolkit-refactor/slices/reqResSlice';
-
+import store from '../../src/client/rtk/store';
+import { reqResReplaced } from '../../src/client/rtk/slices/reqResSlice';
import connectionController from '../../src/client/controllers/reqResController';
-
-jest.mock('../../src/client/toolkit-refactor/store', () => ({
+jest.mock('../../src/client/rtk/store', () => ({
__esModule: true,
default: {
getState: jest.fn(),
@@ -16,8 +11,7 @@ jest.mock('../../src/client/toolkit-refactor/store', () => ({
appDispatch: jest.fn(),
}));
-
-jest.mock('../../src/client/toolkit-refactor/slices/reqResSlice', () => ({
+jest.mock('../../src/client/rtk/slices/reqResSlice', () => ({
__esModule: true,
reqResReplaced: jest.fn(),
}));
@@ -27,7 +21,7 @@ describe('connectionController', () => {
describe('toggleSelectAll', () => {
it('should toggle all the checked values for to true if starting at false', () => {
// Set up the initial state of the reqResArray
- // there is something
+ // there is something
const initialState = {
reqRes: {
reqResArray: [
@@ -48,12 +42,14 @@ describe('connectionController', () => {
expect(initialState.reqRes.reqResArray[2].checked).toBe(true);
// Assert that the reqResReplaced action was called with the modified reqResArray
- expect(reqResReplaced).toHaveBeenCalledWith(initialState.reqRes.reqResArray);
+ expect(reqResReplaced).toHaveBeenCalledWith(
+ initialState.reqRes.reqResArray
+ );
});
it('should toggle all the checked values for to false if starting at false', () => {
// Set up the initial state of the reqResArray
- // there is something
+ // there is something
const initialState = {
reqRes: {
reqResArray: [
@@ -74,13 +70,10 @@ describe('connectionController', () => {
expect(initialState.reqRes.reqResArray[2].checked).toBe(false);
// Assert that the reqResReplaced action was called with the modified reqResArray
- expect(reqResReplaced).toHaveBeenCalledWith(initialState.reqRes.reqResArray);
+ expect(reqResReplaced).toHaveBeenCalledWith(
+ initialState.reqRes.reqResArray
+ );
});
});
-
});
-
-
-
-
diff --git a/test/__tests__/uiSliceTest.js b/test/__tests__/uiSliceTest.js
index 6bf3def28..46025024f 100644
--- a/test/__tests__/uiSliceTest.js
+++ b/test/__tests__/uiSliceTest.js
@@ -1,44 +1,45 @@
/**
* @file Test to determine the state management for the given windows (sidebar, workspace, response pane) in the UI.
- *
+ *
* Currently, updating the state is working properly.
* Possibly @todo - testing for actual updates when the rendering occurs real-time?
- *
+ *
*/
-import uiSliceReducer,
- { initialState,
- setSidebarActiveTab,
- setWorkspaceActiveTab,
- setResponsePaneActiveTab,
- toggleDarkMode } from '../../src/client/toolkit-refactor/slices/uiSlice';
+import uiSliceReducer, {
+ initialState,
+ setSidebarActiveTab,
+ setWorkspaceActiveTab,
+ setResponsePaneActiveTab,
+ toggleDarkMode,
+} from '../../src/client/rtk/slices/uiSlice';
describe('uiSlice', () => {
- it('sidebar active window should be updated when changed', () => {
- const action = setSidebarActiveTab('composer');
- const sliceNewState = uiSliceReducer(initialState, action);
- expect(sliceNewState.sidebarActiveTab).toBe('composer');
- });
+ it('sidebar active window should be updated when changed', () => {
+ const action = setSidebarActiveTab('composer');
+ const sliceNewState = uiSliceReducer(initialState, action);
+ expect(sliceNewState.sidebarActiveTab).toBe('composer');
+ });
- it('workspace active window should be updated when changed', () => {
- const action = setWorkspaceActiveTab('workspace');
- const sliceNewState = uiSliceReducer(initialState, action);
- expect(sliceNewState.workspaceActiveTab).toBe('workspace');
- });
+ it('workspace active window should be updated when changed', () => {
+ const action = setWorkspaceActiveTab('workspace');
+ const sliceNewState = uiSliceReducer(initialState, action);
+ expect(sliceNewState.workspaceActiveTab).toBe('workspace');
+ });
- it('response pane active window should be updated when changed', () => {
- const action = setResponsePaneActiveTab('events');
- const sliceNewState = uiSliceReducer(initialState, action);
- expect(sliceNewState.responsePaneActiveTab).toBe('events');
- });
+ it('response pane active window should be updated when changed', () => {
+ const action = setResponsePaneActiveTab('events');
+ const sliceNewState = uiSliceReducer(initialState, action);
+ expect(sliceNewState.responsePaneActiveTab).toBe('events');
+ });
- it('dark-mode switch should toggle correctly', () => {
- const actionOff = toggleDarkMode(false);
- const actionOn = toggleDarkMode(true);
- let sliceNewState = uiSliceReducer(initialState, actionOff);
- expect(sliceNewState.isDark).toBe(false);
- sliceNewState = uiSliceReducer(initialState, actionOn);
- expect(sliceNewState.isDark).toBe(true);
- });
+ it('dark-mode switch should toggle correctly', () => {
+ const actionOff = toggleDarkMode(false);
+ const actionOn = toggleDarkMode(true);
+ let sliceNewState = uiSliceReducer(initialState, actionOff);
+ expect(sliceNewState.isDark).toBe(false);
+ sliceNewState = uiSliceReducer(initialState, actionOn);
+ expect(sliceNewState.isDark).toBe(true);
+ });
});
diff --git a/test/__tests__/utils/reduxTestingUtils.tsx b/test/__tests__/utils/reduxTestingUtils.tsx
index 21e499702..ce148f7e4 100644
--- a/test/__tests__/utils/reduxTestingUtils.tsx
+++ b/test/__tests__/utils/reduxTestingUtils.tsx
@@ -1,43 +1,46 @@
/**
-* This component is the custom render function to test Redux (More info: https://redux.js.org/usage/writing-tests).
-* The gist: We are creating a new Redux store instance every time the function is
-* called - in this scenario exery time we run a test. We COULD pass in the already established
-* store instance, but I believe since Swell is currently mutating state directly it's better to create a new store
-* for testing purposes.
-*
-* @todo This test is currently written in JS - to update to TS.
-* @todo For now, Jest is configured to ignore this file.
-* Without tests included here, Jest reports this file as failing because it expects it to have tests.
-* This file has been added to the testPathIgnorePatterns option in jest.config.js.
-* Remove this file from the testPathIgnorePatterns option when tests are added.
-*
-* Log from github CI jest testing, when file has no tests and is not ignored:
-* FAIL test/__tests__/utils/reduxTestingUtils.tsx
-* ● Test suite failed to run
-* Your test suite must contain at least one test.
-**/
+ * This component is the custom render function to test Redux (More info: https://redux.js.org/usage/writing-tests).
+ * The gist: We are creating a new Redux store instance every time the function is
+ * called - in this scenario exery time we run a test. We COULD pass in the already established
+ * store instance, but I believe since Swell is currently mutating state directly it's better to create a new store
+ * for testing purposes.
+ *
+ * @todo This test is currently written in JS - to update to TS.
+ * @todo For now, Jest is configured to ignore this file.
+ * Without tests included here, Jest reports this file as failing because it expects it to have tests.
+ * This file has been added to the testPathIgnorePatterns option in jest.config.js.
+ * Remove this file from the testPathIgnorePatterns option when tests are added.
+ *
+ * Log from github CI jest testing, when file has no tests and is not ignored:
+ * FAIL test/__tests__/utils/reduxTestingUtils.tsx
+ * ● Test suite failed to run
+ * Your test suite must contain at least one test.
+ **/
-
-import React from 'react'
-import { render } from '@testing-library/react'
-import { configureStore } from '@reduxjs/toolkit'
-import { Provider } from 'react-redux'
+import React from 'react';
+import { render } from '@testing-library/react';
+import { configureStore } from '@reduxjs/toolkit';
+import { Provider } from 'react-redux';
// As a basic setup, import your same slice reducers
-import IntrospectionDataReducer from '../../../src/client/toolkit-refactor/slices/introspectionDataSlice'
+import IntrospectionDataReducer from '../../../src/client/rtk/slices/introspectionDataSlice';
export function renderWithProviders(
ui,
{
preloadedState = {},
// Automatically create a store instance if no store was passed in
- store = configureStore({ reducer: { user: IntrospectionDataReducer }, preloadedState }),
+ store = configureStore({
+ reducer: { user: IntrospectionDataReducer },
+ preloadedState,
+ }),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
- return {children}
+ return {children} ;
}
// Return an object with the store and all of RTL's query functions
- return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }
-}
\ No newline at end of file
+ return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
+}
+
diff --git a/test/__tests__/warningMessageSliceTest.js b/test/__tests__/warningMessageSliceTest.js
index 4bfd95f6c..dd69ba6a7 100644
--- a/test/__tests__/warningMessageSliceTest.js
+++ b/test/__tests__/warningMessageSliceTest.js
@@ -1,23 +1,25 @@
-/**
+/**
* @file Test to determine if the mockServerSlice reducer switches work.
* This test has been completed.
* **/
-import warningMessageReducer,
- { initialState,
- setWarningMessage } from '../../src/client/toolkit-refactor/slices/warningMessageSlice';
+import warningMessageReducer, {
+ initialState,
+ setWarningMessage,
+} from '../../src/client/rtk/slices/warningMessageSlice';
describe('warningMessageSlice', () => {
- it('state should be updated on server start', () => {
- const warningMessageExample = {
- paylod: {
- err: 'error message',
- uri: 'uri link',
- body: 'body message'
- }
- };
- const action = setWarningMessage(warningMessageExample);
- const sliceNewState = warningMessageReducer(initialState, action);
- expect(sliceNewState).toBe(warningMessageExample);
- });
-});
\ No newline at end of file
+ it('state should be updated on server start', () => {
+ const warningMessageExample = {
+ paylod: {
+ err: 'error message',
+ uri: 'uri link',
+ body: 'body message',
+ },
+ };
+ const action = setWarningMessage(warningMessageExample);
+ const sliceNewState = warningMessageReducer(initialState, action);
+ expect(sliceNewState).toBe(warningMessageExample);
+ });
+});
+
diff --git a/tsconfig.json b/tsconfig.json
index 308747ee3..d62bc6ce5 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -20,8 +20,29 @@
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
/* Advanced Options */
- "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
+ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
+
+ // Sets up custom path aliases for creating shorter, absolute import paths;
+ // if you add any more, be sure to update Webpack, too
+ "paths": {
+ "~/assets/*": ["./src/assets/*"],
+ "~/components/*": ["./src/client/components/*"],
+ "~/controllers/*": ["./src/client/controllers/*"],
+ "~/hooks/*": ["./src/client/hooks/*"],
+ "~/server/*": ["./src/server/*"],
+ "~/toolkit/*": ["./src/client/rtk/*"],
+
+ // Import paths for single files
+ "~/db": ["./src/client/db"],
+ "~/types": ["./src/types"]
+ }
},
+
+ /**
+ * @todo 2023-08-31 - Don't have time to check why there are all these files
+ * manually added to the include path, but anything that isn't glob-based
+ * (as in, anything without stars) should almost definitely be removed.
+ */
"include": [
"./src/**/*.ts",
"./src/**/*.tsx",
@@ -41,3 +62,4 @@
"exclude": ["node_modules", "dist", "build", "coverage", "mocks"],
"typeRoots": ["./node_modules/@types"]
}
+
diff --git a/webpack.config.js b/webpack.config.js
index 161b4bf61..2e1d7d5f5 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -1,3 +1,4 @@
+// @ts-check
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
@@ -12,9 +13,36 @@ const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { name } = require('./package.json');
const title = name.charAt(0).toUpperCase() + name.slice(1);
+/** @type {import("webpack").Configuration} */
module.exports = {
target: 'web',
resolve: {
+ /**
+ * Defines the custom path aliases for importing files from absolute paths.
+ * If you decide to add another path, you must be sure to update tsconfig
+ * as well, and keep it and this file in lockstep.
+ *
+ * In short:
+ * 1. Updating the paths here allows Webpack to make the imports happen at
+ * runtime. That's important, but that's basically it.
+ * 2. Updating the tsconfig file makes TypeScript aware of these paths at
+ * compile time, so that it will give you auto-complete and type-safety.
+ * If you only updated tsconfig, you'd be able to do your imports no
+ * problem, but the app would immediately crash when booting up
+ */
+ alias: {
+ '~/assets': path.resolve(__dirname, '/src/assets/'),
+ '~/components': path.resolve(__dirname, '/src/client/components/'),
+ '~/controllers': path.resolve(__dirname, '/src/client/controllers/'),
+ '~/hooks': path.resolve(__dirname, '/src/client/hooks/'),
+ '~/server': path.resolve(__dirname, '/src/server/'),
+ '~/toolkit': path.resolve(__dirname, '/src/client/rtk/'),
+
+ // Imports meant only for single files
+ '~/db': path.resolve(__dirname, '/src/client/db'),
+ '~/types': path.resolve(__dirname, '/src/types'),
+ },
+
fallback: {
buffer: require.resolve('buffer'),
fs: false,
@@ -28,17 +56,20 @@ module.exports = {
crypto: false,
},
},
+
entry: ['./src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/',
},
+
module: {
rules: [
{
test: /\.(ts|js|mjs)x?$/,
include: [path.resolve(__dirname, 'src')],
+
use: {
loader: 'babel-loader',
options: {
diff --git a/webpack.development.js b/webpack.development.js
index 1b734d578..936c4d6da 100644
--- a/webpack.development.js
+++ b/webpack.development.js
@@ -1,3 +1,4 @@
+// @ts-check
const merge = require('webpack-merge').merge;
const base = require('./webpack.config');
const { spawn } = require('child_process');
@@ -27,6 +28,7 @@ module.exports = merge(base, {
secure: false,
},
},
+
setupMiddlewares: (middlewares, devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
diff --git a/webpack.production.js b/webpack.production.js
index 658c8c474..3477151af 100644
--- a/webpack.production.js
+++ b/webpack.production.js
@@ -1,3 +1,4 @@
+// @ts-check
const path = require('path');
const merge = require('webpack-merge').merge;
const base = require('./webpack.config');