refactor: created current monitoring component and changed isLoading initial to true because of glitch

This commit is contained in:
Caio Cabral committed 2024-10-18 17:29:11 -04:00
1 parent 5adca16b55
commit 704348d1f9
5 files changed
+371 -338

No files matched your search

+158 -165
View File
@@ -1,12 +1,5 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import { Box, ListItem, Autocomplete, TextField, Stack, Typography } from "@mui/material";
Box,
ListItem,
Autocomplete,
TextField,
Stack,
Typography,
} from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import SearchIcon from "../../../assets/icons/search.svg?react"; import SearchIcon from "../../../assets/icons/search.svg?react";
@@ -24,172 +17,172 @@ import SearchIcon from "../../../assets/icons/search.svg?react";
*/ */
const SearchAdornment = () => { const SearchAdornment = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Box <Box
mr={theme.spacing(4)} mr={theme.spacing(4)}
height={16} height={16}
sx={{ sx={{
"& svg": { "& svg": {
width: 16, width: 16,
height: 16, height: 16,
"& path": { "& path": {
stroke: theme.palette.text.tertiary, stroke: theme.palette.text.tertiary,
strokeWidth: 1.2, strokeWidth: 1.2,
}, },
}, },
}} }}
> >
<SearchIcon /> <SearchIcon />
</Box> </Box>
); );
}; };
//TODO keep search state inside of component
const Search = ({ const Search = ({
id, id,
options, options,
filteredBy, filteredBy,
secondaryLabel, secondaryLabel,
value, value,
inputValue, inputValue,
handleInputChange, handleInputChange,
handleChange, handleChange,
sx, sx,
multiple = false, multiple = false,
isAdorned = true, isAdorned = true,
error, error,
disabled, disabled,
}) => { }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Autocomplete <Autocomplete
multiple={multiple} multiple={multiple}
id={id} id={id}
value={value} value={value}
inputValue={inputValue} inputValue={inputValue}
onInputChange={(_, newValue) => { onInputChange={(_, newValue) => {
handleInputChange(newValue); handleInputChange(newValue);
}} }}
onChange={(_, newValue) => { onChange={(_, newValue) => {
handleChange && handleChange(newValue); handleChange && handleChange(newValue);
}} }}
fullWidth fullWidth
freeSolo freeSolo
disabled={disabled} disabled={disabled}
disableClearable disableClearable
options={options} options={options}
getOptionLabel={(option) => option[filteredBy]} getOptionLabel={(option) => option[filteredBy]}
renderInput={(params) => ( renderInput={(params) => (
<Stack> <Stack>
<TextField <TextField
{...params} {...params}
error={Boolean(error)} error={Boolean(error)}
placeholder="Type to search" placeholder="Type to search"
InputProps={{ InputProps={{
...params.InputProps, ...params.InputProps,
...(isAdorned && { startAdornment: <SearchAdornment /> }), ...(isAdorned && { startAdornment: <SearchAdornment /> }),
}} }}
sx={{ sx={{
"& fieldset": { "& fieldset": {
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
}, },
"& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset": "& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
{ {
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
}, },
}} }}
/> />
{error && ( {error && (
<Typography <Typography
component="span" component="span"
className="input-error" className="input-error"
color={theme.palette.error.text} color={theme.palette.error.text}
mt={theme.spacing(2)} mt={theme.spacing(2)}
sx={{ sx={{
opacity: 0.8, opacity: 0.8,
}} }}
> >
{error} {error}
</Typography> </Typography>
)} )}
</Stack> </Stack>
)} )}
filterOptions={(options, { inputValue }) => { filterOptions={(options, { inputValue }) => {
const filtered = options.filter((option) => const filtered = options.filter((option) =>
option[filteredBy].toLowerCase().includes(inputValue.toLowerCase()) option[filteredBy].toLowerCase().includes(inputValue.toLowerCase())
); );
if (filtered.length === 0) { if (filtered.length === 0) {
return [{ [filteredBy]: "No monitors found", noOptions: true }]; return [{ [filteredBy]: "No monitors found", noOptions: true }];
} }
return filtered; return filtered;
}} }}
renderOption={(props, option) => { renderOption={(props, option) => {
const { key, ...optionProps } = props; const { key, ...optionProps } = props;
return ( return (
<ListItem <ListItem
key={key} key={key}
{...optionProps} {...optionProps}
sx={ sx={
option.noOptions option.noOptions
? { ? {
pointerEvents: "none", pointerEvents: "none",
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
} }
: {} : {}
} }
> >
{option[filteredBy] + {option[filteredBy] + (secondaryLabel ? ` (${option[secondaryLabel]})` : "")}
(secondaryLabel ? ` (${option[secondaryLabel]})` : "")} </ListItem>
</ListItem> );
); }}
}} slotProps={{
slotProps={{ popper: {
popper: { keepMounted: true,
keepMounted: true, sx: {
sx: { "& ul": { p: 2 },
"& ul": { p: 2 }, "& li.MuiAutocomplete-option": {
"& li.MuiAutocomplete-option": { color: theme.palette.text.secondary,
color: theme.palette.text.secondary, px: 4,
px: 4, borderRadius: theme.shape.borderRadius,
borderRadius: theme.shape.borderRadius, },
}, "& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover":
"& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover": {
{ backgroundColor: theme.palette.background.fill,
backgroundColor: theme.palette.background.fill, },
}, "& .MuiAutocomplete-noOptions": {
"& .MuiAutocomplete-noOptions": { px: theme.spacing(6),
px: theme.spacing(6), py: theme.spacing(5),
py: theme.spacing(5), },
}, },
}, },
}, }}
}} sx={{
sx={{ height: 34,
height: 34, "&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 },
"&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 }, ...sx,
...sx, }}
}} />
/> );
);
}; };
Search.propTypes = { Search.propTypes = {
id: PropTypes.string, id: PropTypes.string,
multiple: PropTypes.bool, multiple: PropTypes.bool,
options: PropTypes.array.isRequired, options: PropTypes.array.isRequired,
filteredBy: PropTypes.string.isRequired, filteredBy: PropTypes.string.isRequired,
secondaryLabel: PropTypes.string, secondaryLabel: PropTypes.string,
value: PropTypes.array, value: PropTypes.array,
inputValue: PropTypes.string.isRequired, inputValue: PropTypes.string.isRequired,
handleInputChange: PropTypes.func.isRequired, handleInputChange: PropTypes.func.isRequired,
handleChange: PropTypes.func, handleChange: PropTypes.func,
isAdorned: PropTypes.bool, isAdorned: PropTypes.bool,
sx: PropTypes.object, sx: PropTypes.object,
error: PropTypes.string, error: PropTypes.string,
disabled: PropTypes.bool, disabled: PropTypes.bool,
}; };
export default Search; export default Search;
@@ -0,0 +1,79 @@
import { useTheme } from "@emotion/react";
import { Box, Stack, Typography } from "@mui/material";
import Search from "../../../../Components/Inputs/Search";
import MemoizedMonitorTable from "../MonitorTable";
import { useState } from "react";
import useDebounce from "../../../../Utils/debounce";
import PropTypes from "prop-types";
const CurrentMonitoring = ({ totalMonitors, monitors, isAdmin }) => {
const theme = useTheme();
const [search, setSearch] = useState("");
const [isSearching, setIsSearching] = useState(false);
const debouncedFilter = useDebounce(search, 500);
const handleSearch = (value) => {
setIsSearching(true);
setSearch(value);
};
return (
<Box
flex={1}
px={theme.spacing(10)}
py={theme.spacing(8)}
border={1}
borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main}
>
<Stack
direction="row"
alignItems="center"
mb={theme.spacing(8)}
>
<Typography
component="h2"
variant="h2"
fontWeight={500}
letterSpacing={-0.2}
>
Actively monitoring
</Typography>
<Box
className="current-monitors-counter"
color={theme.palette.text.primary}
border={1}
borderColor={theme.palette.border.light}
backgroundColor={theme.palette.background.accent}
>
{totalMonitors}
</Box>
<Box
width="25%"
minWidth={150}
ml="auto"
>
<Search
options={monitors}
filteredBy="name"
inputValue={search}
handleInputChange={handleSearch}
/>
</Box>
</Stack>
<MemoizedMonitorTable
isAdmin={isAdmin}
filter={debouncedFilter}
setIsSearching={setIsSearching}
isSearching={isSearching}
/>
</Box>
);
};
CurrentMonitoring.propTypes = {
totalMonitors: PropTypes.number,
monitors: PropTypes.array,
isAdmin: PropTypes.bool,
};
export { CurrentMonitoring };
@@ -109,7 +109,7 @@ TablePaginationActions.propTypes = {
onPageChange: PropTypes.func.isRequired, onPageChange: PropTypes.func.isRequired,
}; };
const MonitorTable = ({ isAdmin, filter, setLoading, isSearching }) => { const MonitorTable = ({ isAdmin, filter, setIsSearching, isSearching }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
@@ -162,15 +162,25 @@ const MonitorTable = ({ isAdmin, filter, setLoading, isSearching }) => {
}); });
setMonitors(res?.data?.data?.monitors ?? []); setMonitors(res?.data?.data?.monitors ?? []);
setMonitorCount(res?.data?.data?.monitorCount ?? 0); setMonitorCount(res?.data?.data?.monitorCount ?? 0);
setLoading(false);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
} finally {
setIsSearching(false);
} }
}, [authState, page, rowsPerPage, filter, sort, setLoading]); }, [authState, page, rowsPerPage, filter, sort, setIsSearching]);
useEffect(() => { useEffect(() => {
fetchPage(); fetchPage();
}, [updateTrigger, authState, page, rowsPerPage, filter, sort, setLoading, fetchPage]); }, [
updateTrigger,
authState,
page,
rowsPerPage,
filter,
sort,
setIsSearching,
fetchPage,
]);
// Listen for changes in filter, if new value reset the page // Listen for changes in filter, if new value reset the page
useEffect(() => { useEffect(() => {
@@ -459,7 +469,7 @@ const MonitorTable = ({ isAdmin, filter, setLoading, isSearching }) => {
MonitorTable.propTypes = { MonitorTable.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
filter: PropTypes.string, filter: PropTypes.string,
setLoading: PropTypes.func, setIsSearching: PropTypes.func,
isSearching: PropTypes.bool, isSearching: PropTypes.bool,
}; };
+10 -66
View File
@@ -1,19 +1,17 @@
import "./index.css"; import "./index.css";
import { useEffect, useState } from "react"; import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { Box, Button, Stack, Typography } from "@mui/material"; import { Box, Button, Stack } from "@mui/material";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import Fallback from "./fallback"; import Fallback from "./fallback";
import StatusBox from "./StatusBox"; import StatusBox from "./StatusBox";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Breadcrumbs from "../../../Components/Breadcrumbs";
import Greeting from "../../../Utils/greeting"; import Greeting from "../../../Utils/greeting";
import MonitorTable from "./MonitorTable"; import { CurrentMonitoring } from "./CurrentMonitoring";
import Search from "../../../Components/Inputs/Search";
import useDebounce from "../../../Utils/debounce";
const Monitors = ({ isAdmin }) => { const Monitors = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
@@ -22,20 +20,12 @@ const Monitors = ({ isAdmin }) => {
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const dispatch = useDispatch({}); const dispatch = useDispatch({});
//TODO create components, and lower these states.
const [search, setSearch] = useState("");
const [isSearching, setIsSearching] = useState(false);
const debouncedFilter = useDebounce(search, 500);
const handleSearch = (value) => {
setIsSearching(true);
setSearch(value);
};
useEffect(() => { useEffect(() => {
dispatch(getUptimeMonitorsByTeamId(authState.authToken)); dispatch(getUptimeMonitorsByTeamId(authState.authToken));
}, [authState.authToken, dispatch]); }, [authState.authToken, dispatch]);
//TODO bring fetching to this component, like on pageSpeed
const loading = monitorState?.isLoading; const loading = monitorState?.isLoading;
const totalMonitors = monitorState?.monitorsSummary?.monitorCounts?.total; const totalMonitors = monitorState?.monitorsSummary?.monitorCounts?.total;
@@ -100,57 +90,11 @@ const Monitors = ({ isAdmin }) => {
value={monitorState?.monitorsSummary?.monitorCounts?.paused ?? 0} value={monitorState?.monitorsSummary?.monitorCounts?.paused ?? 0}
/> />
</Stack> </Stack>
<Box <CurrentMonitoring
flex={1} isAdmin={isAdmin}
px={theme.spacing(10)} monitors={monitorState.monitorsSummary.monitors}
py={theme.spacing(8)} totalMonitors={totalMonitors}
border={1} />
borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main}
>
<Stack
direction="row"
alignItems="center"
mb={theme.spacing(8)}
>
<Typography
component="h2"
variant="h2"
fontWeight={500}
letterSpacing={-0.2}
>
Actively monitoring
</Typography>
<Box
className="current-monitors-counter"
color={theme.palette.text.primary}
border={1}
borderColor={theme.palette.border.light}
backgroundColor={theme.palette.background.accent}
>
{totalMonitors}
</Box>
<Box
width="25%"
minWidth={150}
ml="auto"
>
<Search
options={monitorState.monitorsSummary.monitors}
filteredBy="name"
inputValue={search}
handleInputChange={handleSearch}
/>
</Box>
</Stack>
<MonitorTable
isAdmin={isAdmin}
filter={debouncedFilter}
setLoading={setIsSearching}
isSearching={isSearching}
/>
</Box>
</> </>
)} )}
</> </>
+109 -102
View File
@@ -14,114 +14,121 @@ import Card from "./card";
import { networkService } from "../../main"; import { networkService } from "../../main";
const PageSpeed = ({ isAdmin }) => { const PageSpeed = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigate = useNavigate(); const navigate = useNavigate();
const { user, authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(true);
const [monitors, setMonitors] = useState([]); const [monitors, setMonitors] = useState([]);
useEffect(() => { useEffect(() => {
dispatch(getPageSpeedByTeamId(authToken)); dispatch(getPageSpeedByTeamId(authToken));
}, [authToken, dispatch]); }, [authToken, dispatch]);
useEffect(() => { useEffect(() => {
const fetchMonitors = async () => { const fetchMonitors = async () => {
try { try {
setIsLoading(true); setIsLoading(true);
const res = await networkService.getMonitorsByTeamId({ const res = await networkService.getMonitorsByTeamId({
authToken: authToken, authToken: authToken,
teamId: user.teamId, teamId: user.teamId,
limit: 10, limit: 10,
types: ["pagespeed"], types: ["pagespeed"],
status: null, status: null,
checkOrder: "desc", checkOrder: "desc",
normalize: true, normalize: true,
page: null, page: null,
rowsPerPage: null, rowsPerPage: null,
filter: null, filter: null,
field: null, field: null,
order: null, order: null,
}); });
if (res?.data?.data?.monitors) { if (res?.data?.data?.monitors) {
setMonitors(res.data.data.monitors); setMonitors(res.data.data.monitors);
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
fetchMonitors(); fetchMonitors();
}, []); }, []);
// will show skeletons only on initial load // will show skeletons only on initial load
// since monitor state is being added to redux persist, there's no reason to display skeletons on every render // since monitor state is being added to redux persist, there's no reason to display skeletons on every render
let isActuallyLoading = isLoading && monitors?.length === 0; let isActuallyLoading = isLoading && monitors?.length === 0;
return ( console.log({ isActuallyLoading });
<Box return (
className="page-speed" <Box
sx={{ className="page-speed"
':has(> [class*="fallback__"])': { sx={{
position: "relative", ':has(> [class*="fallback__"])': {
border: 1, position: "relative",
borderColor: theme.palette.border.light, border: 1,
borderRadius: theme.shape.borderRadius, borderColor: theme.palette.border.light,
borderStyle: "dashed", borderRadius: theme.shape.borderRadius,
backgroundColor: theme.palette.background.main, borderStyle: "dashed",
overflow: "hidden", backgroundColor: theme.palette.background.main,
}, overflow: "hidden",
}} },
> }}
{isActuallyLoading ? ( >
<SkeletonLayout /> <Box mb={theme.spacing(12)}>
) : monitors?.length !== 0 ? ( <Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} />
<Box> <Stack
<Box mb={theme.spacing(12)}> direction="row"
<Breadcrumbs list={[{ name: `pagespeed`, path: "/pagespeed" }]} /> justifyContent="space-between"
<Stack alignItems="center"
direction="row" mt={theme.spacing(5)}
justifyContent="space-between" >
alignItems="center" <Greeting type="pagespeed" />
mt={theme.spacing(5)} {isAdmin && (
> <Button
<Greeting type="pagespeed" /> variant="contained"
{isAdmin && ( color="primary"
<Button onClick={() => navigate("/pagespeed/create")}
variant="contained" sx={{ whiteSpace: "nowrap" }}
color="primary" >
onClick={() => navigate("/pagespeed/create")} Create new
sx={{ whiteSpace: "nowrap" }} </Button>
> )}
Create new </Stack>
</Button> </Box>
)} {isActuallyLoading ? (
</Stack> <SkeletonLayout />
</Box> ) : monitors?.length !== 0 ? (
<Grid container spacing={theme.spacing(12)}> <Box>
{monitors?.map((monitor) => ( <Grid
<Card monitor={monitor} key={monitor._id} /> container
))} spacing={theme.spacing(12)}
</Grid> >
</Box> {monitors?.map((monitor) => (
) : ( <Card
<Fallback monitor={monitor}
title="pagespeed monitor" key={monitor._id}
checks={[ />
"Report on the user experience of a page", ))}
"Help analyze webpage speed", </Grid>
"Give suggestions on how the page can be improved", </Box>
]} ) : (
link="/pagespeed/create" <Fallback
isAdmin={isAdmin} title="pagespeed monitor"
/> checks={[
)} "Report on the user experience of a page",
</Box> "Help analyze webpage speed",
); "Give suggestions on how the page can be improved",
]}
link="/pagespeed/create"
isAdmin={isAdmin}
/>
)}
</Box>
);
}; };
PageSpeed.propTypes = { PageSpeed.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default PageSpeed; export default PageSpeed;