2024-05-04 09:11:30 +02:00

45 lines
1013 B
TypeScript

import {
Toast,
ToastBody,
ToastTitle,
Toaster,
useId,
useToastController,
} from "@fluentui/react-components";
import React, { PropsWithChildren } from "react";
type ToastContext = (
title: string,
body: string,
intent?: "error" | "info" | "success" | "warning"
) => void;
const ToastContextK = React.createContext<ToastContext | null>(null);
export function ToastProvider(p: PropsWithChildren): React.ReactElement {
const toasterId = useId("toaster");
const { dispatchToast } = useToastController(toasterId);
const hook: ToastContext = (title, body, intent) => {
dispatchToast(
<Toast>
<ToastTitle>{title}</ToastTitle>
<ToastBody>{body}</ToastBody>
</Toast>,
{ intent: intent ?? "info" }
);
};
return (
<>
<ToastContextK.Provider value={hook}>{p.children}</ToastContextK.Provider>
<Toaster toasterId={toasterId} />
</>
);
}
export function useToast(): ToastContext {
return React.useContext(ToastContextK)!;
}