import PropTypes from "prop-types"; import { Box, Button, Skeleton, Stack, Typography } from "@mui/material"; import { PieChart } from "@mui/x-charts/PieChart"; import { useDrawingArea } from "@mui/x-charts"; import { useEffect, useState } from "react"; import { useTheme } from "@emotion/react"; import { useNavigate, useParams } from "react-router-dom"; import { useSelector } from "react-redux"; import { formatDuration, formatDurationRounded, } from "../../../Utils/timeUtils"; import { logger } from "../../../Utils/Logger"; import { networkService } from "../../../main"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import LastCheckedIcon from "../../../assets/icons/calendar-check.svg?react"; import ClockIcon from "../../../assets/icons/maintenance.svg?react"; import IntervalCheckIcon from "../../../assets/icons/interval-check.svg?react"; import PageSpeedLineChart from "../../../Components/Charts/PagespeedLineChart"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import PulseDot from "../../../Components/Animated/PulseDot"; import "./index.css"; const StatBox = ({ icon, title, value }) => { const theme = useTheme(); return ( {icon} {title} {value} ); }; StatBox.propTypes = { icon: PropTypes.element, title: PropTypes.string, value: PropTypes.node, }; /** * Renders a centered label within a pie chart. * * @param {Object} props * @param {string | number} props.value - The value to display in the label. * @param {string} props.color - The color of the text. * @returns {JSX.Element} */ const PieCenterLabel = ({ value, color, setExpand }) => { const { width, height } = useDrawingArea(); return ( setExpand(true)} > {value} ); }; PieCenterLabel.propTypes = { value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), color: PropTypes.string, setExpand: PropTypes.func, }; /** * A component that renders a label on a pie chart slice. * The label is positioned relative to the center of the pie chart and is optionally highlighted. * * @param {Object} props * @param {number} props.value - The value to display inside the pie slice. * @param {number} props.startAngle - The starting angle of the pie slice in degrees. * @param {number} props.endAngle - The ending angle of the pie slice in degrees. * @param {string} props.color - The color of the label text when highlighted. * @param {boolean} props.highlighted - Determines if the label should be highlighted or not. * @returns {JSX.Element} */ const PieValueLabel = ({ value, startAngle, endAngle, color, highlighted }) => { const { width, height } = useDrawingArea(); // Compute the midpoint angle in radians const angle = (((startAngle + endAngle) / 2) * Math.PI) / 180; const radius = height / 3.5; // length from center of the circle to where the text is positioned // Calculate x and y positions const x = Math.sin(angle) * radius; const y = -Math.cos(angle) * radius; return ( +{value} ); }; PieValueLabel.propTypes = { value: PropTypes.number, startAngle: PropTypes.number, endAngle: PropTypes.number, color: PropTypes.string, highlighted: PropTypes.bool, }; /** * Renders a skeleton layout. * * @returns {JSX.Element} */ const SkeletonLayout = () => { const theme = useTheme(); return ( <> ); }; const PageSpeedDetails = () => { const theme = useTheme(); const navigate = useNavigate(); const [monitor, setMonitor] = useState({}); const [audits, setAudits] = useState({}); const { monitorId } = useParams(); const { authToken } = useSelector((state) => state.auth); useEffect(() => { const fetchMonitor = async () => { try { const res = await networkService.getStatsByMonitorId( authToken, monitorId, "desc", 50, "day", null, null ); console.log(res.data.data); setMonitor(res?.data?.data ?? {}); setAudits(res?.data?.data?.checks?.[0]?.audits ?? []); } catch (error) { logger.error(logger); navigate("/not-found", { replace: true }); } }; fetchMonitor(); }, [monitorId, authToken, navigate]); /** * Weight constants for different performance metrics. * @type {Object} */ const weights = { fcp: 10, si: 10, lcp: 25, tbt: 30, cls: 25, }; /** * Retrieves color properties based on the performance value. * * @param {number} value - The performance score used to determine the color properties. * @returns {{stroke: string, text: string, bg: string}} The color properties for the given performance value. */ const getColors = (value) => { if (value >= 90 && value <= 100) return { stroke: theme.palette.success.main, strokeBg: theme.palette.success.light, text: theme.palette.success.text, bg: theme.palette.success.bg, shape: "circle", }; else if (value >= 50 && value < 90) return { stroke: theme.palette.warning.main, strokeBg: theme.palette.warning.bg, text: theme.palette.warning.text, bg: theme.palette.warning.light, shape: "square", }; else if (value >= 0 && value < 50) return { stroke: theme.palette.error.text, strokeBg: theme.palette.error.light, text: theme.palette.error.text, bg: theme.palette.error.bg, shape: "circle", }; return { stroke: theme.palette.unresolved.main, strokeBg: theme.palette.unresolved.light, text: theme.palette.unresolved.main, bg: theme.palette.unresolved.bg, shape: "", }; }; /** * Calculates and formats the data needed for rendering a pie chart based on audit scores and weights. * This function generates properties for each pie slice, including angles, radii, and colors. * It also calculates performance based on the weighted values. * * @returns {Array} An array of objects, each representing the properties for a slice of the pie chart. * @returns {number} performance - A variable updated with the rounded sum of weighted values. */ let performance = 0; const getPieData = (audits) => { let props = []; let startAngle = 0; const padding = 3; // padding between arcs const max = 360 - padding * (Object.keys(audits).length - 1); // _id is a child of audits Object.keys(audits).forEach((key) => { if (audits[key].score) { let value = audits[key].score * weights[key]; let endAngle = startAngle + (weights[key] * max) / 100; let theme = getColors(audits[key].score * 100); props.push({ id: key, data: [ { value: value, color: theme.stroke, label: key.toUpperCase(), }, { value: weights[key] - value, color: theme.strokeBg, label: "", }, ], arcLabel: (item) => `${item.label}`, arcLabelRadius: 95, startAngle: startAngle, endAngle: endAngle, innerRadius: 73, outerRadius: 80, cornerRadius: 2, highlightScope: { faded: "global", highlighted: "series" }, faded: { innerRadius: 63, outerRadius: 70, additionalRadius: -20, arcLabelRadius: 5, }, cx: pieSize.width / 2, }); performance += Math.round(value); startAngle = endAngle + padding; } }); return props; }; const pieSize = { width: 210, height: 200 }; const pieData = getPieData(audits); const colorMap = getColors(performance); const [highlightedItem, setHighLightedItem] = useState(null); const [expand, setExpand] = useState(false); let loading = Object.keys(monitor).length === 0; const data = monitor?.checks ? [...monitor.checks].reverse() : []; let sharedStyles = { border: 1, borderColor: theme.palette.border.light, borderRadius: theme.shape.borderRadius, backgroundColor: theme.palette.background.main, }; return ( {loading ? ( ) : ( <> {monitor?.url} Your pagespeed monitor is live. } title="Last checked" value={ <> {formatDuration(monitor?.lastChecked)}{" "} ago } /> } title="Checks since" value={ <> {formatDuration(monitor?.uptimeDuration)}{" "} ago } > } title="Checks every" value={formatDurationRounded(monitor?.interval)} > Score history Performance report setExpand(false)}> {expand ? ( {pieData?.map((pie) => ( ))} ) : ( )} Values are estimated and may vary.{" "} See calculator The{" "} performance score is calculated {" "} directly from these{" "} metrics . {Object.keys(audits).map((key) => { if (key === "_id") return; let audit = audits[key]; let metricParams = getColors(audit.score * 100); let shape = ( ); if (metricParams.shape === "square") shape = ( ); else if (metricParams.shape === "triangle") shape = ( ); // Find the position where the number ends and the unit begins const match = audit.displayValue.match( /(\d+\.?\d*)\s*([a-zA-Z]+)/ ); let value; let unit; if (match) { value = match[1]; unit = match[2]; } else { value = audit.displayValue; } return ( {shape} {audit.title} {value} {unit} ); })} )} ); }; PageSpeedDetails.propTypes = { push: PropTypes.func, }; export default PageSpeedDetails;