2025-09-25 12:53:46 +08:00
|
|
|
|
import {
|
|
|
|
|
|
createContext,
|
|
|
|
|
|
useContext,
|
|
|
|
|
|
useState,
|
|
|
|
|
|
forwardRef,
|
|
|
|
|
|
useCallback,
|
|
|
|
|
|
useMemo,
|
|
|
|
|
|
} from "react";
|
2023-08-20 23:30:08 +08:00
|
|
|
|
import Snackbar from "@mui/material/Snackbar";
|
|
|
|
|
|
import MuiAlert from "@mui/material/Alert";
|
|
|
|
|
|
|
|
|
|
|
|
const Alert = forwardRef(function Alert(props, ref) {
|
|
|
|
|
|
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
const AlertContext = createContext(null);
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 左下角提示,注入context后,方便全局调用
|
|
|
|
|
|
* @param {*} param0
|
|
|
|
|
|
* @returns
|
|
|
|
|
|
*/
|
|
|
|
|
|
export function AlertProvider({ children }) {
|
|
|
|
|
|
const vertical = "top";
|
|
|
|
|
|
const horizontal = "center";
|
|
|
|
|
|
const [open, setOpen] = useState(false);
|
|
|
|
|
|
const [severity, setSeverity] = useState("info");
|
2025-09-25 12:53:46 +08:00
|
|
|
|
const [message, setMessage] = useState(null);
|
2023-08-20 23:30:08 +08:00
|
|
|
|
|
2025-09-25 12:53:46 +08:00
|
|
|
|
const showAlert = useCallback((msg, type) => {
|
2023-08-20 23:30:08 +08:00
|
|
|
|
setOpen(true);
|
|
|
|
|
|
setMessage(msg);
|
|
|
|
|
|
setSeverity(type);
|
2025-09-25 12:53:46 +08:00
|
|
|
|
}, []);
|
2023-08-20 23:30:08 +08:00
|
|
|
|
|
2025-09-25 12:53:46 +08:00
|
|
|
|
const handleClose = useCallback((_, reason) => {
|
2023-08-20 23:30:08 +08:00
|
|
|
|
if (reason === "clickaway") {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setOpen(false);
|
2025-09-25 12:53:46 +08:00
|
|
|
|
}, []);
|
2023-08-20 23:30:08 +08:00
|
|
|
|
|
2025-09-25 12:53:46 +08:00
|
|
|
|
const value = useMemo(
|
|
|
|
|
|
() => ({
|
|
|
|
|
|
error: (msg) => showAlert(msg, "error"),
|
|
|
|
|
|
warning: (msg) => showAlert(msg, "warning"),
|
|
|
|
|
|
info: (msg) => showAlert(msg, "info"),
|
|
|
|
|
|
success: (msg) => showAlert(msg, "success"),
|
|
|
|
|
|
}),
|
|
|
|
|
|
[showAlert]
|
|
|
|
|
|
);
|
2023-08-30 18:05:37 +08:00
|
|
|
|
|
2023-08-20 23:30:08 +08:00
|
|
|
|
return (
|
2025-09-25 12:53:46 +08:00
|
|
|
|
<AlertContext.Provider value={value}>
|
2023-08-20 23:30:08 +08:00
|
|
|
|
{children}
|
|
|
|
|
|
<Snackbar
|
|
|
|
|
|
open={open}
|
2025-09-25 12:53:46 +08:00
|
|
|
|
autoHideDuration={10000}
|
2023-08-20 23:30:08 +08:00
|
|
|
|
onClose={handleClose}
|
|
|
|
|
|
anchorOrigin={{ vertical, horizontal }}
|
|
|
|
|
|
>
|
|
|
|
|
|
<Alert onClose={handleClose} severity={severity} sx={{ width: "100%" }}>
|
|
|
|
|
|
{message}
|
|
|
|
|
|
</Alert>
|
|
|
|
|
|
</Snackbar>
|
|
|
|
|
|
</AlertContext.Provider>
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export function useAlert() {
|
|
|
|
|
|
return useContext(AlertContext);
|
|
|
|
|
|
}
|