restore repo structure

This commit is contained in:
Alex Holliday committed 2025-04-20 11:29:53 -07:00
1 parent 6df099a5b6
commit 8b7e3c650b
592 files changed
+37663 -127

No files matched your search

@@ -0,0 +1,106 @@
// Components
import { Stack, Typography } from "@mui/material";
import ReorderRoundedIcon from "@mui/icons-material/ReorderRounded";
import DeleteIcon from "@mui/icons-material/Delete";
// Utils
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { useTheme } from "@emotion/react";
const MonitorListItem = ({
monitor,
innerRef,
draggableProps,
dragHandleProps,
onDelete,
}) => {
const theme = useTheme();
return (
<Stack
direction={"row"}
{...draggableProps}
{...dragHandleProps}
ref={innerRef}
gap={theme.spacing(4)}
margin={theme.spacing(4)}
padding={theme.spacing(4)}
borderRadius={theme.shape.borderRadius}
alignItems={"center"}
justifyContent={"start"}
border={`1px solid ${theme.palette.primary.lowContrast}`}
>
<ReorderRoundedIcon />
<Typography>{monitor.name}</Typography>
<DeleteIcon
sx={{ marginLeft: "auto" }}
onClick={() => {
onDelete(monitor);
}}
/>
</Stack>
);
};
const MonitorList = ({ selectedMonitors, setSelectedMonitors }) => {
const onDelete = (monitorToDelete) => {
const newMonitors = selectedMonitors.filter(
(monitor) => monitor._id !== monitorToDelete._id
);
setSelectedMonitors(newMonitors);
};
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const onDragEnd = (result) => {
// dropped outside the list
if (!result.destination) {
return;
}
const reorderedMonitors = reorder(
selectedMonitors,
result.source.index,
result.destination.index
);
setSelectedMonitors(reorderedMonitors);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<Stack
{...provided.droppableProps}
ref={provided.innerRef}
>
{selectedMonitors?.map((monitor, index) => (
<Draggable
key={monitor._id}
draggableId={monitor._id}
index={index}
>
{(provided, snapshot) => (
<MonitorListItem
monitor={monitor}
innerRef={provided.innerRef}
draggableProps={provided.draggableProps}
dragHandleProps={provided.dragHandleProps}
onDelete={onDelete}
/>
)}
</Draggable>
))}
{provided.placeholder}
</Stack>
)}
</Droppable>
</DragDropContext>
);
};
export default MonitorList;
@@ -0,0 +1,38 @@
import { Button, Box } from "@mui/material";
import ProgressUpload from "../../../../../Components/ProgressBars";
import ImageIcon from "@mui/icons-material/Image";
import { useTranslation } from "react-i18next";
import { formatBytes } from "../../../../../Utils/fileUtils";
const Progress = ({ isLoading, progressValue, logo, logoType, removeLogo, errors }) => {
const { t } = useTranslation();
if (isLoading) {
return (
<ProgressUpload
icon={<ImageIcon />}
label={logo?.name}
size={formatBytes(logo?.size)}
progress={progressValue}
onClick={removeLogo}
/>
);
}
if (logo && logoType) {
return (
<Box
width="fit-content"
alignSelf="center"
>
<Button
variant="contained"
color="secondary"
onClick={removeLogo}
>
{t("removeLogo")}
</Button>
</Box>
);
}
};
export default Progress;
@@ -0,0 +1,14 @@
import { Stack, Skeleton } from "@mui/material";
const SkeletonLayout = () => {
return (
<Stack>
<Skeleton
variant="rectangular"
height={"90vh"}
/>
</Stack>
);
};
export default SkeletonLayout;
@@ -0,0 +1,26 @@
import { Stack, Typography } from "@mui/material";
import ConfigBox from "../../../../../Components/ConfigBox";
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
// This can be used to add any extra/additional section/stacks on top of existing sections on the tab
const ConfigStack = ({ title, description, children }) => {
const theme = useTheme();
return (
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">{title}</Typography>
<Typography component="p">{description}</Typography>
</Stack>
{children}
</ConfigBox>
);
};
ConfigStack.propTypes = {
title: PropTypes.string.isRequired, // Title must be a string and is required
description: PropTypes.string.isRequired, // Description must be a string and is required
children: PropTypes.node.isRequired,
};
export default ConfigStack;
@@ -0,0 +1,100 @@
// Components
import { Stack, Typography } from "@mui/material";
import { TabPanel } from "@mui/lab";
import MonitorList from "../MonitorList";
import Search from "../../../../../Components/Inputs/Search";
import Checkbox from "../../../../../Components/Inputs/Checkbox";
// Utils
import { useState } from "react";
import { useTheme } from "@emotion/react";
import { useTranslation } from "react-i18next";
import ConfigStack from "./ConfigStack";
const Content = ({
tabValue,
form,
monitors,
handleFormChange,
errors,
selectedMonitors,
setSelectedMonitors,
}) => {
// Local state
const [search, setSearch] = useState("");
// Handlers
const handleMonitorsChange = (selectedMonitors) => {
handleFormChange({
target: { name: "monitors", value: selectedMonitors.map((monitor) => monitor._id) },
});
setSelectedMonitors(selectedMonitors);
};
// Utils
const theme = useTheme();
const { t } = useTranslation();
return (
<TabPanel value={tabValue}>
<Stack gap={theme.spacing(10)}>
<ConfigStack
title={t("statusPageCreateTabsContent")}
description={t("statusPageCreateTabsContentDescription")}
>
<Stack>
<Stack
direction="row"
justifyContent="space-between"
>
<Search
options={monitors}
multiple={true}
filteredBy="name"
value={selectedMonitors}
inputValue={search}
handleInputChange={setSearch}
handleChange={handleMonitorsChange}
/>
</Stack>
<Typography
component="span"
className="input-error"
color={theme.palette.error.main}
sx={{
opacity: 0.8,
}}
>
{errors["monitors"]}
</Typography>
<MonitorList
selectedMonitors={selectedMonitors}
setSelectedMonitors={handleMonitorsChange}
/>
</Stack>
</ConfigStack>
<ConfigStack
title={t("features")}
description={t("statusPageCreateTabsContentFeaturesDescription")}
>
<Stack>
<Checkbox
id="showCharts"
name="showCharts"
label={t("showCharts")}
isChecked={form.showCharts}
onChange={handleFormChange}
/>
<Checkbox
id="showUptimePercentage"
name="showUptimePercentage"
label={t("showUptimePercentage")}
isChecked={form.showUptimePercentage}
onChange={handleFormChange}
/>
</Stack>
</ConfigStack>
</Stack>
</TabPanel>
);
};
export default Content;
@@ -0,0 +1,146 @@
// Components
import { Stack, Typography } from "@mui/material";
import { TabPanel } from "@mui/lab";
import ConfigBox from "../../../../../Components/ConfigBox";
import Checkbox from "../../../../../Components/Inputs/Checkbox";
import TextInput from "../../../../../Components/Inputs/TextInput";
import Select from "../../../../../Components/Inputs/Select";
import ImageField from "../../../../../Components/Inputs/Image";
import ColorPicker from "../../../../../Components/Inputs/ColorPicker";
import Progress from "../Progress";
// Utils
import { useTheme } from "@emotion/react";
import timezones from "../../../../../Utils/timezones.json";
import PropTypes from "prop-types";
import { useTranslation } from "react-i18next";
const TabSettings = ({
isCreate,
tabValue,
form,
handleFormChange,
handleImageChange,
progress,
removeLogo,
errors,
}) => {
// Utils
const theme = useTheme();
const { t } = useTranslation();
return (
<TabPanel value={tabValue}>
<Stack gap={theme.spacing(10)}>
<ConfigBox>
<Stack>
<Typography component="h2">{t("access")}</Typography>
<Typography component="p">
{t("statusPageCreateSettings")}
</Typography>
</Stack>
<Stack gap={theme.spacing(18)}>
<Checkbox
id="publish"
name="isPublished"
label={t("statusPageCreateSettingsCheckboxLabel")}
isChecked={form.isPublished}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">{t("basicInformation")}</Typography>
<Typography component="p">
{t("statusPageCreateBasicInfoDescription")}
</Typography>
</Stack>
<Stack gap={theme.spacing(18)}>
<TextInput
id="companyName"
name="companyName"
type="text"
label={t("companyName")}
value={form.companyName}
onChange={handleFormChange}
helperText={errors["companyName"]}
error={errors["companyName"] ? true : false}
/>
<TextInput
id="url"
name="url"
type="url"
disabled={!isCreate}
label={t("statusPageCreateBasicInfoStatusPageAddress")}
value={form.url}
onChange={handleFormChange}
helperText={errors["url"]}
error={errors["url"] ? true : false}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">{t("timezone")}</Typography>
<Typography component="p">
{t("statusPageCreateSelectTimeZoneDescription")}
</Typography>
</Stack>
<Stack gap={theme.spacing(6)}>
<Select
id="timezone"
name="timezone"
label={t("settingsDisplayTimezone")}
items={timezones}
value={form.timezone}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">{t("settingsAppearance")}</Typography>
<Typography component="p">
{t("statusPageCreateAppearanceDescription")}
</Typography>
</Stack>
<Stack gap={theme.spacing(6)}>
<ImageField
id="logo"
src={form?.logo?.src}
isRound={false}
onChange={handleImageChange}
/>
<Progress
isLoading={progress.isLoading}
progressValue={progress.value}
logo={form.logo}
logoType={form.logo?.type}
removeLogo={removeLogo}
/>
<ColorPicker
id="color"
name="color"
value={form.color}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
</Stack>
</TabPanel>
);
};
TabSettings.propTypes = {
isCreate: PropTypes.bool,
tabValue: PropTypes.string,
form: PropTypes.object,
handleFormChange: PropTypes.func,
handleImageChange: PropTypes.func,
progress: PropTypes.object,
removeLogo: PropTypes.func,
errors: PropTypes.object,
};
export default TabSettings;
@@ -0,0 +1,86 @@
// Components
import { TabContext } from "@mui/lab";
import { Tab, useTheme } from "@mui/material";
import Settings from "./Settings";
import Content from "./Content";
// Utils
import PropTypes from "prop-types";
import CustomTabList from "../../../../../Components/Tab";
const Tabs = ({
isCreate,
form,
errors,
monitors,
selectedMonitors,
setSelectedMonitors,
handleFormChange,
handleImageChange,
progress,
removeLogo,
tab,
setTab,
TAB_LIST,
}) => {
const theme = useTheme();
return (
<TabContext value={TAB_LIST[tab]}>
<CustomTabList
onChange={(_, selected) => {
setTab(TAB_LIST.indexOf(selected));
}}
aria-label="status page tabs"
>
{TAB_LIST.map((tabLabel, idx) => (
<Tab
key={tabLabel}
label={tabLabel}
value={tabLabel}
/>
))}
</CustomTabList>
{tab === 0 ? (
<Settings
tabValue={TAB_LIST[0]}
form={form}
handleFormChange={handleFormChange}
handleImageChange={handleImageChange}
progress={progress}
removeLogo={removeLogo}
errors={errors}
isCreate={isCreate}
/>
) : (
<Content
tabValue={TAB_LIST[1]}
form={form}
monitors={monitors}
handleFormChange={handleFormChange}
errors={errors}
selectedMonitors={selectedMonitors}
setSelectedMonitors={setSelectedMonitors}
/>
)}
</TabContext>
);
};
Tabs.propTypes = {
form: PropTypes.object,
errors: PropTypes.object,
monitors: PropTypes.array,
selectedMonitors: PropTypes.array,
setSelectedMonitors: PropTypes.func,
handleFormChange: PropTypes.func,
handleImageChange: PropTypes.func,
progress: PropTypes.object,
removeLogo: PropTypes.func,
tab: PropTypes.number,
setTab: PropTypes.func,
TAB_LIST: PropTypes.array,
};
export default Tabs;
@@ -0,0 +1,28 @@
import { useState } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
const useCreateStatusPage = (isCreate, url) => {
const { user } = useSelector((state) => state.auth);
const [isLoading, setIsLoading] = useState(false);
const [networkError, setNetworkError] = useState(false);
const createStatusPage = async ({ form }) => {
setIsLoading(true);
try {
await networkService.createStatusPage({ user, form, isCreate, url });
return true;
} catch (error) {
setNetworkError(true);
createToast({ body: error?.response?.data?.msg ?? error.message });
return false;
} finally {
setIsLoading(false);
}
};
return [createStatusPage, isLoading, networkError];
};
export { useCreateStatusPage };
@@ -0,0 +1,34 @@
import { useEffect, useState } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
const useMonitorsFetch = () => {
const { user } = useSelector((state) => state.auth);
const [monitors, setMonitors] = useState(undefined);
const [isLoading, setIsLoading] = useState(true);
const [networkError, setNetworkError] = useState(false);
useEffect(() => {
const fetchMonitors = async () => {
try {
const response = await networkService.getMonitorsByTeamId({
teamId: user.teamId,
limit: null, // donot return any checks for the monitors
types: ["http"], // status page is available only for the uptime type
});
setMonitors(response.data.data.monitors);
} catch (error) {
setNetworkError(true);
createToast({ body: error.message });
} finally {
setIsLoading(false);
}
};
fetchMonitors();
}, [user]);
return [monitors, isLoading, networkError];
};
export { useMonitorsFetch };
@@ -0,0 +1,267 @@
// Components
import { Stack, Button, Typography } from "@mui/material";
import Tabs from "./Components/Tabs";
import GenericFallback from "../../../Components/GenericFallback";
import SkeletonLayout from "./Components/Skeleton";
import Breadcrumbs from "../../../Components/Breadcrumbs/index.jsx";
//Utils
import { useTheme } from "@emotion/react";
import { useState, useEffect, useRef, useCallback } from "react";
import { statusPageValidation } from "../../../Validation/validation";
import { buildErrors } from "../../../Validation/error";
import { useMonitorsFetch } from "./Hooks/useMonitorsFetch";
import { useCreateStatusPage } from "./Hooks/useCreateStatusPage";
import { createToast } from "../../../Utils/toastUtils";
import { useNavigate } from "react-router-dom";
import { useStatusPageFetch } from "../Status/Hooks/useStatusPageFetch";
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
//Constants
const TAB_LIST = ["General settings", "Contents"];
const ERROR_TAB_MAPPING = [
["companyName", "url", "timezone", "color", "isPublished", "logo"],
["monitors", "showUptimePercentage", "showCharts"],
];
const CreateStatusPage = () => {
const { url } = useParams();
//Local state
const [tab, setTab] = useState(0);
const [progress, setProgress] = useState({ value: 0, isLoading: false });
const [form, setForm] = useState({
isPublished: false,
companyName: "",
url: url ?? Math.floor(Math.random() * 1000000).toFixed(0),
logo: undefined,
timezone: "America/Toronto",
color: "#4169E1",
type: "uptime",
monitors: [],
showCharts: true,
showUptimePercentage: true,
});
const [errors, setErrors] = useState({});
const [selectedMonitors, setSelectedMonitors] = useState([]);
// Refs
const intervalRef = useRef(null);
// Setup
const isCreate = typeof url === "undefined";
//Utils
const theme = useTheme();
const [monitors, isLoading, networkError] = useMonitorsFetch();
const [createStatusPage, createStatusIsLoading, createStatusPageNetworkError] =
useCreateStatusPage(isCreate);
const navigate = useNavigate();
const { t } = useTranslation();
const [statusPage, statusPageMonitors, statusPageIsLoading, statusPageNetworkError] =
useStatusPageFetch(isCreate, url);
// Breadcrumbs
const crumbs = [
{ name: t("statusBreadCrumbsStatusPages"), path: "/status" },
];
if (isCreate) {
crumbs.push({ name: t("statusBreadCrumbsCreate"), path: "/status/uptime/create" });
} else {
crumbs.push(
{ name: t("statusBreadCrumbsDetails"), path: `/status/uptime/${statusPage?.url}` },
{ name: t("configure"), path: `/status/uptime/configure/${statusPage?.url}` }
);
}
// Handlers
const handleFormChange = (e) => {
let { type, name, value, checked } = e.target;
// Handle errors
const { error } = statusPageValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
return buildErrors(prev, name, error);
});
//Handle checkbox
if (type === "checkbox") {
setForm((prev) => ({
...prev,
[name]: checked,
}));
return;
}
// Handle other inputs
setForm((prev) => ({
...prev,
[name]: value,
}));
};
const handleImageChange = useCallback((event) => {
const img = event.target?.files?.[0];
const newLogo = {
src: URL.createObjectURL(img),
name: img.name,
type: img.type,
size: img.size,
};
setForm((prev) => ({
...prev,
logo: newLogo,
}));
intervalRef.current = setInterval(() => {
const buffer = 12;
setProgress((prev) => {
if (prev.value + buffer >= 100) {
clearInterval(intervalRef.current);
return { value: 100, isLoading: false };
}
return { ...prev, value: prev.value + buffer };
});
}, 120);
}, []);
const removeLogo = () => {
setForm((prev) => ({
...prev,
logo: undefined,
}));
// interrupt interval if image upload is canceled prior to completing the process
clearInterval(intervalRef.current);
setProgress({ value: 0, isLoading: false });
};
const handleSubmit = async () => {
let toSubmit = {
...form,
logo: { type: form.logo?.type ?? null, size: form.logo?.size ?? null },
};
const { error } = statusPageValidation.validate(toSubmit, {
abortEarly: false,
});
if (typeof error === "undefined") {
const success = await createStatusPage({ form });
if (success) {
createToast({
body: isCreate
? "Status page created successfully"
: "Status page updated successfully",
});
navigate(`/status/uptime/${form.url}`);
}
return;
}
const newErrors = {};
error?.details?.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors((prev) => ({ ...prev, ...newErrors }));
const errorTabs = Object.keys(newErrors).map((err) => {
return ERROR_TAB_MAPPING.findIndex((tab) => tab.includes(err));
});
// If there's an error in the current tab, don't change the tab
if (errorTabs.some((errorTab) => errorTab === tab)) {
return;
}
// If we get -1, there's an unknown error
if (errorTabs[0] === -1) {
createToast({ body: "Unknown error" });
return;
}
// Otherwise go to tab with error
setTab(errorTabs[0]);
};
// If we are configuring, populate fields
useEffect(() => {
if (isCreate) return;
if (typeof statusPage === "undefined") {
return;
}
let newLogo = undefined;
if (statusPage.logo) {
newLogo = {
src: `data:${statusPage.logo.contentType};base64,${statusPage.logo.data}`,
name: "logo",
type: statusPage.logo.contentType,
size: null,
};
}
setForm((prev) => {
return {
...prev,
companyName: statusPage?.companyName,
isPublished: statusPage?.isPublished,
timezone: statusPage?.timezone,
monitors: statusPageMonitors.map((monitor) => monitor._id),
color: statusPage?.color,
logo: newLogo,
};
});
setSelectedMonitors(statusPageMonitors);
}, [isCreate, statusPage, statusPageMonitors]);
if (networkError === true) {
return (
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
{t("networkError")}
</Typography>
<Typography>{t("checkConnection")}</Typography>
</GenericFallback>
);
}
if (isLoading) return <SkeletonLayout />;
// Load fields
return (
<Stack gap={theme.spacing(10)}>
<Breadcrumbs list={crumbs} />
<Tabs
form={form}
errors={errors}
monitors={monitors}
selectedMonitors={selectedMonitors}
setSelectedMonitors={setSelectedMonitors}
handleFormChange={handleFormChange}
handleImageChange={handleImageChange}
progress={progress}
removeLogo={removeLogo}
tab={tab}
setTab={setTab}
TAB_LIST={TAB_LIST}
isCreate={isCreate}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Button
variant="contained"
color="accent"
onClick={handleSubmit}
>
{t("settingsSave")}
</Button>
</Stack>
</Stack>
);
};
export default CreateStatusPage;