initial commit

This commit is contained in:
Alex Holliday committed 2025-02-18 09:47:54 -08:00
commit 6dbb6dad7e
371 files changed
+53232

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
import store from "../store";
const LOG_LEVEL = import.meta.env.VITE_APP_LOG_LEVEL || "debug";
const NO_OP = () => {};
class Logger {
constructor() {
let logLevel = LOG_LEVEL;
this.unsubscribe = store.subscribe(() => {
const state = store.getState();
logLevel = state.settings.logLevel || "debug";
this.updateLogLevel(logLevel);
});
}
updateLogLevel(logLevel) {
if (logLevel === "none") {
this.info = NO_OP;
this.error = NO_OP;
this.warn = NO_OP;
this.log = NO_OP;
return;
}
if (logLevel === "error") {
this.error = console.error.bind(console);
this.info = NO_OP;
this.warn = NO_OP;
this.log = NO_OP;
return;
}
if (logLevel === "warn") {
this.error = console.error.bind(console);
this.warn = console.warn.bind(console);
this.info = NO_OP;
this.log = NO_OP;
return;
}
if (logLevel === "info") {
this.error = console.error.bind(console);
this.warn = console.warn.bind(console);
this.info = console.info.bind(console);
this.log = NO_OP;
return;
}
if (logLevel === "debug") {
this.error = console.error.bind(console);
this.warn = console.warn.bind(console);
this.info = console.info.bind(console);
this.log = console.log.bind(console);
return;
}
}
cleanup() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
}
export const logger = new Logger();
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router";
import { setNetworkService } from "./NetworkService";
import NetworkService, { networkService } from "./NetworkService";
import { store } from "../store";
const NetworkServiceProvider = ({ children }) => {
const dispatch = useDispatch();
const navigate = useNavigate();
if (!networkService) {
setNetworkService(new NetworkService(store, dispatch, navigate));
}
return children;
};
export default NetworkServiceProvider;
+1
View File
@@ -0,0 +1 @@
#Utils folder
+271
View File
@@ -0,0 +1,271 @@
import { lighten, darken } from "@mui/material/styles"; // CAIO_REVIEW
const typographyBase = 14;
/* TODO
Check for px in codebase. All font sizes should be in REM and should live here.
Rest should be checked on each case
*/
const typographyLevels = {
base: typographyBase,
xs: `${(typographyBase - 4) / 16}rem`,
s: `${(typographyBase - 2) / 16}rem`,
m: `${typographyBase / 16}rem`,
l: `${(typographyBase + 2) / 16}rem`,
xl: `${(typographyBase + 10) / 16}rem`,
};
/* TODO Review color palette and semantic colors */
const paletteColors = {
white: "#FFFFFF",
gray50: "#FEFEFE",
gray60: "#FEFDFE",
gray70: "#FDFDFD",
gray80: "#FDFCFD",
gray90: "#FCFCFD",
gray100: "#F4F4F4",
gray150: "#EFEFEF",
gray200: "#E3E3E3",
gray300: "#A2A3A3",
gray500: "#838C99",
gray600: "#454546",
gray750: "#36363E",
gray800: "#2D2D33",
gray850: "#131315",
gray860: "#111113",
gray870: "#0F0F11",
gray880: "#0C0C0E",
gray890: "#09090B",
blueGray20: "#E8F0FE",
blueGray150: "#667085",
blueGray200: "#475467",
blueGray400: "#344054",
blueGray900: "#1c2130",
blueBlueWave: "#1570EF",
blue700: "#4E5BA6",
purple300: "#664EFF",
purple400: "#3A1BFF",
green50: "#D4F4E1",
green150: "#45BB7A",
green400: "#079455",
green500: "#07B467",
green800: "#1C4428",
green900: "#12261E",
red50: "#F9ECED",
red100: "#FBD1D1",
red200: "#F04438",
red300: "#D32F2F",
red700: "#542426",
red800: "#912018",
orange50: "#FEF8EA",
orange100: "#FFECBC",
orange300: "#FDB022",
orange400: "#FF9F00",
orange500: "#E88C30",
orange600: "#DC6803",
orange800: "#624711",
};
const semanticColors = {
unresolved: {
main: {
light: paletteColors.blue700,
dark: paletteColors.purple300,
},
light: {
light: paletteColors.blueGray20,
dark: paletteColors.purple400,
},
bg: {
light: paletteColors.gray100,
dark: paletteColors.gray100,
},
},
};
const newColors = {
offWhite: "#FEFEFE",
offBlack: "#131315",
gray100: "#F3F3F3",
gray200: "#EFEFEF",
gray500: "#A2A3A3",
blueGray50: "#E8F0FE",
blueGray500: "#475467",
blueGray600: "#344054",
blueGray800: "#1C2130",
blueBlueWave: "#1570EF",
/* I changed green 100 and green 700. Need to change red and warning as well, and refactor the object following the structure */
green100: "#67cd78",
green200: "#4B9B77",
green400: "#079455",
green700: "#026513",
orange100: "#FD8F22",
orange200: "#D69A5D",
orange600: "#9B734B",
orange700: "#884605",
red100: "#F27C7C",
red400: "#D92020",
red600: "#9B4B4B",
red700: "#980303",
};
/*
Structure:
main: background color
contrastText: color for main contrast text
contrastTextSecondary: if needed
contrastTextTertiary: if needed
lowContrast: if we need some low contrast for that color (for borders, and decorative elements). This should never be usend in text
*/
const newSemanticColors = {
accent: {
main: {
light: newColors.blueBlueWave,
dark: newColors.blueBlueWave,
},
light: {
light: lighten(newColors.blueBlueWave, 0.2), //CAIO_REVIEW
dark: lighten(newColors.blueBlueWave, 0.2), //CAIO_REVIEW
},
darker: {
// CAIO_REVIEW
light: darken(newColors.blueBlueWave, 0.2), // CAIO_REVIEW
dark: darken(newColors.blueBlueWave, 0.2), // CAIO_REVIEW
},
contrastText: {
light: newColors.offWhite,
dark: newColors.offWhite,
},
},
primary: {
main: {
light: newColors.offWhite,
dark: newColors.offBlack,
},
contrastText: {
light: newColors.blueGray800,
dark: newColors.blueGray50,
},
contrastTextSecondary: {
light: newColors.blueGray600,
dark: newColors.gray200,
},
// CAIO_REVIEW, need a brighter color for dark bg
contrastTextSecondaryDarkBg: {
light: newColors.gray200,
dark: newColors.gray200,
},
contrastTextTertiary: {
light: newColors.blueGray500,
dark: newColors.gray500,
},
lowContrast: {
light: newColors.gray200,
dark: newColors.blueGray600,
},
},
secondary: {
main: {
light: newColors.gray200,
dark: "#313131" /* newColors.blueGray600 */,
},
contrastText: {
light: newColors.blueGray600,
dark: newColors.gray200,
},
},
tertiary: {
main: {
light: newColors.gray100,
dark: newColors.blueGray800,
},
contrastText: {
light: newColors.blueGray800,
dark: newColors.gray100,
},
},
success: {
main: {
light: newColors.green700,
dark: newColors.green100,
},
contrastText: {
light: newColors.offWhite,
dark: newColors.offBlack,
},
lowContrast: {
light: newColors.green400,
dark: newColors.green200,
},
},
warning: {
main: {
light: newColors.orange700,
dark: newColors.orange200,
},
contrastText: {
light: newColors.offWhite,
dark: newColors.offBlack,
},
lowContrast: {
light: newColors.orange100,
dark: newColors.orange600,
},
},
error: {
main: {
light: newColors.red700,
dark: newColors.red100,
},
contrastText: {
light: newColors.offWhite,
dark: newColors.offBlack,
},
lowContrast: {
light: newColors.red400,
dark: newColors.red600,
},
},
/* These are temporary, just for everything not to break */
gradient: {
color1: {
light: paletteColors.gray90,
dark: paletteColors.gray890,
},
color2: {
light: paletteColors.gray80,
dark: paletteColors.gray880,
},
color3: {
light: paletteColors.gray70,
dark: paletteColors.gray870,
},
color4: {
light: paletteColors.gray60,
dark: paletteColors.gray860,
},
color5: {
light: paletteColors.gray50,
dark: paletteColors.gray850,
},
},
map: {
main: {
light: newColors.offWhite,
dark: undefined,
},
lowContrast: {
light: newColors.gray200,
dark: undefined,
},
highContrast: {
light: newColors.gray500,
dark: undefined,
},
},
};
export { typographyLevels, semanticColors as colors, newSemanticColors };
+13
View File
@@ -0,0 +1,13 @@
import { createTheme } from "@mui/material";
import { baseTheme } from "./globalTheme";
import { /* colors, */ newSemanticColors } from "./constants";
import { extractThemeColors } from "./extractColorObject";
const palette = extractThemeColors("dark", newSemanticColors);
const darkTheme = createTheme({
palette,
...baseTheme(palette),
});
export default darkTheme;
+25
View File
@@ -0,0 +1,25 @@
function extractThemeColors(themeType, colorObject) {
if (!["light", "dark"].includes(themeType)) {
throw new Error('Invalid theme type. Use "light" or "dark".');
}
const extract = (obj) => {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if ("light" in obj && "dark" in obj) {
// CAIO_REVIEW: This will break if the root object has light and dark properties
return obj[themeType]; // Return the value for the specified theme
}
// Reduce the object, keeping only the extracted themeType values
return Object.keys(obj).reduce((acc, key) => {
acc[key] = extract(obj[key]);
return acc;
}, {});
};
return extract(colorObject);
}
export { extractThemeColors };
+392
View File
@@ -0,0 +1,392 @@
import { typographyLevels } from "./constants";
const fontFamilyPrimary = '"Inter" , sans-serif';
// const fontFamilySecondary = '"Avenir", sans-serif';
/* TODO take the color out from here */
const shadow =
"0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03)";
const baseTheme = (palette) => ({
typography: {
fontFamily: fontFamilyPrimary,
fontSize: 14,
h1: {
fontSize: typographyLevels.xl,
color: palette.primary.contrastText,
fontWeight: 500,
},
h2: {
fontSize: typographyLevels.l,
color: palette.primary.contrastTextSecondary,
fontWeight: 400,
},
// CAIO_REVIEW, need a brighter color for dark bg
h2DarkBg: {
fontSize: typographyLevels.l,
color: palette.primary.contrastTextSecondaryDarkBg,
fontWeight: 400,
},
body1: {
fontSize: typographyLevels.m,
color: palette.primary.contrastTextTertiary,
fontWeight: 400,
},
body2: {
fontSize: typographyLevels.s,
color: palette.primary.contrastTextTertiary,
fontWeight: 400,
},
},
/* TODO change to 4 */
spacing: 2,
/* TODO we can skip using the callback functions on the next lines since we are already accessing it on line 10. That was the last thing I managed to do, so we are sort of doing it twice*/
/* TODO All these should live inside of a component*/
components: {
MuiButton: {
defaultProps: {
disableRipple: true,
},
styleOverrides: {
root: ({ theme }) => ({
variants: [
{
props: (props) => props.color === "accent",
style: {
"&:hover": {
backgroundColor: theme.palette.accent.darker,
},
},
},
{
props: (props) => props.color === "error",
style: {
"&.Mui-disabled": {
backgroundColor: theme.palette.error.lowContrast,
},
"& .MuiButton-loadingIndicator": {
// styles for error variant loading indicator
color: theme.palette.error.contrastText,
},
},
},
{
props: (props) => props.variant === "group",
style: {
/* color: theme.palette.secondary.contrastText, */
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
},
},
{
props: (props) => props.variant === "group" && props.filled === "true",
style: {
backgroundColor: theme.palette.secondary.main,
},
},
/* {
props: (props) => props.variant === "contained",
style: {
backgroundColor: `${theme.palette.accent.main} !important`,
},
}, */
{
props: (props) =>
props.variant === "contained" && props.color === "secondary",
style: {
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
},
},
{
props: (props) => {
return (
props.variant === "contained" &&
props.disabled &&
props?.classes?.loadingIndicator === undefined // Do not apply to loading button
);
},
style: {
backgroundColor: `${theme.palette.secondary.main} !important`,
color: `${theme.palette.secondary.contrastText} !important`,
},
},
],
fontWeight: 400,
borderRadius: 4,
boxShadow: "none",
textTransform: "none",
"&:focus": {
outline: "none",
},
"&:hover": {
boxShadow: "none",
},
"&.Mui-disabled": {
backgroundColor: theme.palette.secondary.main,
color: theme.palette.primary.contrastText,
},
"&.MuiButton-root": {
"&:disabled": {
backgroundColor: theme.palette.secondary.main,
color: theme.palette.primary.contrastText,
},
"&.MuiButton-colorAccent:hover": {
boxShadow: `0 0 0 1px ${theme.palette.accent.main}`, // CAIO_REVIEW, this should really have a solid BG color
},
},
"&.MuiButton-loading": {
"&:disabled": {
color: "transparent",
},
"& .MuiButton-loadingIndicator": {
color: theme.palette.primary.contrastText,
},
},
}),
},
},
MuiIconButton: {
styleOverrides: {
root: ({ theme }) => ({
padding: 4,
transition: "none",
"&:hover": {
backgroundColor: theme.palette.primary.lowContrast,
},
}),
},
},
MuiPaper: {
styleOverrides: {
root: ({ theme }) => {
return {
marginTop: 4,
padding: 0,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
borderRadius: 4,
boxShadow: shadow,
backgroundColor: theme.palette.primary.main,
backgroundImage: "none",
};
},
},
},
MuiList: {
styleOverrides: {
root: {
padding: 0,
},
},
},
MuiListItemButton: {
styleOverrides: {
root: {
transition: "none",
},
},
},
MuiMenuItem: {
styleOverrides: {
root: ({ theme }) => ({
borderRadius: 4,
backgroundColor: "inherit",
padding: "4px 6px",
color: theme.palette.primary.contrastTextSecondary,
fontSize: 13,
margin: 2,
minWidth: 100,
"&:hover, &.Mui-selected, &.Mui-selected:hover, &.Mui-selected.Mui-focusVisible":
{
backgroundColor: theme.palette.primary.lowContrast,
},
}),
},
},
MuiTableCell: {
styleOverrides: {
root: ({ theme }) => ({
borderBottomColor: theme.palette.primary.lowContrast,
}),
},
},
MuiTableHead: {
styleOverrides: {
root: ({ theme }) => ({
backgroundColor: theme.palette.tertiary.main,
}),
},
},
MuiPagination: {
styleOverrides: {
root: ({ theme }) => ({
backgroundColor: theme.palette.primary.main,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
"& button": {
color: theme.palette.primary.contrastTextTertiary,
borderRadius: 4,
},
"& li:first-of-type button, & li:last-of-type button": {
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
},
}),
},
},
MuiPaginationItem: {
styleOverrides: {
root: ({ theme }) => ({
"&:not(.MuiPaginationItem-ellipsis):hover, &.Mui-selected": {
backgroundColor: theme.palette.primary.lowContrast,
},
}),
},
},
MuiSkeleton: {
styleOverrides: {
root: ({ theme }) => ({
backgroundColor: theme.palette.primary.lowContrast,
}),
},
},
MuiTextField: {
styleOverrides: {
root: ({ theme }) => ({
"& fieldset": {
borderColor: theme.palette.primary.lowContrast,
borderRadius: theme.shape.borderRadius,
},
"& .MuiInputBase-input": {
padding: ".75em",
minHeight: "var(--env-var-height-2)",
fontSize: "var(--env-var-font-size-medium)",
fontWeight: 400,
color: palette.primary.contrastTextSecondary,
"&.Mui-disabled": {
opacity: 0.3,
WebkitTextFillColor: "unset",
},
"& .Mui-focused": {
/* color: "#ff0000", */
/* borderColor: theme.palette.primary.contrastText, */
},
},
"& .MuiInputBase-input:-webkit-autofill": {
transition: "background-color 5000s ease-in-out 0s",
WebkitBoxShadow: `0 0 0px 1000px ${theme.palette.primary.main} inset`,
WebkitTextFillColor: theme.palette.primary.contrastText,
},
"& .MuiInputBase-input.MuiOutlinedInput-input": {
padding: "0 var(--env-var-spacing-1-minus) !important",
},
"& .MuiOutlinedInput-root": {
color: theme.palette.primary.contrastTextSecondary,
borderRadius: 4,
},
"& .MuiOutlinedInput-notchedOutline": {
borderRadius: 4,
},
"& .MuiFormHelperText-root": {
color: palette.error.main,
opacity: 0.8,
fontSize: "var(--env-var-font-size-medium)",
marginLeft: 0,
},
"& .MuiFormHelperText-root.Mui-error": {
opacity: 0.8,
fontSize: "var(--env-var-font-size-medium)",
color: palette.error.main,
},
}),
},
},
MuiOutlinedInput: {
styleOverrides: {
root: {
color: palette.primary.contrastTextTertiary,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: palette.primary.contrastTextTertiary,
},
},
},
},
MuiTab: {
styleOverrides: {
root: ({ theme }) => ({
fontSize: 13,
color: theme.palette.tertiary.contrastText,
backgroundColor: theme.palette.tertiary.main,
textTransform: "none",
minWidth: "fit-content",
paddingY: theme.spacing(6),
fontWeight: 400,
borderBottom: "2px solid transparent",
borderRight: `1px solid ${theme.palette.primary.lowContrast}`,
"&:first-of-type": { borderTopLeftRadius: "8px" },
"&:last-child": { borderTopRightRadius: "8px", borderRight: 0 },
"&:focus-visible": {
color: theme.palette.primary.contrastText,
borderColor: theme.palette.tertiary.contrastText,
borderRightColor: theme.palette.primary.lowContrast,
},
"&.Mui-selected": {
backgroundColor: theme.palette.secondary.main,
color: theme.palette.secondary.contrastText,
borderColor: theme.palette.secondary.contrastText,
borderRightColor: theme.palette.primary.lowContrast,
},
"&:hover": {
borderColor: theme.palette.primary.lowContrast,
},
}),
},
},
MuiSvgIcon: {
styleOverrides: {
root: ({ theme }) => ({
color: theme.palette.primary.contrastTextTertiary,
}),
},
},
MuiTabs: {
styleOverrides: {
root: ({ theme }) => ({
"& .MuiTabs-indicator": {
backgroundColor: theme.palette.tertiary.contrastText,
},
}),
},
},
MuiSwitch: {
styleOverrides: {
root: ({ theme }) => ({
"& .MuiSwitch-track": {
backgroundColor: theme.palette.primary.contrastText,
},
}),
},
},
},
shape: {
borderRadius: 2,
borderThick: 2,
boxShadow: shadow,
},
});
export { baseTheme };
+12
View File
@@ -0,0 +1,12 @@
import { createTheme } from "@mui/material";
import { baseTheme } from "./globalTheme";
import { /* colors, */ newSemanticColors } from "./constants";
import { extractThemeColors } from "./extractColorObject";
const palette = extractThemeColors("light", newSemanticColors);
const lightTheme = createTheme({
palette,
...baseTheme(palette),
});
export default lightTheme;
+18
View File
@@ -0,0 +1,18 @@
import { useState, useEffect } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
+11
View File
@@ -0,0 +1,11 @@
export const formatBytes = (bytes) => {
if (bytes === 0) return "0 Bytes";
const megabytes = bytes / (1024 * 1024);
return megabytes.toFixed(2) + " MB";
};
export const checkImage = (url) => {
const img = new Image();
img.src = url;
return img.naturalWidth !== 0;
};
+194
View File
@@ -0,0 +1,194 @@
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
import { Box, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { setGreeting } from "../Features/UI/uiSlice";
const early = [
{
prepend: "Rise and shine",
append: "If you’re up this early, you might as well be a legend!",
emoji: "☕",
},
{
prepend: "Good morning",
append: "The world’s still asleep, but you’re already awesome!",
emoji: "🦉",
},
{
prepend: "Good morning",
append: "Are you a wizard? Only magical people are up at this hour!",
emoji: "🌄",
},
{
prepend: "Up before the roosters",
append: "Ready to tackle the day before it even starts?",
emoji: "🐓",
},
{
prepend: "Early bird special",
append: "Let’s get things done while everyone else is snoozing!",
emoji: "🌟",
},
];
const morning = [
{
prepend: "Good morning",
append: "Is it coffee o’clock yet, or should we start with high fives?",
emoji: "☕",
},
{
prepend: "Morning",
append: "The sun is up, and so are you—time to be amazing!",
emoji: "🌞",
},
{
prepend: "Good morning",
append: "Time to make today the best thing since sliced bread!",
emoji: "🥐",
},
{
prepend: "Morning",
append: "Let’s kick off the day with more energy than a double espresso!",
emoji: "🚀",
},
{
prepend: "Rise and shine",
append: "You’re about to make today so great, even Monday will be jealous!",
emoji: "🌟",
},
];
const afternoon = [
{
prepend: "Good afternoon",
append: "How about a break to celebrate how awesome you’re doing?",
emoji: "🥪",
},
{
prepend: "Afternoon",
append: "If you’re still going strong, you’re officially a rockstar!",
emoji: "🌞",
},
{
prepend: "Hey there",
append: "The afternoon is your playground—let’s make it epic!",
emoji: "🍕",
},
{
prepend: "Good afternoon",
append: "Time to crush the rest of the day like a pro!",
emoji: "🏆",
},
{
prepend: "Afternoon",
append: "Time to turn those afternoon slumps into afternoon triumphs!",
emoji: "🎉",
},
];
const evening = [
{
prepend: "Good evening",
append: "Time to wind down and think about how you crushed today!",
emoji: "🌇",
},
{
prepend: "Evening",
append: "You’ve earned a break—let’s make the most of these evening vibes!",
emoji: "🍹",
},
{
prepend: "Hey there",
append: "Time to relax and bask in the glow of your day’s awesomeness!",
emoji: "🌙",
},
{
prepend: "Good evening",
append: "Ready to trade productivity for chill mode?",
emoji: "🛋️ ",
},
{
prepend: "Evening",
append: "Let’s call it a day and toast to your success!",
emoji: "🕶️",
},
];
/**
* Greeting component that displays a personalized greeting message
* based on the time of day and the user's first name.
*
* @component
* @example
* return <Greeting type={"pagespeed"} />;
*
* @param {Object} props
* @param {string} props.type - The type of monitor to be displayed in the message
* @returns {JSX.Element} The rendered Greeting component
*/
const Greeting = ({ type = "" }) => {
const theme = useTheme();
const dispatch = useDispatch();
const { firstName } = useSelector((state) => state.auth.user);
const index = useSelector((state) => state.ui.greeting.index);
const lastUpdate = useSelector((state) => state.ui.greeting.lastUpdate);
const now = new Date();
const hour = now.getHours();
useEffect(() => {
const hourDiff = lastUpdate ? hour - lastUpdate : null;
if (!lastUpdate || hourDiff >= 1) {
let random = Math.floor(Math.random() * 5);
dispatch(setGreeting({ index: random, lastUpdate: hour }));
}
}, [dispatch, hour]);
let greetingArray =
hour < 6 ? early : hour < 12 ? morning : hour < 18 ? afternoon : evening;
const { prepend, append, emoji } = greetingArray[index];
return (
<Box>
<Typography
component="h1"
variant="h1"
mb={theme.spacing(1)}
>
<Typography
component="span"
fontSize="inherit"
color={theme.palette.primary.contrastTextTertiary}
>
{prepend},{" "}
</Typography>
<Typography
component="span"
fontSize="inherit"
fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
>
{firstName} {emoji}
</Typography>
</Typography>
<Typography
variant="h2"
lineHeight={1}
color={theme.palette.primary.contrastTextTertiary}
>
{append} — Here’s an overview of your {type} monitors.
</Typography>
</Box>
);
};
Greeting.propTypes = {
type: PropTypes.string,
};
export default Greeting;
+37
View File
@@ -0,0 +1,37 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import { setLanguage } from "../Features/UI/uiSlice";
import store from "../store";
const primaryLanguage = "gb";
const translations = import.meta.glob("../locales/*.json", { eager: true });
const resources = {};
Object.keys(translations).forEach((path) => {
const langCode = path.match(/\/([^/]+)\.json$/)[1];
resources[langCode] = {
translation: translations[path].default || translations[path],
};
});
const savedLanguage = store.getState()?.ui?.language;
const initialLanguage = savedLanguage || primaryLanguage;
i18n.use(initReactI18next).init({
resources,
lng: initialLanguage,
fallbackLng: primaryLanguage,
debug: import.meta.env.MODE === "development",
ns: ["translation"],
defaultNS: "translation",
interpolation: {
escapeValue: false,
},
});
i18n.on("languageChanged", (lng) => {
store.dispatch(setLanguage(lng));
});
export default i18n;
+38
View File
@@ -0,0 +1,38 @@
import { capitalizeFirstLetter } from "./stringUtils";
/**
* Helper function to get duration since last check or the last date checked
* @param {Array} checks Array of check objects.
* @param {boolean} duration Whether the function should return the duration since last checked or the date itself
* @returns {number} Timestamp of the most recent check.
*/
export const getLastChecked = (checks, duration = true) => {
if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available
}
// Data is sorted newest -> oldest, so newest check is the most recent
if (!duration) {
return new Date(checks[0].createdAt);
}
return new Date() - new Date(checks[0].createdAt);
};
export const parseDomainName = (url) => {
url = url.replace(/^https?:\/\//, "");
// Remove leading/trailing dots
url = url.replace(/^\.+|\.+$/g, "");
// Split by dots
const parts = url.split(".");
// Remove common prefixes and empty parts and exclude the last element of the array (the last element should be the TLD)
const cleanParts = parts.filter((part) => part !== "www" && part !== "").slice(0, -1);
// If there's more than one part, append the two words and capitalize the first letters (e.g. ["api", "test"] -> "Api Test")
const domainPart =
cleanParts.length > 1
? cleanParts.map((part) => capitalizeFirstLetter(part)).join(" ")
: capitalizeFirstLetter(cleanParts[0]);
if (domainPart) return domainPart;
return url;
};
+36
View File
@@ -0,0 +1,36 @@
/**
* Helper function to get first letter capitalized string
* @param {string} str String whose first letter is to be capitalized
* @returns A string with first letter capitalized
*/
export const capitalizeFirstLetter = (str) => {
if (str === null || str === undefined) {
return "";
}
if (typeof str !== "string") {
throw new TypeError("Input must be a string");
}
if (str.length === 0) {
return "";
}
return str.charAt(0).toUpperCase() + str.slice(1);
};
/**
* Helper function to get first letter as a lower case string
* @param {string} str String whose first letter is to be lower cased
* @returns A string with first letter lower cased
*/
export const toLowerCaseFirstLetter = (str) => {
if (str === null || str === undefined) {
return "";
}
if (typeof str !== "string") {
throw new TypeError("Input must be a string");
}
if (str.length === 0) {
return "";
}
return str.charAt(0).toLowerCase() + str.slice(1);
};
+117
View File
@@ -0,0 +1,117 @@
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import customParseFormat from "dayjs/plugin/customParseFormat";
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);
dayjs.extend(duration);
export const MS_PER_SECOND = 1000;
export const MS_PER_MINUTE = 60 * MS_PER_SECOND;
export const MS_PER_HOUR = 60 * MS_PER_MINUTE;
export const MS_PER_DAY = 24 * MS_PER_HOUR;
export const MS_PER_WEEK = MS_PER_DAY * 7;
export const formatDuration = (ms) => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
let dateStr = "";
days && (dateStr += `${days}d `);
hours && (dateStr += `${hours % 24}h `);
minutes && (dateStr += `${minutes % 60}m `);
seconds && (dateStr += `${seconds % 60}s `);
dateStr === "" && (dateStr = "0s");
return dateStr;
};
export const formatDurationRounded = (ms) => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
let time = "";
if (days > 0) {
time += `${days} day${days !== 1 ? "s" : ""}`;
return time;
}
if (hours > 0) {
time += `${hours} hour${hours !== 1 ? "s" : ""}`;
return time;
}
if (minutes > 0) {
time += `${minutes} minute${minutes !== 1 ? "s" : ""}`;
return time;
}
if (seconds > 0) {
time += `${seconds} second${seconds !== 1 ? "s" : ""}`;
return time;
}
return time;
};
export const formatDurationSplit = (ms) => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return days > 0
? { time: days, format: days === 1 ? "day" : "days" }
: hours > 0
? { time: hours, format: hours === 1 ? "hour" : "hours" }
: minutes > 0
? { time: minutes, format: minutes === 1 ? "minute" : "minutes" }
: seconds > 0
? { time: seconds, format: seconds === 1 ? "second" : "seconds" }
: { time: 0, format: "seconds" };
};
export const getHumanReadableDuration = (ms) => {
const durationObj = dayjs.duration(ms);
if (durationObj.asDays() >= 1) {
const days = Math.floor(durationObj.asDays());
return { time: days, units: days === 1 ? "day" : "days" };
} else if (durationObj.asHours() >= 1) {
const hours = Math.floor(durationObj.asHours());
return { time: hours, units: hours === 1 ? "hour" : "hours" };
} else if (durationObj.asMinutes() >= 1) {
const minutes = Math.floor(durationObj.asMinutes());
return { time: minutes, units: minutes === 1 ? "minute" : "minutes" };
} else {
const seconds = Math.floor(durationObj.asSeconds());
return { time: seconds, units: seconds === 1 ? "second" : "seconds" };
}
};
export const formatDate = (date, customOptions) => {
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
...customOptions,
};
// Return the date using the specified options
return date
.toLocaleString("en-US", options)
.replace(/\b(AM|PM)\b/g, (match) => match.toLowerCase());
};
export const formatDateWithTz = (timestamp, format, timezone) => {
const formattedDate = dayjs(timestamp).tz(timezone).format(format);
return formattedDate;
};
File diff suppressed because it is too large. Load diff
+51
View File
@@ -0,0 +1,51 @@
import PropTypes from "prop-types";
import { toast, Slide } from "react-toastify";
import Alert from "../Components/Alert";
/**
* @param {object} props
* @param {'info' | 'error' | 'warning'} - The variant of the alert (e.g., "info", "error").
* @param {string} props.title - The title of the alert.
* @param {string} props.body - The body/content of the alert.
* @param {boolean} props.hasIcon - Whether the alert should include an icon.
* @param {object} [props.config] - Additional configuration props for the toast.
*/
export const createToast = ({
variant = "info",
title,
body,
hasIcon = false,
config = {},
}) => {
const toastConfig = {
position: "top-right",
autoClose: 3000,
hideProgressBar: true,
closeButton: false,
transition: Slide,
...config,
};
toast(
({ closeToast }) => (
<Alert
variant={variant}
title={title}
body={body}
isToast={true}
hasIcon={hasIcon}
onClick={closeToast}
/>
),
toastConfig
);
};
createToast.propTypes = {
variant: PropTypes.oneOf(["info", "error", "warning"]),
title: PropTypes.string,
body: PropTypes.string.isRequired,
hasIcon: PropTypes.bool,
config: PropTypes.object,
};