Files
jobtrackingapp/job-tracker-ui/src/components/NotificationsPopover.tsx
T

226 lines
9.4 KiB
TypeScript

import React, { useCallback, useEffect, useRef, useState } from "react";
import {
Alert,
Box,
Button,
CircularProgress,
Divider,
IconButton,
Popover,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import DoneIcon from "@mui/icons-material/Done";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import { notificationDateLabel, UserNotification } from "../notifications";
type Props = {
anchorEl: HTMLElement | null;
onClose: () => void;
onNavigate: (path: string) => void;
onChanged: () => void;
};
export default function NotificationsPopover({ anchorEl, onClose, onNavigate, onChanged }: Props) {
const { language, t } = useI18n();
const open = Boolean(anchorEl);
const [notifications, setNotifications] = useState<UserNotification[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<{ cause: unknown; action: boolean } | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const activeLoad = useRef<AbortController | null>(null);
const openGeneration = useRef(0);
const pendingAction = useRef(false);
const contentRef = useRef<HTMLDivElement>(null);
const headingRef = useRef<HTMLHeadingElement>(null);
const actionFocus = useRef<HTMLElement | null>(null);
const load = useCallback(async () => {
if (activeLoad.current || pendingAction.current) return;
const controller = new AbortController();
activeLoad.current = controller;
setLoading(true);
try {
const response = await api.get<UserNotification[]>("/notifications?limit=10", { signal: controller.signal });
if (controller.signal.aborted) return;
setNotifications(response.data ?? []);
setError(null);
} catch (requestError) {
if (!controller.signal.aborted) setError({ cause: requestError, action: false });
} finally {
if (activeLoad.current === controller) { activeLoad.current = null; setLoading(false); }
}
}, []);
useEffect(() => {
openGeneration.current += 1;
if (open) void load();
else {
activeLoad.current?.abort();
setNotifications([]);
setError(null);
setBusyId(null);
}
return () => {
openGeneration.current += 1;
activeLoad.current?.abort();
activeLoad.current = null;
pendingAction.current = false;
actionFocus.current = null;
};
}, [load, open]);
useEffect(() => {
if (!open || loading || busyId || !actionFocus.current) return;
const target = actionFocus.current;
actionFocus.current = null;
if (document.activeElement !== contentRef.current) return;
if (target.isConnected && !target.matches(":disabled")) target.focus();
else headingRef.current?.focus();
}, [busyId, loading, notifications, open]);
const rememberFocus = () => {
const active = document.activeElement;
if (active instanceof HTMLElement && active !== contentRef.current && contentRef.current?.contains(active)) {
actionFocus.current = active;
contentRef.current.focus();
}
};
const markRead = async (notification: UserNotification) => {
if (notification.readAtUtc) return true;
if (pendingAction.current) return false;
pendingAction.current = true;
const generation = openGeneration.current;
rememberFocus();
setBusyId(notification.id);
try {
await api.post(`/notifications/${notification.id}/read`);
if (generation !== openGeneration.current) return false;
setNotifications((items) => items.map((item) => item.id === notification.id
? { ...item, readAtUtc: new Date().toISOString() }
: item));
setError(null);
onChanged();
return true;
} catch (requestError) {
if (generation === openGeneration.current) setError({ cause: requestError, action: true });
return false;
} finally {
if (generation === openGeneration.current) { pendingAction.current = false; setBusyId(null); }
}
};
const dismiss = async (notification: UserNotification) => {
if (pendingAction.current) return;
pendingAction.current = true;
const generation = openGeneration.current;
rememberFocus();
setBusyId(notification.id);
try {
await api.delete(`/notifications/${notification.id}`);
if (generation !== openGeneration.current) return;
setNotifications((items) => items.filter((item) => item.id !== notification.id));
setError(null);
onChanged();
} catch (requestError) {
if (generation === openGeneration.current) setError({ cause: requestError, action: true });
} finally {
if (generation === openGeneration.current) { pendingAction.current = false; setBusyId(null); }
}
};
const openNotification = async (notification: UserNotification) => {
if (!notification.linkPath || pendingAction.current) return;
const generation = openGeneration.current;
if (!notification.readAtUtc && !await markRead(notification)) return;
if (generation !== openGeneration.current) return;
pendingAction.current = true;
onClose();
onNavigate(notification.linkPath);
};
return (
<Popover
open={open}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
transformOrigin={{ vertical: "top", horizontal: "right" }}
slotProps={{
paper: {
role: "dialog",
"aria-label": t("notificationsPanel"),
sx: {
mt: 1,
width: "min(420px, calc(100vw - 24px))",
maxHeight: "min(70vh, 600px)",
borderRadius: 1,
display: "flex",
flexDirection: "column",
overflow: "hidden",
},
},
}}
>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1.5, flexShrink: 0 }}>
<Box>
<Typography component="h2" variant="sectionTitle" ref={headingRef} tabIndex={-1}>{t("notifications")}</Typography>
<Typography variant="caption" color="text.secondary">{t("notificationsRecent")}</Typography>
</Box>
<Tooltip title={t("close")}>
<IconButton size="small" aria-label={t("close")} onClick={onClose}><CloseIcon fontSize="small" /></IconButton>
</Tooltip>
</Stack>
<Divider />
<Box ref={contentRef} role="region" aria-label={t("notificationsRecent")} tabIndex={-1} aria-busy={loading} sx={{ overflowY: "auto", minHeight: 0, p: 1 }}>
{loading ? <Box role="status" sx={{ py: 4, display: "grid", placeItems: "center" }}><CircularProgress size={28} aria-label={t("loading")} /></Box> : null}
{error ? <Alert severity="error" action={<Button color="inherit" size="small" disabled={loading || busyId !== null} onClick={() => { rememberFocus(); void load(); }}>{t("retry")}</Button>} sx={{ m: 0.5, overflowWrap: "anywhere" }}>{getApiErrorMessage(error.cause, t(error.action ? "notificationsActionFailed" : "notificationsLoadFailed"))}</Alert> : null}
{!loading && !error && notifications.length === 0 ? (
<Box sx={{ py: 4, px: 2, textAlign: "center" }}>
<Typography sx={{ fontWeight: 800 }}>{t("notificationsEmptyTitle")}</Typography>
<Typography variant="body2" color="text.secondary">{t("notificationsEmptyBody")}</Typography>
</Box>
) : null}
{!loading ? notifications.map((notification) => (
<Box
key={notification.id}
sx={{
p: 1.5,
mb: 0.75,
borderRadius: 1,
border: "1px solid",
borderColor: "divider",
bgcolor: notification.readAtUtc ? "transparent" : "action.selected",
}}
>
<Typography sx={{ fontWeight: notification.readAtUtc ? 600 : 700, overflowWrap: "anywhere" }}>{notification.title}</Typography>
{!notification.readAtUtc ? <Typography variant="caption" color="text.secondary">{t("notificationsUnread")}</Typography> : null}
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.25, overflowWrap: "anywhere" }}>{notification.message}</Typography>
<Typography variant="caption" color="text.secondary">{notificationDateLabel(notification.createdAtUtc, language === "nb" ? "nb-NO" : "en-GB")}</Typography>
<Stack direction="row" useFlexGap spacing={0.5} alignItems="center" sx={{ mt: 0.75, flexWrap: "wrap", "& .MuiButton-root": { whiteSpace: "normal", overflowWrap: "anywhere", minHeight: 40 } }}>
{notification.linkPath ? <Button size="small" disabled={busyId !== null} onClick={() => void openNotification(notification)}>{t("notificationsOpen")}</Button> : null}
{!notification.readAtUtc ? (
<Button size="small" startIcon={<DoneIcon />} disabled={busyId !== null} onClick={() => void markRead(notification)}>{t("notificationsMarkRead")}</Button>
) : null}
<Button size="small" color="inherit" startIcon={<DeleteOutlineIcon />} disabled={busyId !== null} onClick={() => void dismiss(notification)}>{t("notificationsDismiss")}</Button>
</Stack>
</Box>
)) : null}
</Box>
<Divider />
<Box sx={{ p: 1, flexShrink: 0 }}>
<Button fullWidth onClick={() => { onClose(); onNavigate("/operations"); }}>{t("notificationsViewAll")}</Button>
</Box>
</Popover>
);
}