- Update validation

- Switch to active tab when there are errors on it upon submission
- Add createStatusPage function
- Updated JSDOC for functions
This commit is contained in:
Shemy Gan committed 2024-12-24 14:46:54 -05:00
1 parent c535a6f99b
commit d844078ed7
6 files changed
+128 -104

No files matched your search

@@ -3,16 +3,13 @@ import { Button, Box, Stack, Typography } from "@mui/material";
import ConfigBox from "../../../Components/ConfigBox"; import ConfigBox from "../../../Components/ConfigBox";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { publicPageGeneralSettingsValidation } from "../../../Validation/validation";
import { buildErrors } from "../../../Validation/error";
import Card from "./Card"; import Card from "./Card";
import update from "immutability-helper"; import update from "immutability-helper";
import Checkbox from "../../Inputs/Checkbox";
import { StatusFormContext } from "../../../Pages/Status/CreateStatusContext"; import { StatusFormContext } from "../../../Pages/Status/CreateStatusContext";
const ContentPanel = () => { const ContentPanel = () => {
const theme = useTheme(); const theme = useTheme();
const { form, setForm, errors, setErrors } = useContext(StatusFormContext); const { form, setForm, errors, setErrors } = useContext(StatusFormContext);
const [cards, setCards] = useState(form.monitors); const [cards, setCards] = useState(form.monitors);
const moveCard = useCallback( const moveCard = useCallback(
@@ -30,44 +27,31 @@ const ContentPanel = () => {
[cards] [cards]
); );
const handleChange = (event) => {
event.preventDefault();
const { value, id } = event.target;
setForm((prev) => ({
...prev,
[id]: value,
}));
};
const handleCardChange = (event) => { const handleCardChange = (event) => {
event.preventDefault(); event.preventDefault();
const { value, id } = event.target; const { value, id } = event.target;
let idx = cards.findIndex((a) => a.id == id); let idx = cards.findIndex((a) => a.id == id);
let newCards;
if (idx >= 0) { if (idx >= 0) {
let x = JSON.parse(JSON.stringify(cards[idx])); let x = JSON.parse(JSON.stringify(cards[idx]));
x.url = value; x.url = value;
setCards(update(cards, { $splice: [[idx, 1, x]] })); newCards = update(cards, { $splice: [[idx, 1, x]] });
} else setCards(update(cards, { $push: [{ id: id, url: value }] })); setCards(newCards);
} } else {
newCards = update(cards, { $push: [{ id: id, url: value }] });
setCards(newCards);
}
setForm({ ...form, monitors: newCards });
};
const handleAddNew = () => { const handleAddNew = () => {
setCards([...cards, { id: "" + Math.random() }]); const newCards = [...cards, { id: "" + Math.random() }];
setCards(newCards);
setForm({ ...form, monitors: newCards });
}; };
const removeCard = (id) => { const removeCard = (id) => {
setCards(cards.filter((c) => c?.id != id)); const newCards = cards.filter((c) => c?.id != id);
}; setCards(newCards);
const handleBlur = (event) => { setForm({ ...form, monitors: newCards });
event.preventDefault();
const { value, id } = event.target;
const { error } = publicPageGeneralSettingsValidation.validate(
{ [id]: value },
{
abortEarly: false,
}
);
setErrors((prev) => {
return buildErrors(prev, id, error);
});
}; };
return ( return (
@@ -101,7 +85,6 @@ const ContentPanel = () => {
className="status-contents-server-list" className="status-contents-server-list"
sx={{ sx={{
margin: theme.spacing(20), margin: theme.spacing(20),
//padding: theme.spacing(20),
border: "solid", border: "solid",
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
@@ -113,48 +96,54 @@ const ContentPanel = () => {
}, },
}} }}
> >
<Box> <Stack
<Stack direction="row"
direction="row" justifyContent="space-around"
justifyContent="space-around" >
<Typography
component="p"
alignSelf={"center"}
> >
<Typography {" "}
component="p" Servers list{" "}
alignSelf={"center"} </Typography>
> <Button onClick={handleAddNew}>Add New</Button>
{" "} </Stack>
Servers list{" "} {cards.length > 0 && (
</Typography> <Stack
<Button onClick={handleAddNew}>Add New</Button> id="monitors"
direction="column"
gap={theme.spacing(2)}
>
{cards.map((card, idx) => (
<Card
key={idx}
index={idx}
id={card?.id ?? "" + Math.random()}
text={"" + idx}
moveCard={moveCard}
removeCard={removeCard}
value={card?.url ?? ""}
onChange={handleCardChange}
/>
))}
</Stack> </Stack>
{cards.length > 0 && ( )}
<Stack {errors["monitors"] && (
direction="column" <Typography
alignItems="center" component="span"
gap={theme.spacing(6)} className="input-error"
sx={{ color={theme.palette.error.main}
ml: theme.spacing(4), sx={{
mr: theme.spacing(8), opacity: 0.8,
mb: theme.spacing(8), }}
}} >
> {errors["monitors"]}
{cards.map((card, idx) => ( </Typography>
<Card )}
key={idx}
index={idx}
id={card?.id ?? "" + Math.random()}
text={"" + idx}
moveCard={moveCard}
removeCard={removeCard}
value={card?.url??""}
onChange = {handleCardChange}
/>
))}
</Stack>
)}
</Box>
</Box> </Box>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
@@ -162,7 +151,7 @@ const ContentPanel = () => {
<Typography component="p">Show more details on the status page</Typography> <Typography component="p">Show more details on the status page</Typography>
</Stack> </Stack>
</Box> </Box>
<Stack sx={{margin: theme.spacing(20)}} {/* <Stack sx={{margin: theme.spacing(20)}}
> >
<Checkbox <Checkbox
id="show-barcode" id="show-barcode"
@@ -178,7 +167,7 @@ const ContentPanel = () => {
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur} onBlur={handleBlur}
/> />
</Stack> </Stack> */}
</ConfigBox> </ConfigBox>
</Stack> </Stack>
</TabPanel> </TabPanel>
@@ -64,7 +64,6 @@ const GeneralSettingsPanel = () => {
abortEarly: false, abortEarly: false,
} }
); );
setErrors((prev) => { setErrors((prev) => {
return buildErrors(prev, id, error); return buildErrors(prev, id, error);
}); });
@@ -186,7 +185,7 @@ const GeneralSettingsPanel = () => {
</Box> </Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Select <Select
id="display-timezone" id="timezone"
label="Display timezone" label="Display timezone"
value={form.timezone} value={form.timezone}
onChange={handleChange} onChange={handleChange}
+23 -17
View File
@@ -1,5 +1,5 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useEffect, useState } from "react"; import { useState } from "react";
import { Box, Tab, useTheme, Stack, Button } from "@mui/material"; import { Box, Tab, useTheme, Stack, Button } from "@mui/material";
import TabContext from "@mui/lab/TabContext"; import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList"; import TabList from "@mui/lab/TabList";
@@ -21,6 +21,7 @@ import { networkService } from "../../../main";
const CreateStatus = ({ initForm }) => { const CreateStatus = ({ initForm }) => {
const theme = useTheme(); const theme = useTheme();
const mode = useSelector((state) => state.ui.mode);
const {authToken} = useSelector((state) => state.auth); const {authToken} = useSelector((state) => state.auth);
const {apiBaseUrl} = useSelector((state) => state.settings); const {apiBaseUrl} = useSelector((state) => state.settings);
const [tabIdx, setTabIdx] = useState(0); const [tabIdx, setTabIdx] = useState(0);
@@ -46,31 +47,36 @@ import { networkService } from "../../../main";
} }
); );
// switch to the respective tab when there is error on it const setActiveTabOnErrors = () => {
useEffect(() => {
let newIdx = -1; let newIdx = -1;
Object.keys(errors).map(id=>{ Object.keys(errors).map((id) => {
error_tab_maping.map((val, idx) => { if (newIdx !== -1) return;
let anyMatch = val.some(vl=> vl==id ) error_tab_maping.map((val, idx) => {
if(anyMatch){ let anyMatch = val.some((vl) => vl == id);
newIdx = idx; if (anyMatch) {
newIdx = idx;
return;
} }
}) });
}) });
if (newIdx !== -1) setTabIdx(newIdx); if (newIdx !== -1) setTabIdx(newIdx);
}, [errors]); };
const handleTabChange = (_, newTab) => { const handleTabChange = (_, newTab) => {
setTabIdx(tabList.indexOf(newTab)); setTabIdx(tabList.indexOf(newTab));
}; };
const handleSubmit = async () => { const handleSubmit = async (e) => {
e.preventDefault();
//validate rest of the form //validate rest of the form
delete form.logo; delete form.logo;
//let localData = {...form, monitors: form.monitors.map(m=>m.url)}
let localData = {...form, monitors: form.monitors, theme: mode}
if (hasValidationErrors(form, publicPageGeneralSettingsValidation, setErrors)) { if (hasValidationErrors(localData, publicPageGeneralSettingsValidation, setErrors)) {
setActiveTabOnErrors();
return; return;
} }
// //validate image field, double check if it is required // //validate image field, double check if it is required
// let error = validateField( // let error = validateField(
// { type: logo?.type ?? null, size: logo?.size ?? null }, // { type: logo?.type ?? null, size: logo?.size ?? null },
@@ -78,8 +84,8 @@ import { networkService } from "../../../main";
// ); // );
// if (error) return; // if (error) return;
//form.logo = { ...logo, size: formatBytes(logo?.size) }; //form.logo = { ...logo, size: formatBytes(logo?.size) };
let config = { authToken: authToken, url: apiBaseUrl, data: form }; let config = { authToken: authToken, url: apiBaseUrl, data: localData };
try{ try{
const res = await networkService.createStatusPage(config) const res = await networkService.createStatusPage(config)
if (!res.status === 200) { if (!res.status === 200) {
+10
View File
@@ -856,6 +856,16 @@ class NetworkService {
}, },
}); });
} }
async createStatusPage(config) {
const { url, authToken, data } = config;
return this.axiosInstance.post(`/status-page/${url}`, data, {
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
});
}
} }
export default NetworkService; export default NetworkService;
+22 -4
View File
@@ -1,6 +1,16 @@
/**
* Update errors if passed id matches the error.details[0].path, otherwise remove
* the error for the id
* @param {*} prev Previous errors *
* @param {*} id ID of the field whose error is to be either updated or removed
* @param {*} error the error object
* @returns the Update Errors with the specific field with id being either removed or updated
*/
const buildErrors = (prev, id, error) => { const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (error) { if (error && id == error.details[0].path) {
updatedErrors[id] = error.details[0].message ?? "Validation error"; updatedErrors[id] = error.details[0].message ?? "Validation error";
} else { } else {
delete updatedErrors[id]; delete updatedErrors[id];
@@ -32,7 +42,15 @@ const getTouchedFieldErrors = (validation, touchedErrors) => {
return newErrors; return newErrors;
}; };
/**
*
* @param {*} form The form object of the submitted form data
* @param {*} validation The Joi validation rules
* @param {*} setErrors The function used to set the local errors
* @returns true if there is no error or false if there is error after validating the form
* the error will be reset to {} if returns false; otherwise the errors object will be set with
* the new value
*/
const hasValidationErrors = (form, validation, setErrors) => { const hasValidationErrors = (form, validation, setErrors) => {
const { error } = validation.validate(form, { const { error } = validation.validate(form, {
abortEarly: false, abortEarly: false,
@@ -66,8 +84,7 @@ const hasValidationErrors = (form, validation, setErrors) => {
newErrors["usage_temperature"] = null; newErrors["usage_temperature"] = null;
} }
}); });
console.log("newErrors", newErrors);
if (Object.values(newErrors).some((v) => v)) { if (Object.values(newErrors).some((v) => v)) {
setErrors(newErrors); setErrors(newErrors);
return true; return true;
@@ -76,6 +93,7 @@ const hasValidationErrors = (form, validation, setErrors) => {
return false; return false;
} }
} }
setErrors({});
return false; return false;
}; };
export { buildErrors, hasValidationErrors, getTouchedFieldErrors }; export { buildErrors, hasValidationErrors, getTouchedFieldErrors };
+10 -8
View File
@@ -150,25 +150,27 @@ const logoImageValidation = joi.object({
}); });
const publicPageGeneralSettingsValidation = joi.object({ const publicPageGeneralSettingsValidation = joi.object({
companyName: joi.string().trim().messages({ "string.empty": "Company name is required." }), publish: joi.bool(),
companyName: joi
.string()
.trim()
.messages({ "string.empty": "Company name is required." }),
url: joi.string().trim().messages({ "string.empty": "URL is required." }), url: joi.string().trim().messages({ "string.empty": "URL is required." }),
timezone: joi.string().trim().messages({ "string.empty": "Timezone is required." }), timezone: joi.string().trim().messages({ "string.empty": "Timezone is required." }),
color: joi.string().trim().messages({ "string.empty": "Color is required." }), color: joi.string().trim().messages({ "string.empty": "Color is required." }),
publish: joi.bool(),
theme: joi.string(),
monitors: joi monitors: joi
.array() .array()
.items(joi.string().pattern(/^[0-9a-fA-F]{24}$/)) .min(1)
.required() .items({ id: joi.string(), url: joi.string().required() })
.messages({ .messages({
"string.pattern.base": "Must be a valid monitor ID", "string.pattern.base": "Must be a valid monitor ID",
"array.base": "Monitors must be an array", "array.base": "Monitors must be an array",
"array.empty": "At least one monitor is required", "array.empty": "At least one monitor is required",
"any.required": "Monitors are required", "any.required": "Monitors are required",
}), }),
});
}
)
const settingsValidation = joi.object({ const settingsValidation = joi.object({
ttl: joi.number().required().messages({ ttl: joi.number().required().messages({
"string.empty": "TTL is required", "string.empty": "TTL is required",