fix(notifications): preserve action state and accessible recovery

This commit is contained in:
cesnimda
2026-10-16 23:14:33 +02:00
parent 9dfea1226f
commit 40cfe04df5
22 changed files with 5963 additions and 66 deletions
@@ -28,17 +28,21 @@ type Props = {
};
export default function NotificationsPopover({ anchorEl, onClose, onNavigate, onChanged }: Props) {
const { t } = useI18n();
const { language, t } = useI18n();
const open = Boolean(anchorEl);
const [notifications, setNotifications] = useState<UserNotification[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
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 () => {
activeLoad.current?.abort();
if (activeLoad.current || pendingAction.current) return;
const controller = new AbortController();
activeLoad.current = controller;
setLoading(true);
@@ -48,11 +52,11 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
setNotifications(response.data ?? []);
setError(null);
} catch (requestError) {
if (!controller.signal.aborted) setError(getApiErrorMessage(requestError, t("notificationsLoadFailed")));
if (!controller.signal.aborted) setError({ cause: requestError, action: false });
} finally {
if (activeLoad.current === controller) setLoading(false);
if (activeLoad.current === controller) { activeLoad.current = null; setLoading(false); }
}
}, [t]);
}, []);
useEffect(() => {
openGeneration.current += 1;
@@ -63,31 +67,61 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
setError(null);
setBusyId(null);
}
return () => activeLoad.current?.abort();
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 || busyId) return;
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;
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(getApiErrorMessage(requestError, t("notificationsActionFailed")));
if (generation === openGeneration.current) setError({ cause: requestError, action: true });
return false;
} finally {
if (generation === openGeneration.current) setBusyId(null);
if (generation === openGeneration.current) { pendingAction.current = false; setBusyId(null); }
}
};
const dismiss = async (notification: UserNotification) => {
if (busyId) return;
if (pendingAction.current) return;
pendingAction.current = true;
const generation = openGeneration.current;
rememberFocus();
setBusyId(notification.id);
try {
await api.delete(`/notifications/${notification.id}`);
@@ -96,17 +130,18 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
setError(null);
onChanged();
} catch (requestError) {
if (generation === openGeneration.current) setError(getApiErrorMessage(requestError, t("notificationsActionFailed")));
if (generation === openGeneration.current) setError({ cause: requestError, action: true });
} finally {
if (generation === openGeneration.current) setBusyId(null);
if (generation === openGeneration.current) { pendingAction.current = false; setBusyId(null); }
}
};
const openNotification = async (notification: UserNotification) => {
if (!notification.linkPath) return;
if (!notification.linkPath || pendingAction.current) return;
const generation = openGeneration.current;
if (!notification.readAtUtc) await markRead(notification);
if (!notification.readAtUtc && !await markRead(notification)) return;
if (generation !== openGeneration.current) return;
pendingAction.current = true;
onClose();
onNavigate(notification.linkPath);
};
@@ -120,20 +155,23 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
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: 3,
borderRadius: 1,
display: "flex",
flexDirection: "column",
overflow: "hidden",
},
},
}}
>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1.5 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1.5, flexShrink: 0 }}>
<Box>
<Typography component="h2" sx={{ fontWeight: 700 }}>{t("notifications")}</Typography>
<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")}>
@@ -142,34 +180,33 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
</Stack>
<Divider />
<Box sx={{ overflowY: "auto", maxHeight: "min(52vh, 450px)", p: 1 }}>
<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" onClick={() => void load()}>{t("retry")}</Button>} sx={{ m: 0.5 }}>{error}</Alert> : 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 && !error ? notifications.map((notification) => (
{!loading ? notifications.map((notification) => (
<Box
key={notification.id}
sx={{
p: 1.5,
mb: 0.75,
borderRadius: 2.5,
borderRadius: 1,
border: "1px solid",
borderColor: "divider",
bgcolor: notification.readAtUtc ? "transparent" : "action.selected",
opacity: notification.readAtUtc ? 0.82 : 1,
}}
>
<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)}</Typography>
<Stack direction="row" spacing={0.5} alignItems="center" sx={{ mt: 0.75, flexWrap: "wrap" }}>
{notification.linkPath ? <Button size="small" onClick={() => void openNotification(notification)}>{t("notificationsOpen")}</Button> : null}
<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}
@@ -180,7 +217,7 @@ export default function NotificationsPopover({ anchorEl, onClose, onNavigate, on
</Box>
<Divider />
<Box sx={{ p: 1 }}>
<Box sx={{ p: 1, flexShrink: 0 }}>
<Button fullWidth onClick={() => { onClose(); onNavigate("/operations"); }}>{t("notificationsViewAll")}</Button>
</Box>
</Popover>