Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/hooks/use-save-toast.tsx
T

158 lines
5.7 KiB
TypeScript

// Turns a route's action result into the save confirmation at the top of the
// screen. One hook call per screen, so every list and detail page reports a
// save the same way.
//
// The contract is the action result shape the routes already return:
// { intent?: string; ok?: true; error?: string }
// `error` is an i18n key (never a raw message), which is what keeps the toast
// inside the Klartext rule (A.1) instead of printing a provider string.
//
// Success is only ever reported for `ok === true` — the server's own answer.
// A pending or failed write cannot produce a green toast.
import { useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router";
import { toast } from "sonner";
import { SaveToast } from "~/components/notifications/SaveToast";
/** How long a toast stays before it removes itself. */
export const SAVE_TOAST_DURATION_MS = 4000;
export type ToastMessageValues = Readonly<Record<string, string | number>>;
export type SaveActionResult = {
readonly intent?: string | null;
readonly ok?: boolean;
/**
* i18n key of a headline the action picked itself ("Tresor archiviert").
* Several routes already answer with one; it wins over the screen's default
* so the confirmation names what actually ran.
*/
readonly messageKey?: string | null;
/** Interpolation values for the success headline, e.g. a bulk-action count. */
readonly messageValues?: ToastMessageValues | null;
/** i18n key describing what went wrong. */
readonly error?: string | null;
/** Alias used by newer action contracts. */
readonly errorKey?: string | null;
/** Interpolation values for the error detail. */
readonly errorValues?: ToastMessageValues | null;
} | null | undefined;
export type UseSaveToastOptions = {
/**
* i18n key of the success headline. Defaults to the shared "Gespeichert",
* which is what almost every screen wants.
*/
readonly successKey?: string;
/** Intent-specific success headlines for actions that only return an intent. */
readonly successKeyByIntent?: Readonly<Record<string, string>>;
/** Optional detail line under the success headline. */
readonly successDescriptionKey?: string;
/**
* Keep successful, immediately visible UI changes quiet while still
* reporting action errors. Defaults to true.
*/
readonly reportSuccess?: boolean;
/**
* Only report results of these intents. A screen whose action serves several
* purposes (save, search, export) would otherwise toast for all of them.
* Omit to report every result.
*/
readonly intents?: readonly string[];
};
/**
* Fires exactly once per action result. React Router hands back the same
* object identity until the next submission, so comparing the reference is
* what keeps a re-render from toasting again.
*/
export function useSaveToast(result: SaveActionResult, options: UseSaveToastOptions = {}): void {
const { t } = useTranslation();
const lastReported = useRef<SaveActionResult>(undefined);
// The latest copy is read inside the effect, so changing options between
// renders never re-fires a toast that was already shown.
const latest = useRef({ t, options });
latest.current = { t, options };
useEffect(() => {
if (!result) return;
if (lastReported.current === result) return;
lastReported.current = result;
const { t: translate, options: current } = latest.current;
if (current.intents && !current.intents.includes(result.intent ?? "")) return;
const errorKey = result.error ?? result.errorKey;
if (errorKey) {
// A key with no translation would print the key itself, which is exactly
// the cryptic output the Klartext rule forbids — fall back to plain text.
const detail = translate(errorKey, {
...result.errorValues,
defaultValue: translate("shared.saveToast.errorFallback"),
});
toast.custom(
() => (
<SaveToast
variant="error"
title={translate("shared.saveToast.errorTitle")}
description={detail}
/>
),
{ duration: SAVE_TOAST_DURATION_MS }
);
return;
}
if (result.ok !== true || current.reportSuccess === false) return;
const intentKey = result.intent ? current.successKeyByIntent?.[result.intent] : undefined;
const titleKey = result.messageKey || intentKey || current.successKey || "shared.saveToast.successTitle";
const title = translate(titleKey, {
...result.messageValues,
defaultValue: translate("shared.saveToast.successTitle"),
});
toast.custom(
() => (
<SaveToast
variant="success"
title={title}
description={current.successDescriptionKey ? translate(current.successDescriptionKey) : null}
/>
),
{ duration: SAVE_TOAST_DURATION_MS }
);
}, [result]);
}
/**
* Reports a successful mutation that completed with a redirect.
*
* Routes opt in by appending `?toast=<i18n-key>` to their redirect target.
* The parameter is removed immediately after it has been consumed so reloads,
* copied links and browser history do not repeat stale confirmations.
*/
export function useRedirectToast(): void {
const location = useLocation();
const messageKey = new URLSearchParams(location.search).get("toast");
const result = useMemo(
() => (messageKey ? { ok: true as const, messageKey } : undefined),
[messageKey]
);
useSaveToast(result);
useEffect(() => {
if (!messageKey) return;
const url = new URL(window.location.href);
url.searchParams.delete("toast");
window.history.replaceState(
window.history.state,
"",
`${url.pathname}${url.search}${url.hash}`
);
}, [messageKey]);
}