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

63 lines
1.5 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";
import { Modal } from "../../ui/React/Modal";
import Typography from "@mui/material/Typography";
2021-10-04 03:33:48 +02:00
import Box from "@mui/material/Box";
2021-10-01 07:00:50 +02:00
export const AlertEvents = new EventEmitter<[string | JSX.Element]>();
interface Alert {
id: string;
text: string | JSX.Element;
}
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) => {
return [
...old,
{
id: id,
text: text,
},
];
});
}),
[],
);
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);
}, []);
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" }}>
2021-10-04 03:33:48 +02:00
<Typography>{alerts[0].text}</Typography>
</Box>
2021-10-01 07:00:50 +02:00
</Modal>
)}
</>
);
}