Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | 3x 43x 43x 43x 43x 43x 3x 22x 11x 11x 2x 2x 2x 2x 2x 11x 11x 11x 11x 11x 2x 16x 2x 2x 11x 2x 2x 2x 2x 2x 2x 2x 11x 1x 8x 1x 1x 11x 2x 2x 2x 11x 2x 2x 2x 11x 11x 11x 11x 11x 11x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 11x 2x 2x | import * as React from "react";
import { Alert } from "@mui/material";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import TextField from "@mui/material/TextField";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import FormHelperText from "@mui/material/FormHelperText";
import { useFormik } from "formik";
import * as yup from "yup";
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useSnackbar } from "notistack";
import { DemoContainer } from "@mui/x-date-pickers/internals/demo";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { _updateClass, setSpecificClassData, _clearErrorMessage } from "@/store/slices/teacher/TeacherSpecificClass";
import { useState } from "react";
import CreateNewSched from "./CreateNewSched";
import { _fetchAllClasses } from "@/store/slices/teacher/TeacherClasses";
export const editClassValidationSchema = yup.object({
semester: yup.string().required("Semester is required"),
title: yup
.string()
.min(1, "Title must be at least 1 character long")
.max(25, "Title must be no more than 25 characters long")
.required("Title is required")
.test("has-alphanumeric", "Title must contain a letter or number", (value) => /[a-zA-Z0-9]/.test(value || ""))
.test("no-trailing-space", "Title cannot end with a space", (value) => value?.trimEnd() === value),
section: yup
.string()
.min(1, "Section/Period must be at least 1 character long")
.max(25, "Section/Period must be no more than 25 characters long")
.required("Section/Period is required")
.test("no-trailing-space", "Section/Period cannot end with a space", (value) => value?.trimEnd() === value),
description: yup
.string()
.max(60, "Description must be no more than 60 characters long")
.test("has-alphanumeric", "Description must contain a letter or number", (value) =>
!value || /[a-zA-Z0-9]/.test(value)
)
.test("no-trailing-space", "Description cannot end with a space", (value) => !value || value.trimEnd() === value),
});
const EditClass = ({ showDialog, setDialog, classDetails }) => {
const { specificClassData, isLoading, hasErrors } = useSelector((state) => state.TeacherSpecificClass);
const hydratedRef = useRef(false);
useEffect(() => {
// Hydrate the form from the class data ONCE per open, guarded by a ref.
// - Keying only on [classDetails] re-fired on every re-fetch (incl. the
// _fetchAllClasses dispatch below) and clobbered the user's in-progress
// edits — the typed title reverted, Save stayed disabled, no update fired.
// - Keying only on [showDialog] missed a classDetails that arrives AFTER the
// dialog opens, so the fields (notably the schedule) never populated and
// a save went out with an empty schedule.
// The ref lets a late classDetails hydrate the form exactly once, without
// re-clobbering later edits; it resets when the dialog closes.
Eif (showDialog && classDetails && !hydratedRef.current) {
hydratedRef.current = true;
setAllFieldValues();
dispatch(_fetchAllClasses());
}
Iif (!showDialog) {
hydratedRef.current = false;
}
}, [showDialog, classDetails]);
const dispatch = useDispatch();
const { enqueueSnackbar } = useSnackbar();
const [schedules, setSchedules] = useState([]);
const { values, touched, errors, handleChange, handleBlur, setFieldTouched, setFieldError, setFieldValue } =
useFormik({
initialValues: {
semester: "",
title: "",
section: "",
code: "",
description: "",
day: "",
timeStart: "",
timeEnd: "",
},
validationSchema: editClassValidationSchema,
});
const isValidated = () => {
// touch all fields
Object.keys(values).forEach((fieldName) => {
setFieldTouched(fieldName, true);
});
// check if there are errors
Eif (Object.keys(errors).length === 0) {
return true;
}
return false;
};
const setAllFieldValues = () => {
Eif (classDetails) {
values.semester = classDetails.semester;
values.title = classDetails.title;
values.section = classDetails.section;
values.code = classDetails.class_code;
values.description = classDetails.description ?? "";
setSchedules((prevSchedules) => [...prevSchedules, ...classDetails.schedules]);
}
};
const resetAllFieldValues = () => {
Object.keys(values).forEach((key) => {
values[key] = "";
});
// remove all field errors
Object.keys(errors).forEach((fieldName) => {
setFieldError(fieldName, "");
});
setSchedules([]);
};
const sanitizeString = (input) => {
let sanitized = input.replace(/\s+/g, " ").trimStart();
Iif (sanitized.endsWith(" ")) sanitized = sanitized.slice(0, -1);
return sanitized;
};
const handleSanitizedChange = (event) => {
const { name, value } = event.target;
const sanitizedValue = sanitizeString(value);
setFieldValue(name, sanitizedValue, true);
};
const hasChanges = () => {
let oldData = {
semester: classDetails.semester,
title: classDetails.title,
section: classDetails.section,
code: classDetails.class_code,
description: classDetails.description,
schedules: [...classDetails.schedules],
};
let newData = {
semester: values.semester,
title: values.title,
section: values.section,
code: values.code,
description: values.description,
schedules: [...schedules],
};
return JSON.stringify(oldData) === JSON.stringify(newData);
};
const handleCancel = () => {
resetAllFieldValues();
dispatch(_clearErrorMessage());
setDialog(false);
setAllFieldValues();
};
const handleSave = () => {
let payload = {
classID: classDetails._id,
classDetails: {
semester: values.semester,
title: values.title,
section: values.section,
description: values.description,
schedules: [...schedules],
},
};
Eif (isValidated()) {
dispatch(_updateClass(payload)).then((response) => {
if (!response.error) {
dispatch(setSpecificClassData(response.payload.data.updated_class));
resetAllFieldValues();
setDialog(false);
enqueueSnackbar("Class successfully updated", { variant: "success" });
} else {
// Surface backend errors (e.g. 409 "A class with the same
// schedule already exists") instead of failing silently. Keep
// the dialog open so the user can correct and retry.
const detail = response.payload?.detail;
enqueueSnackbar(typeof detail === "string" ? detail : "Failed to update class. Please try again.", {
variant: "error",
});
}
});
}
};
return (
<Dialog
open={showDialog}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
fullWidth
>
<DialogTitle id="alert-dialog-title">Edit Class</DialogTitle>
<DialogContent dividers>
{hasErrors && (
<Alert severity="error" sx={{ mb: 2.5 }}>
{hasErrors}
</Alert>
)}
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={["TimePicker"]}>
<div
className="teacher-edit-class"
style={{
width: "100%",
display: "flex",
flexDirection: "column",
gap: 25,
}}
>
<FormControl fullWidth variant="outlined" error={touched.semester && Boolean(errors.semester)}>
<InputLabel>Semester</InputLabel>
<Select
id="semester"
name="semester"
value={values.semester}
onChange={handleChange}
onBlur={handleBlur}
label="Semester"
fullWidth
>
<MenuItem value="fall">Fall</MenuItem>
<MenuItem value="summer 1">Summer 1</MenuItem>
<MenuItem value="summer 2">Summer 2</MenuItem>
<MenuItem value="spring">Spring</MenuItem>
</Select>
<FormHelperText>{touched.semester && errors.semester}</FormHelperText>
</FormControl>
<TextField
variant="outlined"
label="Title"
fullWidth
id="edit-class-title"
name="title"
value={values.title}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.title && Boolean(errors.title)}
helperText={touched.title && errors.title}
/>
<TextField
variant="outlined"
label="Section"
fullWidth
id="edit-class-section"
name="section"
value={values.section}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.section && Boolean(errors.section)}
helperText={touched.section && errors.section}
/>
<TextField
variant="outlined"
label="Code"
fullWidth
id="edit-class-code"
name="code"
value={values.code}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.code && Boolean(errors.code)}
helperText={touched.code && errors.code}
disabled
/>
<TextField
label="Description"
fullWidth
multiline
id="edit-class-description"
name="description"
value={values.description}
onChange={(e) => {
handleChange(e);
handleSanitizedChange(e);
}}
onBlur={handleBlur}
error={touched.description && Boolean(errors.description)}
helperText={touched.description && errors.description}
/>
<CreateNewSched schedules={schedules} setSchedules={setSchedules} />
</div>
</DemoContainer>
</LocalizationProvider>
</DialogContent>
<DialogActions sx={{ display: "flex", justifyContent: "space-between" }}>
<Button sx={{ width: "150px" }} variant="inherit" onClick={handleCancel}>
Cancel
</Button>
<Button
sx={{ width: "150px" }}
variant="contained"
color="primary"
onClick={handleSave}
disabled={hasChanges()}
>
Save
</Button>
</DialogActions>
</Dialog>
);
};
export default EditClass;
|