base-notice.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import ReactDOM from "react-dom";
  2. import { ReactNode, useState } from "react";
  3. import { Box, IconButton, Slide, Snackbar, Typography } from "@mui/material";
  4. import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
  5. interface InnerProps {
  6. type: string;
  7. duration?: number;
  8. message: ReactNode;
  9. onClose: () => void;
  10. }
  11. const NoticeInner = (props: InnerProps) => {
  12. const { type, message, duration = 2000, onClose } = props;
  13. const [visible, setVisible] = useState(true);
  14. const onBtnClose = () => {
  15. setVisible(false);
  16. onClose();
  17. };
  18. const onAutoClose = (_e: any, reason: string) => {
  19. if (reason !== "clickaway") onBtnClose();
  20. };
  21. const msgElement =
  22. type === "info" ? (
  23. message
  24. ) : (
  25. <Box sx={{ display: "flex", alignItems: "center" }}>
  26. {type === "error" && <ErrorRounded color="error" />}
  27. {type === "success" && <CheckCircleRounded color="success" />}
  28. <Typography
  29. sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
  30. >
  31. {message}
  32. </Typography>
  33. </Box>
  34. );
  35. return (
  36. <Snackbar
  37. open={visible}
  38. anchorOrigin={{ vertical: "top", horizontal: "right" }}
  39. autoHideDuration={duration}
  40. onClose={onAutoClose}
  41. message={msgElement}
  42. sx={{ maxWidth: 360 }}
  43. TransitionComponent={(p) => <Slide {...p} direction="left" />}
  44. transitionDuration={200}
  45. action={
  46. <IconButton size="small" color="inherit" onClick={onBtnClose}>
  47. <Close fontSize="inherit" />
  48. </IconButton>
  49. }
  50. />
  51. );
  52. };
  53. interface NoticeInstance {
  54. (props: Omit<InnerProps, "onClose">): void;
  55. info(message: ReactNode, duration?: number): void;
  56. error(message: ReactNode, duration?: number): void;
  57. success(message: ReactNode, duration?: number): void;
  58. }
  59. let parent: HTMLDivElement = null!;
  60. // @ts-ignore
  61. const Notice: NoticeInstance = (props) => {
  62. if (!parent) {
  63. parent = document.createElement("div");
  64. document.body.appendChild(parent);
  65. }
  66. const container = document.createElement("div");
  67. parent.appendChild(container);
  68. const onUnmount = () => {
  69. const result = ReactDOM.unmountComponentAtNode(container);
  70. if (result && parent) parent.removeChild(container);
  71. };
  72. ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
  73. };
  74. (["info", "error", "success"] as const).forEach((type) => {
  75. Notice[type] = (message, duration) => Notice({ type, message, duration });
  76. });
  77. export default Notice;