feat(settings): preserve drafts and connection recovery
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
Box,
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
InputLabel,
|
||||
MenuItem,
|
||||
Select,
|
||||
Skeleton,
|
||||
Tab,
|
||||
Tabs,
|
||||
Typography,
|
||||
@@ -30,6 +29,7 @@ import { useI18n } from "../i18n/I18nProvider";
|
||||
import { api, getApiErrorMessage } from "../api";
|
||||
import { useToast } from "../toast";
|
||||
import { PageSection } from "../layout/PageLayout";
|
||||
import ViewStateNotice from "./ViewStateNotice";
|
||||
|
||||
interface Props {
|
||||
pageSize: 15 | 20 | 25;
|
||||
@@ -66,21 +66,38 @@ export default function SettingsView({
|
||||
const { language, setLanguage, t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs | null>(null);
|
||||
const [notificationError, setNotificationError] = useState<string | null>(null);
|
||||
const [savedNotificationPrefs, setSavedNotificationPrefs] = useState<NotificationPrefs | null>(null);
|
||||
const [notificationError, setNotificationError] = useState<{ cause: unknown; action: boolean } | null>(null);
|
||||
const [loadingNotifications, setLoadingNotifications] = useState(true);
|
||||
const [savingNotifications, setSavingNotifications] = useState(false);
|
||||
const [savedRules, setSavedRules] = useState<RuleSettings | null>(null);
|
||||
const [rulesDraft, setRulesDraft] = useState<RuleDraft | null>(null);
|
||||
const [rulesLoadError, setRulesLoadError] = useState<string | null>(null);
|
||||
const [rulesLoadError, setRulesLoadError] = useState<{ cause: unknown } | null>(null);
|
||||
const [rulesSaveError, setRulesSaveError] = useState(false);
|
||||
const [invalidRules, setInvalidRules] = useState<RuleField[]>([]);
|
||||
const [savingRules, setSavingRules] = useState(false);
|
||||
const rulesSession = useRef({ mounted: true, loading: false, saving: false });
|
||||
const notificationSession = useRef({ mounted: true, loading: false, saving: false, generation: 0 });
|
||||
const notificationBody = useRef<HTMLDivElement>(null);
|
||||
const notificationRetryFocus = useRef<HTMLElement | null>(null);
|
||||
const currentTranslation = useRef(t);
|
||||
const rulesDirty = Boolean(rulesDraft && savedRules && RULE_FIELDS.some(field => rulesDraft[field] !== String(savedRules[field])));
|
||||
const notificationsDirty = Boolean(notificationPrefs && savedNotificationPrefs && notificationPrefs.emailFollowUpRemindersEnabled !== savedNotificationPrefs.emailFollowUpRemindersEnabled);
|
||||
|
||||
useEffect(() => { currentTranslation.current = t; }, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
const session = rulesSession.current;
|
||||
const notifications = notificationSession.current;
|
||||
session.mounted = true;
|
||||
return () => { session.mounted = false; };
|
||||
notifications.mounted = true;
|
||||
return () => {
|
||||
session.mounted = false;
|
||||
notifications.mounted = false;
|
||||
notifications.generation += 1;
|
||||
notifications.loading = false;
|
||||
notifications.saving = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadRules = async () => {
|
||||
@@ -94,7 +111,7 @@ export default function SettingsView({
|
||||
setSavedRules(data);
|
||||
setRulesDraft(ruleDraft(data));
|
||||
} catch (error) {
|
||||
if (session.mounted) setRulesLoadError(getApiErrorMessage(error, t("rulesLoadFailed")));
|
||||
if (session.mounted) setRulesLoadError({ cause: error });
|
||||
} finally { session.loading = false; }
|
||||
};
|
||||
|
||||
@@ -120,7 +137,7 @@ export default function SettingsView({
|
||||
setSavedRules(submitted);
|
||||
// A completed save acknowledges its snapshot, not edits made while it was pending.
|
||||
setRulesDraft(current => current && RULE_FIELDS.every(field => current[field] === submittedDraft[field]) ? ruleDraft(submitted) : current);
|
||||
toast(t("rulesSaved"), "success");
|
||||
toast(currentTranslation.current("rulesSaved"), "success");
|
||||
} catch {
|
||||
if (session.mounted) setRulesSaveError(true);
|
||||
} finally {
|
||||
@@ -136,27 +153,74 @@ export default function SettingsView({
|
||||
setRulesSaveError(false);
|
||||
};
|
||||
|
||||
const loadNotifications = useCallback(async () => {
|
||||
const session = notificationSession.current;
|
||||
if (!session.mounted || session.loading) return;
|
||||
const generation = session.generation;
|
||||
session.loading = true;
|
||||
setLoadingNotifications(true);
|
||||
setNotificationError(null);
|
||||
try {
|
||||
const { data } = await api.get<NotificationPrefs>("/notification-settings");
|
||||
if (!session.mounted || generation !== session.generation) return;
|
||||
setNotificationPrefs(data);
|
||||
setSavedNotificationPrefs(data);
|
||||
} catch (cause) {
|
||||
if (session.mounted && generation === session.generation) setNotificationError({ cause, action: false });
|
||||
} finally {
|
||||
if (generation === session.generation) {
|
||||
session.loading = false;
|
||||
if (session.mounted) setLoadingNotifications(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void loadNotifications(); }, [loadNotifications]);
|
||||
|
||||
const retryNotifications = () => {
|
||||
const active = document.activeElement;
|
||||
if (active instanceof HTMLElement && notificationBody.current?.contains(active)) notificationRetryFocus.current = active;
|
||||
void loadNotifications();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.get<NotificationPrefs>("/notification-settings")
|
||||
.then(({ data }) => { if (active) setNotificationPrefs(data); })
|
||||
.catch((error) => { if (active) setNotificationError(getApiErrorMessage(error, t("settingsNotificationsLoadFailed"))); });
|
||||
return () => { active = false; };
|
||||
}, [t]);
|
||||
const target = notificationRetryFocus.current;
|
||||
if (loadingNotifications || !target) return;
|
||||
notificationRetryFocus.current = null;
|
||||
if (!target.isConnected && document.activeElement === document.body) notificationBody.current?.focus();
|
||||
}, [loadingNotifications, notificationError, notificationPrefs]);
|
||||
|
||||
const saveNotifications = async () => {
|
||||
if (!notificationPrefs) return;
|
||||
const session = notificationSession.current;
|
||||
if (!session.mounted || !notificationPrefs || session.saving) return;
|
||||
const submitted = { emailFollowUpRemindersEnabled: notificationPrefs.emailFollowUpRemindersEnabled };
|
||||
const generation = session.generation;
|
||||
session.saving = true;
|
||||
setSavingNotifications(true);
|
||||
setNotificationError(null);
|
||||
try {
|
||||
const { data } = await api.put<NotificationPrefs>("/notification-settings", notificationPrefs);
|
||||
setNotificationPrefs(data);
|
||||
toast(t("settingsNotificationsSaved"), "success");
|
||||
} catch (error) {
|
||||
setNotificationError(getApiErrorMessage(error, t("settingsNotificationsSaveFailed")));
|
||||
} finally { setSavingNotifications(false); }
|
||||
const { data } = await api.put<NotificationPrefs>("/notification-settings", submitted);
|
||||
if (!session.mounted || generation !== session.generation) return;
|
||||
setSavedNotificationPrefs(data);
|
||||
setNotificationPrefs(current => current?.emailFollowUpRemindersEnabled === submitted.emailFollowUpRemindersEnabled ? data : current);
|
||||
toast(currentTranslation.current("settingsNotificationsSaved"), "success");
|
||||
} catch (cause) {
|
||||
if (session.mounted && generation === session.generation) setNotificationError({ cause, action: true });
|
||||
} finally {
|
||||
if (generation === session.generation) {
|
||||
session.saving = false;
|
||||
if (session.mounted) setSavingNotifications(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const discardNotifications = () => {
|
||||
if (!savedNotificationPrefs || notificationSession.current.saving) return;
|
||||
setNotificationPrefs(savedNotificationPrefs);
|
||||
setNotificationError(null);
|
||||
};
|
||||
const notificationReadStatus = (notificationError?.cause as { response?: { status?: number } } | undefined)?.response?.status;
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<FormControl fullWidth sx={{ display: { xs: "flex", sm: "none" }, mb: 1 }}>
|
||||
@@ -274,7 +338,7 @@ export default function SettingsView({
|
||||
</TabPanel>
|
||||
|
||||
<TabPanel value={tab} index={1} label={t("settingsTabFollowUps")}>
|
||||
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError} saveError={rulesSaveError} invalid={invalidRules}
|
||||
<RulesSettingsCard draft={rulesDraft} loadError={rulesLoadError ? getApiErrorMessage(rulesLoadError.cause, t("rulesLoadFailed")) : null} saveError={rulesSaveError} invalid={invalidRules}
|
||||
saving={savingRules} dirty={rulesDirty} onSave={() => void saveRules()} onRetry={() => void loadRules()} onDiscard={discardRules}
|
||||
onChange={(field, value) => {
|
||||
setRulesDraft(current => current ? { ...current, [field]: value } : current);
|
||||
@@ -284,15 +348,25 @@ export default function SettingsView({
|
||||
|
||||
<TabPanel value={tab} index={2} label={t("settingsTabNotifications")}>
|
||||
<PageSection surface title={t("settingsNotificationsTitle")} description={t("settingsNotificationsBody")}>
|
||||
{notificationError ? <Alert severity="error" sx={{ mb: 1.5 }}>{notificationError}</Alert> : null}
|
||||
{!notificationPrefs ? <Skeleton variant="rounded" height={70} /> : <Box sx={{ display: "grid", gap: 1 }}>
|
||||
<Box ref={notificationBody} role="group" aria-label={t("settingsNotificationsTitle")} tabIndex={-1} aria-busy={loadingNotifications || savingNotifications} sx={{ minWidth: 0 }}>
|
||||
{!notificationPrefs ? <ViewStateNotice compact loading={loadingNotifications} title={t("settingsNotificationsLoadFailed")} error={notificationError ? {
|
||||
kind: notificationReadStatus === 401 || notificationReadStatus === 403 ? "unauthorized" : "error",
|
||||
message: getApiErrorMessage(notificationError.cause, t("settingsNotificationsLoadFailed")),
|
||||
retryable: notificationReadStatus !== 401 && notificationReadStatus !== 403,
|
||||
} : null} onRetry={retryNotifications} /> : <Box sx={{ display: "grid", gap: 1 }}>
|
||||
{notificationError?.action ? <Alert severity="error" sx={{ mb: 1.5, overflowWrap: "anywhere" }}>{getApiErrorMessage(notificationError.cause, t("settingsNotificationsSaveFailed"))}</Alert> : null}
|
||||
{notificationsDirty ? <Typography role="status" variant="body2" color="text.secondary">{t("assetsUnsavedChanges")}. {t("settingsNotificationsDraftScope")}</Typography> : null}
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={notificationPrefs.emailFollowUpRemindersEnabled} onChange={(e) => setNotificationPrefs({ emailFollowUpRemindersEnabled: e.target.checked })} />}
|
||||
label={t("settingsNotificationsFollowUpReminders")}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">{t("settingsNotificationsEmailBody")}</Typography>
|
||||
<Box><Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? t("settingsSaving") : t("settingsNotificationsSave")}</Button></Box>
|
||||
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 1 }}>
|
||||
<Button disabled={!notificationsDirty || savingNotifications} onClick={discardNotifications}>{t("assetsDiscardChanges")}</Button>
|
||||
<Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? t("settingsSaving") : t("settingsNotificationsSave")}</Button>
|
||||
</Box>
|
||||
</Box>}
|
||||
</Box>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1.5 }}>
|
||||
{t("settingsNotificationsDelivery")}
|
||||
</Typography>
|
||||
|
||||
Reference in New Issue
Block a user