bitburner-src/src/ui/React/AlertManager.tsx

75 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-10-01 07:00:50 +02:00
import React, { useState, useEffect } from "react";
import { EventEmitter } from "../../utils/EventEmitter";
2022-03-06 05:05:55 +01:00
import { Modal } from "./Modal";
2021-10-01 07:00:50 +02:00
import Typography from "@mui/material/Typography";
2021-10-04 03:33:48 +02:00
import Box from "@mui/material/Box";
2022-03-21 02:26:10 +01:00
import { sha256 } from "js-sha256";
2021-10-01 07:00:50 +02:00
export const AlertEvents = new EventEmitter<[string | JSX.Element]>();
interface Alert {
id: string;
text: string | JSX.Element;
hash: string;
2021-10-01 07:00:50 +02:00
}
let i = 0;
export function AlertManager(): React.ReactElement {
const [alerts, setAlerts] = useState<Alert[]>([]);
useEffect(
() =>
AlertEvents.subscribe((text: string | JSX.Element) => {
const id = i + "";
i++;
setAlerts((old) => {
const hash = getMessageHash(text);
2022-03-21 02:26:10 +01:00
if (old.some((a) => a.hash === hash)) {
return old;
}
2021-10-01 07:00:50 +02:00
return [
...old,
{
id: id,
text: text,
hash: hash,
2021-10-01 07:00:50 +02:00
},
];
});
}),
[],
);
2021-12-20 21:48:26 +01:00
useEffect(() => {
function handle(this: Document, event: KeyboardEvent): void {
if (event.code === "Escape") {
setAlerts([]);
}
}
document.addEventListener("keydown", handle);
return () => document.removeEventListener("keydown", handle);
}, []);
function getMessageHash(text: string | JSX.Element): string {
2022-03-21 02:26:10 +01:00
if (typeof text === "string") return sha256(text);
return sha256(JSON.stringify(text.props));
}
2021-10-01 07:00:50 +02:00
function close(): void {
setAlerts((old) => {
return old.slice(1, 1e99);
2021-10-01 07:00:50 +02:00
});
}
return (
<>
{alerts.length > 0 && (
<Modal open={true} onClose={close}>
2021-10-04 19:15:04 +02:00
<Box overflow="scroll" sx={{ overflowWrap: "break-word", whiteSpace: "pre-line" }}>
2022-04-07 01:30:08 +02:00
<Typography component={"span"}>{alerts[0].text}</Typography>
2021-10-04 03:33:48 +02:00
</Box>
2021-10-01 07:00:50 +02:00
</Modal>
)}
</>
);
}