Skip to content

Commit

Permalink
Fix codeclimate issues
Browse files Browse the repository at this point in the history
  • Loading branch information
VanessaScherma committed Oct 28, 2024
1 parent ae4a9a8 commit 28c38a7
Show file tree
Hide file tree
Showing 5 changed files with 203 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import {
DialogTitle,
TextField,
Button,
Typography,
} from '@mui/material';
import { renameFile } from 'preview/store/file.slice';
import { useDispatch } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { RootState } from 'store/store';

interface ChangeFileNameDialogProps {
open: boolean;
Expand All @@ -27,14 +29,31 @@ const ChangeFileNameDialog: React.FC<ChangeFileNameDialogProps> = ({
setFileType,
}) => {
const [modifiedFileName, setModifiedFileName] = useState(fileName);
const [errorChangeMessage, setErrorChangeMessage] = useState('');

const files = useSelector((state: RootState) => state.files);
const dispatch = useDispatch();

useEffect(() => {
setModifiedFileName(fileName);
}, [fileName]);

const handleChangeFileName = () => {
const fileExists = files.some(
(fileStore: { name: string }) => fileStore.name === modifiedFileName,
);

if (fileExists) {
setErrorChangeMessage('A file with this name already exists.');
return;
}

if (modifiedFileName === '') {
setErrorChangeMessage("File name can't be empty.");
return;
}

setErrorChangeMessage('');
dispatch(renameFile({ oldName: fileName, newName: modifiedFileName }));
setFileName(modifiedFileName);

Expand All @@ -44,6 +63,12 @@ const ChangeFileNameDialog: React.FC<ChangeFileNameDialogProps> = ({
onClose();
};

const handleCloseChangeFileNameDialog = () => {
setErrorChangeMessage('');
setModifiedFileName(fileName);
onClose();
};

return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>Change the file name</DialogTitle>
Expand All @@ -57,12 +82,16 @@ const ChangeFileNameDialog: React.FC<ChangeFileNameDialogProps> = ({
value={modifiedFileName}
onChange={(e) => setModifiedFileName(e.target.value)}
/>
<Typography style={{ color: 'red' }}>{errorChangeMessage}</Typography>
</DialogContent>
<DialogActions>
<Button onClick={onClose} color="primary">
<Button
onClick={() => handleCloseChangeFileNameDialog()}
color="primary"
>
Cancel
</Button>
<Button onClick={handleChangeFileName} color="secondary">
<Button onClick={() => handleChangeFileName()} color="secondary">
Change
</Button>
</DialogActions>
Expand Down
209 changes: 136 additions & 73 deletions client/src/preview/route/digitaltwins/create/CreateDTDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,113 @@ const defaultFiles = [
{ name: '.gitlab-ci.yml', type: 'config' },
];

const validateFiles = (
files: FileState[],
setErrorMessage: Dispatch<SetStateAction<string>>,
): boolean => {
const emptyFiles = files
.filter((file) => file.isNew && file.content === '')
.map((file) => file.name);

if (emptyFiles.length > 0) {
setErrorMessage(
`The following files have empty content: ${emptyFiles.join(', ')}. Edit them in order to create the new digital twin.`,
);
return true;
}
return false;
};

const initDigitalTwin = async (newDigitalTwinName: string) => {
const gitlabInstance = new GitlabInstance(
sessionStorage.getItem('username') || '',
getAuthority(),
sessionStorage.getItem('access_token') || '',
);
await gitlabInstance.init();
return new DigitalTwin(newDigitalTwinName, gitlabInstance);
};

const addDefaultFiles = (
defaultFilesNames: { name: string; type: string }[],
files: FileState[],
dispatch: ReturnType<typeof useDispatch>,
) => {
defaultFilesNames.forEach((file) => {
if (!files.some((existingFile) => existingFile.name === file.name)) {
dispatch(addNewFile(file));
}
});
};

const handleError = (
message: string,
dispatch: ReturnType<typeof useDispatch>,
) => {
dispatch(showSnackbar({ message, severity: 'error' }));
};

const handleSuccess = (
digitalTwin: DigitalTwin,
dispatch: ReturnType<typeof useDispatch>,
newDigitalTwinName: string,
files: FileState[],
) => {
dispatch(
showSnackbar({
message: `Digital twin ${newDigitalTwinName} created successfully`,
severity: 'success',
}),
);
dispatch(setDigitalTwin({ assetName: newDigitalTwinName, digitalTwin }));
dispatch(removeAllCreationFiles());

addDefaultFiles(defaultFiles, files, dispatch);
};

const resetDialogAndForm = (
setOpenCreateDTDialog: Dispatch<SetStateAction<boolean>>,
setFileName: Dispatch<SetStateAction<string>>,
setFileContent: Dispatch<SetStateAction<string>>,
setFileType: Dispatch<SetStateAction<string>>,
) => {
setOpenCreateDTDialog(false);
setFileName('');
setFileContent('');
setFileType('');
};

const handleConfirm = async (
files: FileState[],
setErrorMessage: Dispatch<SetStateAction<string>>,
newDigitalTwinName: string,
dispatch: ReturnType<typeof useDispatch>,
setOpenCreateDTDialog: Dispatch<SetStateAction<boolean>>,
setFileName: Dispatch<SetStateAction<string>>,
setFileContent: Dispatch<SetStateAction<string>>,
setFileType: Dispatch<SetStateAction<string>>,
setNewDigitalTwinName: Dispatch<SetStateAction<string>>,
) => {
if (validateFiles(files, setErrorMessage)) return;

const digitalTwin = await initDigitalTwin(newDigitalTwinName);
const result = await digitalTwin.createDT(files);

if (result.startsWith('Error')) {
handleError(result, dispatch);
} else {
handleSuccess(digitalTwin, dispatch, newDigitalTwinName, files);
}

resetDialogAndForm(
setOpenCreateDTDialog,
setFileName,
setFileContent,
setFileType,
);
setNewDigitalTwinName('');
};

const CreateDTDialog: React.FC<CreateDTDialogProps> = ({
open,
onClose,
Expand All @@ -54,77 +161,6 @@ const CreateDTDialog: React.FC<CreateDTDialogProps> = ({
const files: FileState[] = useSelector((state: RootState) => state.files);
const dispatch = useDispatch();

const validateFiles = (): boolean => {
const emptyFiles = files
.filter((file) => file.isNew && file.content === '')
.map((file) => file.name);

if (emptyFiles.length > 0) {
setErrorMessage(
`The following files have empty content: ${emptyFiles.join(', ')}. Edit them in order to create the new digital twin.`,
);
return true;
}
return false;
};

const initDigitalTwin = async () => {
const gitlabInstance = new GitlabInstance(
sessionStorage.getItem('username') || '',
getAuthority(),
sessionStorage.getItem('access_token') || '',
);
await gitlabInstance.init();
return new DigitalTwin(newDigitalTwinName, gitlabInstance);
};

const addDefaultFiles = () => {
defaultFiles.forEach((file) => {
if (!files.some((existingFile) => existingFile.name === file.name)) {
dispatch(addNewFile(file));
}
});
};

const handleError = (message: string) => {
dispatch(showSnackbar({ message, severity: 'error' }));
};

const handleSuccess = (digitalTwin: DigitalTwin) => {
dispatch(
showSnackbar({
message: `Digital twin ${newDigitalTwinName} created successfully`,
severity: 'success',
}),
);
dispatch(setDigitalTwin({ assetName: newDigitalTwinName, digitalTwin }));
dispatch(removeAllCreationFiles());
addDefaultFiles();
};

const resetDialogAndForm = () => {
setOpenCreateDTDialog(false);
setFileName('');
setFileContent('');
setFileType('');
setNewDigitalTwinName('');
};

const handleConfirm = async () => {
if (validateFiles()) return;

const digitalTwin = await initDigitalTwin();
const result = await digitalTwin.createDT(files);

if (result.startsWith('Error')) {
handleError(result);
} else {
handleSuccess(digitalTwin);
}

resetDialogAndForm();
};

return (
<Dialog open={open} onClose={onClose}>
<DialogContent>
Expand All @@ -135,8 +171,35 @@ const CreateDTDialog: React.FC<CreateDTDialogProps> = ({
<Typography style={{ color: 'red' }}>{errorMessage}</Typography>
</DialogContent>
<DialogActions>
<Button onClick={resetDialogAndForm}>Cancel</Button>
<Button onClick={handleConfirm}>Confirm</Button>
<Button
onClick={() =>
resetDialogAndForm(
setOpenCreateDTDialog,
setFileName,
setFileContent,
setFileType,
)
}
>
Cancel
</Button>
<Button
onClick={() =>
handleConfirm(
files,
setErrorMessage,
newDigitalTwinName,
dispatch,
setOpenCreateDTDialog,
setFileName,
setFileContent,
setFileType,
setNewDigitalTwinName,
)
}
>
Confirm
</Button>
</DialogActions>
</Dialog>
);
Expand Down
13 changes: 12 additions & 1 deletion client/src/preview/route/digitaltwins/editor/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { selectDigitalTwinByName } from '../../../store/digitalTwin.slice';
import DigitalTwin from '../../../util/gitlabDigitalTwin';
import {
handleAddFileClick,
handleCloseFileNameDialog,
handleCreateFileClick,
handleFileSubmit,
handleReconfigureFileClick,
Expand Down Expand Up @@ -225,7 +226,17 @@ const Sidebar = ({
{errorMessage && <p style={{ color: 'red' }}>{errorMessage}</p>}
</DialogContent>
<DialogActions>
<Button onClick={() => setIsFileNameDialogOpen(false)}>Cancel</Button>
<Button
onClick={() =>
handleCloseFileNameDialog(
setIsFileNameDialogOpen,
setNewFileName,
setErrorMessage,
)
}
>
Cancel
</Button>
<Button
onClick={() =>
handleFileSubmit(
Expand Down
15 changes: 15 additions & 0 deletions client/src/preview/route/digitaltwins/editor/sidebarFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ export const handleAddFileClick = (
setIsFileNameDialogOpen(true);
};

export const handleCloseFileNameDialog = (
setIsFileNameDialogOpen: Dispatch<SetStateAction<boolean>>,
setNewFileName: Dispatch<SetStateAction<string>>,
setErrorMessage: Dispatch<SetStateAction<string>>,
) => {
setIsFileNameDialogOpen(false);
setNewFileName('');
setErrorMessage('');
};

export const handleFileSubmit = (
files: FileState[],
newFileName: string,
Expand All @@ -112,6 +122,11 @@ export const handleFileSubmit = (
return;
}

if (newFileName === '') {
setErrorMessage("File name can't be empty.");
return;
}

setErrorMessage('');
let type;

Expand Down
8 changes: 8 additions & 0 deletions client/src/preview/store/file.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ const filesSlice = createSlice({
},

addOrUpdateNewFile: (state, action: PayloadAction<FileState>) => {
const { name } = action.payload;

if (!name) return;

const index = state.findIndex(
(file) => file.name === action.payload.name,
);
Expand All @@ -43,6 +47,10 @@ const filesSlice = createSlice({
},

addOrUpdateFile: (state, action: PayloadAction<FileState>) => {
const { name } = action.payload;

if (!name) return;

const index = state.findIndex(
(file) => file.name === action.payload.name && !file.isNew,
);
Expand Down

0 comments on commit 28c38a7

Please sign in to comment.