www-new/components/WarningHeader.tsx

78 lines
2.2 KiB
TypeScript

import { parse } from "date-fns";
import { utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";
import React from "react";
import warnings from "../content/warnings/warnings.json";
import styles from "./WarningHeader.module.css";
// Had to add these functions here, since we cannot use import the file from ./lib/events since that uses libraries only on the serverside
const WARNING_DATE_FORMAT = "MMMM dd yyyy HH:mm";
function getLocalDateFromEST(date: Date) {
return utcToZonedTime(
// The parsed date is in EST
zonedTimeToUtc(date, "America/Toronto"),
Intl.DateTimeFormat().resolvedOptions().timeZone
);
}
interface Warning {
message: string;
startDate: string;
endDate: string;
}
function getCurrentWarning(): Warning | null {
const today = new Date();
let currentWarning: Warning | null = null;
warnings.forEach((warning) => {
if (!warning.startDate || !warning.endDate) {
console.error("INVALID WARNING:", warning);
}
// convert dates to date objects in EST time zone
let startDate = parse(warning.startDate, WARNING_DATE_FORMAT, new Date());
let endDate = parse(warning.endDate, WARNING_DATE_FORMAT, new Date());
if (
!startDate ||
!endDate ||
isNaN(startDate.getTime()) || // this checks if the parsed date is not valid (eg. wrong format)
isNaN(endDate.getTime())
) {
console.error("WARNING WITH INVALID DATES:", warning);
return; // skip to next warning in loop, this one is invalid
}
startDate = getLocalDateFromEST(startDate);
endDate = getLocalDateFromEST(endDate);
// check if current time is in warning range
if (
startDate.getTime() < today.getTime() &&
endDate.getTime() > today.getTime()
) {
if (currentWarning) {
console.error(
"ERROR: TWO WARNINGS SCHEDULED AT SAME TIME! ",
currentWarning,
warning
);
}
currentWarning = warning;
}
});
return currentWarning;
}
export function WarningHeader() {
const warning = getCurrentWarning();
return !warning || warning.message == "" ? (
<></>
) : (
<div className={styles.warning}>{warning.message}</div>
);
}