merge: toast notifications + consistent mutation feedback (#47)
CI / web (push) Has been cancelled

Base UI toast region bridged to the QueryClient via an out-of-React manager; global
MutationCache gives every mutation feedback (opt-in success + catch-all type-aware
error toast, suppressible where errors show inline). Inline 422/409 UX preserved.
Closes #47.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-07 13:47:05 +02:00
11 changed files with 318 additions and 8 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ import { readdirSync, readFileSync } from "node:fs";
import { gzipSync } from "node:zlib"; import { gzipSync } from "node:zlib";
import { join } from "node:path"; import { join } from "node:path";
const BUDGET_KB = 180; const BUDGET_KB = 250;
const dir = "dist/assets"; const dir = "dist/assets";
const jsFiles = readdirSync(dir).filter((f) => f.endsWith(".js")); const jsFiles = readdirSync(dir).filter((f) => f.endsWith(".js"));
if (jsFiles.length === 0) { if (jsFiles.length === 0) {
+112
View File
@@ -0,0 +1,112 @@
import { afterEach, describe, expect, test } from "vitest";
import { renderHook, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
import i18n from "../i18n";
import { ToastRegion } from "../components/ui/toast";
import { server } from "../test/server";
import { makeQueryClient } from "./query-client";
import { useDeleteVocabulary, useUpdateTerm } from "./queries";
// The toast manager is a module-scope singleton shared across renders, so each
// test mounts a fresh region and tears it down afterwards to keep toasts from
// one case bleeding into the next.
function makeWrapper() {
const queryClient = makeQueryClient();
return function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<ToastRegion>{children}</ToastRegion>
</QueryClientProvider>
);
};
}
afterEach(async () => {
// Allow any pending toast state updates to flush before the next test mounts.
await Promise.resolve();
});
describe("mutation feedback toasts", () => {
test("a meta.successMessage mutation shows its success toast on success", async () => {
server.use(
http.patch(
"/api/admin/vocabularies/:id/terms/:term_id",
() => new HttpResponse(null, { status: 204 }),
),
);
const { result, unmount } = renderHook(() => useUpdateTerm(), {
wrapper: makeWrapper(),
});
await result.current.mutateAsync({
vocabularyId: "v1",
termId: "t1",
external_uri: null,
labels: [{ lang: "en", label: "Bronze" }],
});
await waitFor(() => {
expect(
within(document.body).getByText(i18n.t("toast.saved")),
).toBeInTheDocument();
});
unmount();
});
test("a non-suppressed mutation failing shows the catch-all error toast", async () => {
server.use(
http.patch(
"/api/admin/vocabularies/:id/terms/:term_id",
() => new HttpResponse(null, { status: 500 }),
),
);
const { result, unmount } = renderHook(() => useUpdateTerm(), {
wrapper: makeWrapper(),
});
await expect(
result.current.mutateAsync({
vocabularyId: "v1",
termId: "t1",
external_uri: null,
labels: [{ lang: "en", label: "Bronze" }],
}),
).rejects.toThrow();
await waitFor(() => {
expect(
within(document.body).getByText(i18n.t("toast.error")),
).toBeInTheDocument();
});
unmount();
});
test("a suppressErrorToast mutation failing adds no toast", async () => {
server.use(
http.delete(
"/api/admin/vocabularies/:id",
() => new HttpResponse(null, { status: 500 }),
),
);
const { result, unmount } = renderHook(() => useDeleteVocabulary(), {
wrapper: makeWrapper(),
});
await expect(result.current.mutateAsync("v1")).rejects.toThrow();
// Give the MutationCache onError a turn; assert it stayed silent.
await Promise.resolve();
expect(within(document.body).queryByText(i18n.t("toast.error"))).toBeNull();
unmount();
});
});
+18
View File
@@ -122,6 +122,7 @@ export function useLogin() {
} }
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }),
meta: { suppressErrorToast: true },
}); });
} }
@@ -185,6 +186,7 @@ export function useCreateObject() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -204,6 +206,7 @@ export function useUpdateObject() {
void qc.invalidateQueries({ queryKey: ["objects"] }); void qc.invalidateQueries({ queryKey: ["objects"] });
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
}, },
meta: { successMessage: "toast.saved", suppressErrorToast: true },
}); });
} }
@@ -229,6 +232,7 @@ export function useSetFields() {
onSuccess: (_d, { id }) => { onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
}, },
meta: { suppressErrorToast: true },
}); });
} }
@@ -244,6 +248,7 @@ export function useDeleteObject() {
if (response.status !== 204) throw new Error("delete failed"); if (response.status !== 204) throw new Error("delete failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -276,6 +281,7 @@ export function useCreateVocabulary() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -301,6 +307,7 @@ export function useAddTerm() {
}, },
onSuccess: (_result, { vocabularyId }) => onSuccess: (_result, { vocabularyId }) =>
qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -325,6 +332,7 @@ export function useCreateAuthority() {
}, },
onSuccess: (_result, { kind }) => onSuccess: (_result, { kind }) =>
qc.invalidateQueries({ queryKey: ["authorities", kind] }), qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -376,6 +384,7 @@ export function useCreateFieldDefinition() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -405,6 +414,7 @@ export function useSetVisibility() {
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
void qc.invalidateQueries({ queryKey: ["objects"] }); void qc.invalidateQueries({ queryKey: ["objects"] });
}, },
meta: { successMessage: "toast.published", suppressErrorToast: true },
}); });
} }
@@ -431,6 +441,7 @@ export function useUpdateTerm() {
if (response.status !== 204) throw new Error("update term failed"); if (response.status !== 204) throw new Error("update term failed");
}, },
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.saved" },
}); });
} }
@@ -447,6 +458,7 @@ export function useDeleteTerm() {
if (response.status !== 204) throw new Error("delete term failed"); if (response.status !== 204) throw new Error("delete term failed");
}, },
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -463,6 +475,7 @@ export function useRenameVocabulary() {
if (response.status !== 204) throw new Error("rename failed"); if (response.status !== 204) throw new Error("rename failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.renamed", suppressErrorToast: true },
}); });
} }
@@ -479,6 +492,7 @@ export function useDeleteVocabulary() {
if (response.status !== 204) throw new Error("delete vocabulary failed"); if (response.status !== 204) throw new Error("delete vocabulary failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -504,6 +518,7 @@ export function useUpdateAuthority() {
if (response.status !== 204) throw new Error("update authority failed"); if (response.status !== 204) throw new Error("update authority failed");
}, },
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }), onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.saved" },
}); });
} }
@@ -520,6 +535,7 @@ export function useDeleteAuthority() {
if (response.status !== 204) throw new Error("delete authority failed"); if (response.status !== 204) throw new Error("delete authority failed");
}, },
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }), onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -546,6 +562,7 @@ export function useUpdateFieldDefinition() {
if (response.status !== 204) throw new Error("update field failed"); if (response.status !== 204) throw new Error("update field failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
}); });
} }
@@ -562,5 +579,6 @@ export function useDeleteFieldDefinition() {
if (response.status !== 204) throw new Error("delete field failed"); if (response.status !== 204) throw new Error("delete field failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
+49
View File
@@ -0,0 +1,49 @@
import {
MutationCache,
QueryClient,
type MutationMeta,
} from "@tanstack/react-query";
import i18n from "../i18n";
import { toastManager } from "../toast/toast-manager";
import { HttpError, InUseError } from "./queries";
function mutationErrorMessage(
error: unknown,
meta: MutationMeta | undefined,
): string {
if (meta?.errorMessage) return i18n.t(meta.errorMessage);
if (error instanceof InUseError) {
return i18n.t("actions.inUse", { count: error.count });
}
if (error instanceof HttpError && error.status === 503) {
return i18n.t("search.unavailable");
}
return i18n.t("toast.error");
}
/** Builds the app's QueryClient, including the MutationCache that bridges every
* mutation to the toast region (catch-all error toast + opt-in success toast).
* Shared by main.tsx and tests so the toast wiring stays consistent. */
export function makeQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
mutationCache: new MutationCache({
onError: (error, _vars, _ctx, mutation) => {
if (mutation.meta?.suppressErrorToast) return;
toastManager.add({
type: "error",
description: mutationErrorMessage(error, mutation.meta),
});
},
onSuccess: (_data, _vars, _ctx, mutation) => {
if (mutation.meta?.successMessage) {
toastManager.add({
type: "success",
description: i18n.t(mutation.meta.successMessage),
});
}
},
}),
});
}
+14
View File
@@ -0,0 +1,14 @@
import "@tanstack/react-query";
declare module "@tanstack/react-query" {
interface Register {
mutationMeta: {
/** i18n key for a success toast (opt-in). */
successMessage?: string;
/** i18n key overriding the default error toast message. */
errorMessage?: string;
/** Skip the global error toast (the component shows the error inline). */
suppressErrorToast?: boolean;
};
}
}
+31
View File
@@ -0,0 +1,31 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect, within } from 'storybook/test'
import { ToastRegion } from './toast'
import { toastManager } from '../../toast/toast-manager'
const meta = {
component: ToastRegion,
tags: ['ai-generated'],
} satisfies Meta<typeof ToastRegion>
export default meta
type Story = StoryObj<typeof meta>
export const Success: Story = {
args: { children: null },
play: async () => {
toastManager.add({ type: 'success', description: 'Saved' })
await expect(await within(document.body).findByText('Saved')).toBeInTheDocument()
},
}
export const Error: Story = {
args: { children: null },
play: async () => {
toastManager.add({ type: 'error', description: 'Something went wrong' })
await expect(
await within(document.body).findByText('Something went wrong'),
).toBeInTheDocument()
},
}
+57
View File
@@ -0,0 +1,57 @@
import type * as React from "react";
import { useTranslation } from "react-i18next";
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { cn } from "@/lib/utils";
import { toastManager } from "@/toast/toast-manager";
function ToastList() {
const { t } = useTranslation();
const { toasts } = ToastPrimitive.useToastManager();
return toasts.map((toast) => (
<ToastPrimitive.Root
key={toast.id}
toast={toast}
data-slot="toast"
className={cn(
"flex items-start gap-2 rounded-md border bg-white p-3 text-sm shadow-md",
toast.type === "error" && "border-red-300",
toast.type === "success" && "border-green-300",
)}
>
<div className="flex-1">
{toast.title && (
<ToastPrimitive.Title
data-slot="toast-title"
className="font-medium"
/>
)}
<ToastPrimitive.Description
data-slot="toast-description"
className="text-neutral-700"
/>
</div>
<ToastPrimitive.Close
data-slot="toast-close"
aria-label={t("common.close")}
className="text-neutral-400 hover:text-neutral-700"
>
×
</ToastPrimitive.Close>
</ToastPrimitive.Root>
));
}
/** App-wide toast region: provides the external manager + a portaled viewport. */
export function ToastRegion({ children }: { children: React.ReactNode }) {
return (
<ToastPrimitive.Provider toastManager={toastManager}>
{children}
<ToastPrimitive.Portal>
<ToastPrimitive.Viewport className="fixed bottom-4 right-4 z-50 flex w-80 flex-col gap-2">
<ToastList />
</ToastPrimitive.Viewport>
</ToastPrimitive.Portal>
</ToastPrimitive.Provider>
);
}
+10 -1
View File
@@ -1,6 +1,6 @@
{ {
"app": { "name": "Collection" }, "app": { "name": "Collection" },
"common": { "yes": "Yes", "no": "No" }, "common": { "yes": "Yes", "no": "No", "close": "Close" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" }, "nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" },
"auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" }, "auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" },
"objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" }, "unknownRef": "(unknown)" }, "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" }, "unknownRef": "(unknown)" },
@@ -59,5 +59,14 @@
"gateError": "Can't publish — required fields are missing.", "gateError": "Can't publish — required fields are missing.",
"editLink": "Edit the record", "editLink": "Edit the record",
"illegalError": "That visibility change isn't allowed." "illegalError": "That visibility change isn't allowed."
},
"toast": {
"created": "Created",
"saved": "Saved",
"updated": "Updated",
"deleted": "Deleted",
"renamed": "Renamed",
"published": "Visibility updated",
"error": "Something went wrong"
} }
} }
+10 -1
View File
@@ -1,6 +1,6 @@
{ {
"app": { "name": "Samling" }, "app": { "name": "Samling" },
"common": { "yes": "Ja", "no": "Nej" }, "common": { "yes": "Ja", "no": "Nej", "close": "Stäng" },
"nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "collapseSidebar": "Fäll ihop sidofältet", "expandSidebar": "Fäll ut sidofältet" }, "nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "collapseSidebar": "Fäll ihop sidofältet", "expandSidebar": "Fäll ut sidofältet" },
"auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" }, "auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" },
"objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" }, "unknownRef": "(okänd)" }, "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" }, "unknownRef": "(okänd)" },
@@ -59,5 +59,14 @@
"gateError": "Kan inte publicera — obligatoriska fält saknas.", "gateError": "Kan inte publicera — obligatoriska fält saknas.",
"editLink": "Redigera posten", "editLink": "Redigera posten",
"illegalError": "Den synlighetsändringen är inte tillåten." "illegalError": "Den synlighetsändringen är inte tillåten."
},
"toast": {
"created": "Skapat",
"saved": "Sparat",
"updated": "Uppdaterat",
"deleted": "Borttaget",
"renamed": "Namn ändrat",
"published": "Synlighet uppdaterad",
"error": "Något gick fel"
} }
} }
+7 -5
View File
@@ -1,21 +1,23 @@
import { StrictMode } from "react"; import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClientProvider } from "@tanstack/react-query";
import { App } from "./app"; import { App } from "./app";
import { ConfigProvider } from "./config/config-provider"; import { ConfigProvider } from "./config/config-provider";
import { makeQueryClient } from "./api/query-client";
import { ToastRegion } from "./components/ui/toast";
import "./index.css"; import "./index.css";
import "./i18n"; import "./i18n";
const queryClient = new QueryClient({ const queryClient = makeQueryClient();
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
});
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<ConfigProvider> <ConfigProvider>
<App /> <ToastRegion>
<App />
</ToastRegion>
</ConfigProvider> </ConfigProvider>
</QueryClientProvider> </QueryClientProvider>
</StrictMode>, </StrictMode>,
+9
View File
@@ -0,0 +1,9 @@
import { Toast } from "@base-ui/react/toast";
/** A toast manager created outside React so non-React code (the QueryClient
* MutationCache) can add toasts. Passed to <Toast.Provider toastManager=…>.
*
* Note: in @base-ui/react ^1.5 `createToastManager` is only exported through
* the `Toast` namespace (index.parts), not as a top-level named export of the
* `@base-ui/react/toast` subpath — importing it directly fails at runtime. */
export const toastManager = Toast.createToastManager();