feat(web): Base UI toast region + global mutation feedback wiring (#47)
Add a module-scope Base UI toast manager bridged to the QueryClient so every mutation can give consistent feedback. A MutationCache (extracted into a makeQueryClient() factory for test reuse) emits a catch-all, type-aware error toast (unless meta.suppressErrorToast) and an opt-in success toast (meta.successMessage), reading mutation.meta + i18n.t outside React. meta is type-checked via a react-query Register augmentation. ToastRegion is mounted app-wide in main.tsx. Adds a toast i18n namespace (en/sv parity) and a validated story. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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),
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
Vendored
+14
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type * as React from "react";
|
||||
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { toastManager } from "@/toast/toast-manager";
|
||||
|
||||
function ToastList() {
|
||||
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="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>
|
||||
);
|
||||
}
|
||||
@@ -59,5 +59,14 @@
|
||||
"gateError": "Can't publish — required fields are missing.",
|
||||
"editLink": "Edit the record",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,5 +59,14 @@
|
||||
"gateError": "Kan inte publicera — obligatoriska fält saknas.",
|
||||
"editLink": "Redigera posten",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
+6
-4
@@ -1,21 +1,23 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { App } from "./app";
|
||||
import { ConfigProvider } from "./config/config-provider";
|
||||
import { makeQueryClient } from "./api/query-client";
|
||||
import { ToastRegion } from "./components/ui/toast";
|
||||
import "./index.css";
|
||||
import "./i18n";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
|
||||
});
|
||||
const queryClient = makeQueryClient();
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConfigProvider>
|
||||
<ToastRegion>
|
||||
<App />
|
||||
</ToastRegion>
|
||||
</ConfigProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
|
||||
@@ -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();
|
||||
Reference in New Issue
Block a user