Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+114
@@ -0,0 +1,114 @@
|
||||
// WF-P8 S01 — query-parameter plumbing for the board filter bar.
|
||||
//
|
||||
// Both board routes (`/projects` and `/projects/pipelines/:id`) drive the same
|
||||
// screen, so the mapping "facet option ↔ query parameter" lives here instead of
|
||||
// being copied into each route and drifting.
|
||||
|
||||
import { useSearchParams } from "react-router";
|
||||
import type { BoardFacet, BoardFacetChip } from "@hivegrid/view-models";
|
||||
|
||||
/** Query parameter backing each facet. Mirrors parseBoardFacetParams. */
|
||||
const FACET_PARAM: Record<BoardFacet["key"], string> = {
|
||||
owner: "owner",
|
||||
customerType: "kundentyp",
|
||||
tags: "tags",
|
||||
period: "zeitraum",
|
||||
value: "wert",
|
||||
};
|
||||
|
||||
/** Every facet holds a list of values — the period one unions its ranges. */
|
||||
const MULTI_FACETS: ReadonlySet<BoardFacet["key"]> = new Set(["owner", "customerType", "tags", "period", "value"]);
|
||||
|
||||
/**
|
||||
* Every parameter a filter reset has to drop. `page` is in the list because a
|
||||
* narrowed list can sit on page 4; keeping that after a reset would show an
|
||||
* empty page instead of the unfiltered first one.
|
||||
*/
|
||||
const FILTER_PARAMS = ["q", "onlyMine", "owner", "kundentyp", "tags", "zeitraum", "von", "bis", "wert", "page"] as const;
|
||||
|
||||
function readList(params: URLSearchParams, key: string): string[] {
|
||||
const raw = params.get(key);
|
||||
return raw ? raw.split(",").filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function writeList(next: URLSearchParams, key: string, values: readonly string[]): void {
|
||||
if (values.length > 0) next.set(key, values.join(","));
|
||||
else next.delete(key);
|
||||
}
|
||||
|
||||
export function useBoardFacetParams() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
/**
|
||||
* Any change to the filter changes which rows exist, so the paged list goes
|
||||
* back to page 1 instead of landing on a page the new result no longer has.
|
||||
*/
|
||||
function commit(next: URLSearchParams) {
|
||||
next.delete("page");
|
||||
setSearchParams(next);
|
||||
}
|
||||
|
||||
function setParam(key: string, value: string) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
if (value) next.set(key, value);
|
||||
else next.delete(key);
|
||||
commit(next);
|
||||
}
|
||||
|
||||
function toggleFacet(facet: BoardFacet["key"], value: string) {
|
||||
const key = FACET_PARAM[facet];
|
||||
const next = new URLSearchParams(searchParams);
|
||||
if (MULTI_FACETS.has(facet)) {
|
||||
const current = readList(next, key);
|
||||
writeList(next, key, current.includes(value) ? current.filter((entry) => entry !== value) : [...current, value]);
|
||||
} else {
|
||||
// Single-select: clicking the active option clears it.
|
||||
if (next.get(key) === value) next.delete(key);
|
||||
else next.set(key, value);
|
||||
// The custom bounds belong to the custom option only.
|
||||
if (next.get(key) !== "custom") {
|
||||
next.delete("von");
|
||||
next.delete("bis");
|
||||
}
|
||||
}
|
||||
commit(next);
|
||||
}
|
||||
|
||||
function removeChip(chip: BoardFacetChip) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
if (chip.facet === "onlyMine") next.delete("onlyMine");
|
||||
else if (chip.facet === "q") next.delete("q");
|
||||
else if (MULTI_FACETS.has(chip.facet)) {
|
||||
const key = FACET_PARAM[chip.facet];
|
||||
writeList(
|
||||
next,
|
||||
key,
|
||||
readList(next, key).filter((entry) => entry !== chip.value)
|
||||
);
|
||||
} else {
|
||||
next.delete(FACET_PARAM[chip.facet]);
|
||||
next.delete("von");
|
||||
next.delete("bis");
|
||||
}
|
||||
commit(next);
|
||||
}
|
||||
|
||||
function setPeriodRange(from: string, to: string) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("zeitraum", "custom");
|
||||
if (from) next.set("von", from);
|
||||
else next.delete("von");
|
||||
if (to) next.set("bis", to);
|
||||
else next.delete("bis");
|
||||
commit(next);
|
||||
}
|
||||
|
||||
/** Drop every filter in one navigation — pipeline and demo toggle survive. */
|
||||
function resetFilters() {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
for (const key of FILTER_PARAMS) next.delete(key);
|
||||
commit(next);
|
||||
}
|
||||
|
||||
return { setParam, toggleFacet, removeChip, setPeriodRange, resetFilters };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const custom = vi.fn();
|
||||
vi.mock("sonner", () => ({ toast: { custom: (...args: unknown[]) => custom(...args) } }));
|
||||
vi.mock("react", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react")>();
|
||||
return {
|
||||
...actual,
|
||||
useCallback: <T extends (...args: never[]) => unknown>(callback: T) => callback,
|
||||
useRef: <T,>(value: T) => ({ current: value }),
|
||||
};
|
||||
});
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("~/components/notifications/SaveToast", () => ({
|
||||
SaveToast: () => null,
|
||||
}));
|
||||
|
||||
import { useCopyToast } from "./use-copy-toast";
|
||||
|
||||
function lastToastProps(): { variant: string; title: string; description?: string } {
|
||||
const factory = custom.mock.lastCall?.[0] as () => React.ReactElement;
|
||||
return factory().props as { variant: string; title: string; description?: string };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
custom.mockClear();
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
configurable: true,
|
||||
value: { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } },
|
||||
});
|
||||
});
|
||||
|
||||
describe("useCopyToast", () => {
|
||||
it("reports success only after the clipboard write resolves", async () => {
|
||||
const copyText = useCopyToast();
|
||||
|
||||
expect(await copyText("value")).toBe(true);
|
||||
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("value");
|
||||
expect(lastToastProps()).toMatchObject({
|
||||
variant: "success",
|
||||
title: "shared.copyToast.successTitle",
|
||||
});
|
||||
});
|
||||
|
||||
it("supports a value-specific success headline", async () => {
|
||||
const copyText = useCopyToast();
|
||||
|
||||
await copyText("https://example.test", { successKey: "settings.forms.toast.linkCopied" });
|
||||
|
||||
expect(lastToastProps().title).toBe("settings.forms.toast.linkCopied");
|
||||
});
|
||||
|
||||
it("reports a clipboard failure with a recovery hint", async () => {
|
||||
vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error("denied"));
|
||||
const copyText = useCopyToast();
|
||||
|
||||
expect(await copyText("value")).toBe(false);
|
||||
|
||||
expect(lastToastProps()).toMatchObject({
|
||||
variant: "error",
|
||||
title: "shared.copyToast.errorTitle",
|
||||
description: "shared.copyToast.errorDescription",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { SaveToast } from "~/components/notifications/SaveToast";
|
||||
|
||||
export const COPY_TOAST_DURATION_MS = 4000;
|
||||
|
||||
export type CopyToastOptions = {
|
||||
/** Headline that names the copied value, for example "Form link copied". */
|
||||
readonly successKey?: string;
|
||||
/** Plain-language recovery hint for a failed clipboard write. */
|
||||
readonly errorKey?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies text and reports the browser-confirmed outcome consistently.
|
||||
*
|
||||
* Clipboard writes are one of the few client-only mutations in the product:
|
||||
* there is no route action whose result could drive `useSaveToast`. Keeping
|
||||
* the toast behind the resolved clipboard promise prevents false success.
|
||||
*/
|
||||
export function useCopyToast(): (text: string, options?: CopyToastOptions) => Promise<boolean> {
|
||||
const { t } = useTranslation();
|
||||
const latestTranslation = useRef(t);
|
||||
latestTranslation.current = t;
|
||||
|
||||
return useCallback(async (text: string, options: CopyToastOptions = {}) => {
|
||||
const translate = latestTranslation.current;
|
||||
try {
|
||||
if (!navigator.clipboard?.writeText) throw new Error("Clipboard API unavailable");
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast.custom(() => <SaveToast variant="success" title={translate(options.successKey ?? "shared.copyToast.successTitle")} />, {
|
||||
duration: COPY_TOAST_DURATION_MS,
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
toast.custom(
|
||||
() => (
|
||||
<SaveToast
|
||||
variant="error"
|
||||
title={translate("shared.copyToast.errorTitle")}
|
||||
description={translate(options.errorKey ?? "shared.copyToast.errorDescription")}
|
||||
/>
|
||||
),
|
||||
{ duration: COPY_TOAST_DURATION_MS }
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { useLiveFilter, LIVE_FILTER_DEBOUNCE_MS } from "./use-live-filter";
|
||||
|
||||
describe("useLiveFilter", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("does not apply while draft equals the applied value (mount, loader round-trip)", () => {
|
||||
const apply = vi.fn();
|
||||
renderHook(({ draft, applied }) => useLiveFilter(draft, applied, apply), {
|
||||
initialProps: { draft: "dach", applied: "dach" },
|
||||
});
|
||||
vi.advanceTimersByTime(LIVE_FILTER_DEBOUNCE_MS * 2);
|
||||
expect(apply).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("applies once after the debounce delay when the draft settles", () => {
|
||||
const apply = vi.fn();
|
||||
const { rerender } = renderHook(({ draft, applied }) => useLiveFilter(draft, applied, apply), {
|
||||
initialProps: { draft: "", applied: "" },
|
||||
});
|
||||
rerender({ draft: "d", applied: "" });
|
||||
rerender({ draft: "da", applied: "" });
|
||||
rerender({ draft: "dach", applied: "" });
|
||||
vi.advanceTimersByTime(LIVE_FILTER_DEBOUNCE_MS - 1);
|
||||
expect(apply).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("cancels the pending apply when the draft returns to the applied value", () => {
|
||||
const apply = vi.fn();
|
||||
const { rerender } = renderHook(({ draft, applied }) => useLiveFilter(draft, applied, apply), {
|
||||
initialProps: { draft: "dach", applied: "dach" },
|
||||
});
|
||||
rerender({ draft: "dachx", applied: "dach" });
|
||||
rerender({ draft: "dach", applied: "dach" });
|
||||
vi.advanceTimersByTime(LIVE_FILTER_DEBOUNCE_MS * 2);
|
||||
expect(apply).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the latest apply callback at fire time", () => {
|
||||
const first = vi.fn();
|
||||
const second = vi.fn();
|
||||
const { rerender } = renderHook(({ draft, applied, apply }) => useLiveFilter(draft, applied, apply), {
|
||||
initialProps: { draft: "", applied: "", apply: first },
|
||||
});
|
||||
rerender({ draft: "neu", applied: "", apply: second });
|
||||
vi.advanceTimersByTime(LIVE_FILTER_DEBOUNCE_MS);
|
||||
expect(first).not.toHaveBeenCalled();
|
||||
expect(second).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// Shared debounce effect for live list filters: free-text inputs settle for a
|
||||
// short delay before the filter is applied, while dropdowns/checkboxes apply
|
||||
// immediately via their own change handlers. The applied value is compared so
|
||||
// the effect neither fires on mount nor re-fires after the loader round-trip.
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export const LIVE_FILTER_DEBOUNCE_MS = 400;
|
||||
|
||||
/**
|
||||
* Calls `apply` once `draft` has settled (debounced) and differs from the
|
||||
* currently applied value. Pass normalized values (e.g. trimmed) on both sides
|
||||
* so whitespace-only edits do not trigger a query round-trip.
|
||||
*/
|
||||
export function useLiveFilter(draft: string, applied: string, apply: () => void, delayMs: number = LIVE_FILTER_DEBOUNCE_MS): void {
|
||||
const applyRef = useRef(apply);
|
||||
applyRef.current = apply;
|
||||
|
||||
useEffect(() => {
|
||||
if (draft === applied) return;
|
||||
const timer = window.setTimeout(() => applyRef.current(), delayMs);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [draft, applied, delayMs]);
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
if (typeof window.matchMedia !== "function") {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return;
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
};
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile
|
||||
return !!isMobile;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// useSaveToast unit test. The toast layer is stubbed so the assertions are
|
||||
// about WHEN a toast fires and with which copy, not about sonner's rendering.
|
||||
// i18n is mocked so `t` echoes the key.
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
const custom = vi.fn();
|
||||
const dismiss = vi.fn();
|
||||
vi.mock("sonner", () => ({ toast: { custom: (...args: unknown[]) => custom(...args), dismiss: (...args: unknown[]) => dismiss(...args) } }));
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
// Mirrors i18next: an unknown key falls back to the supplied defaultValue.
|
||||
t: (key: string, options?: { defaultValue?: string; count?: number }) =>
|
||||
key.startsWith("unknown.") ? (options?.defaultValue ?? key) : options?.count === undefined ? key : `${key}:${options.count}`,
|
||||
i18n: { language: "de" },
|
||||
}),
|
||||
}));
|
||||
|
||||
import { SAVE_TOAST_DURATION_MS, useSaveToast, type SaveActionResult, type UseSaveToastOptions } from "./use-save-toast";
|
||||
|
||||
function Harness({ result, options }: { result: SaveActionResult; options?: UseSaveToastOptions }) {
|
||||
useSaveToast(result, options);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Render the toast body sonner was handed, so its copy can be asserted. */
|
||||
function renderLastToast() {
|
||||
const factory = custom.mock.lastCall?.[0] as (id: string) => React.ReactElement;
|
||||
render(factory("toast-1"));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
custom.mockClear();
|
||||
dismiss.mockClear();
|
||||
});
|
||||
|
||||
describe("useSaveToast", () => {
|
||||
it("stays silent while there is no result", () => {
|
||||
render(<Harness result={null} />);
|
||||
expect(custom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays silent for a result the server has not confirmed", () => {
|
||||
// No `ok`, no `error` — a submission that produced data but no verdict must
|
||||
// never read as "Gespeichert".
|
||||
render(<Harness result={{ intent: "save" }} />);
|
||||
expect(custom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a server-confirmed save in green", () => {
|
||||
render(<Harness result={{ intent: "save", ok: true }} />);
|
||||
|
||||
expect(custom).toHaveBeenCalledTimes(1);
|
||||
expect(custom.mock.lastCall?.[1]).toMatchObject({ duration: SAVE_TOAST_DURATION_MS });
|
||||
renderLastToast();
|
||||
expect(document.querySelector("[data-ui-id='ui.saveToast.success']")).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("shared.saveToast.successTitle");
|
||||
});
|
||||
|
||||
it("reports a failure in red and names what went wrong", () => {
|
||||
render(<Harness result={{ intent: "save", error: "projects.error.scheduleConflictOverrideRequired" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.querySelector("[data-ui-id='ui.saveToast.error']")).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("shared.saveToast.errorTitle");
|
||||
expect(document.body.textContent).toContain("projects.error.scheduleConflictOverrideRequired");
|
||||
});
|
||||
|
||||
it("accepts the errorKey alias used by newer action contracts", () => {
|
||||
render(<Harness result={{ intent: "save", errorKey: "projects.error.scheduleConflictOverrideRequired" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.querySelector("[data-ui-id='ui.saveToast.error']")).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("projects.error.scheduleConflictOverrideRequired");
|
||||
});
|
||||
|
||||
it("falls back to plain text rather than printing an untranslated key", () => {
|
||||
render(<Harness result={{ error: "unknown.error.key" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("shared.saveToast.errorFallback");
|
||||
expect(document.body.textContent).not.toContain("unknown.error.key");
|
||||
});
|
||||
|
||||
it("fires once per result, not once per render", () => {
|
||||
const result: SaveActionResult = { intent: "save", ok: true };
|
||||
const view = render(<Harness result={result} />);
|
||||
view.rerender(<Harness result={result} />);
|
||||
view.rerender(<Harness result={result} />);
|
||||
|
||||
expect(custom).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A new submission is a new object, and does report again.
|
||||
view.rerender(<Harness result={{ intent: "save", ok: true }} />);
|
||||
expect(custom).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("ignores results of intents the screen did not opt into", () => {
|
||||
render(<Harness result={{ intent: "search", ok: true }} options={{ intents: ["save"] }} />);
|
||||
expect(custom).not.toHaveBeenCalled();
|
||||
|
||||
render(<Harness result={{ intent: "save", ok: true }} options={{ intents: ["save"] }} />);
|
||||
expect(custom).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("can keep visible successes quiet while still reporting failures", () => {
|
||||
const view = render(
|
||||
<Harness result={{ intent: "mark-read", ok: true }} options={{ reportSuccess: false }} />
|
||||
);
|
||||
expect(custom).not.toHaveBeenCalled();
|
||||
|
||||
view.rerender(
|
||||
<Harness
|
||||
result={{ intent: "mark-read", error: "notifications.errors.deliveryRequired" }}
|
||||
options={{ reportSuccess: false }}
|
||||
/>
|
||||
);
|
||||
expect(custom).toHaveBeenCalledTimes(1);
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("notifications.errors.deliveryRequired");
|
||||
});
|
||||
|
||||
it("takes a screen-specific success headline", () => {
|
||||
render(<Harness result={{ ok: true }} options={{ successKey: "crm.toast.contactSaved" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("crm.toast.contactSaved");
|
||||
});
|
||||
|
||||
it("varies the headline by confirmed intent", () => {
|
||||
render(
|
||||
<Harness
|
||||
result={{ intent: "archive", ok: true }}
|
||||
options={{ successKeyByIntent: { archive: "emails.toast.archived", restore: "emails.toast.restored" } }}
|
||||
/>
|
||||
);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("emails.toast.archived");
|
||||
expect(document.body.textContent).not.toContain("emails.toast.restored");
|
||||
});
|
||||
|
||||
it("passes interpolation values from the server-confirmed result", () => {
|
||||
render(<Harness result={{ ok: true, messageKey: "emails.toast.archived", messageValues: { count: 3 } }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("emails.toast.archived:3");
|
||||
});
|
||||
|
||||
it("lets the action name the confirmation itself", () => {
|
||||
// Several routes already answer with a headline of their own; it has to win
|
||||
// over the screen default, otherwise every save reads "Gespeichert".
|
||||
render(<Harness result={{ ok: true, messageKey: "hr.passwordSafe.feedback.vaultArchived" }} options={{ successKey: "crm.toast.contactSaved" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("hr.passwordSafe.feedback.vaultArchived");
|
||||
expect(document.body.textContent).not.toContain("crm.toast.contactSaved");
|
||||
});
|
||||
|
||||
it("falls back to plain text when a success key is unknown", () => {
|
||||
render(<Harness result={{ ok: true, messageKey: "unknown.toast.key" }} />);
|
||||
|
||||
renderLastToast();
|
||||
expect(document.body.textContent).toContain("shared.saveToast.successTitle");
|
||||
expect(document.body.textContent).not.toContain("unknown.toast.key");
|
||||
});
|
||||
|
||||
it("carries no close button - it removes itself", () => {
|
||||
render(<Harness result={{ ok: true }} />);
|
||||
renderLastToast();
|
||||
|
||||
expect(document.querySelector("[data-ui-id='ui.saveToast.success.dismiss']")).toBeNull();
|
||||
expect(custom.mock.lastCall?.[1]).toMatchObject({ duration: SAVE_TOAST_DURATION_MS });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
// 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]);
|
||||
}
|
||||
Reference in new issue
Block a user