toast.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import {
  2. type ReactNode,
  3. Fragment
  4. } from "react";
  5. import {
  6. type ToastContextType,
  7. type ToastDataType
  8. } from "../types/toast";
  9. import NCoreContext, {
  10. type ConfigType
  11. } from "ncore-context";
  12. import Toast from "../components/toast";
  13. import {
  14. uuid
  15. } from "../utils";
  16. class NCoreUIKitToast extends NCoreContext<ToastContextType, ConfigType<ToastContextType>> {
  17. constructor({
  18. data = []
  19. }: {
  20. data?: Array<ToastDataType>
  21. }) {
  22. super({
  23. close: () => {},
  24. open: () => "",
  25. data: data
  26. }, {
  27. key: "NCoreUIKit-ToastContext"
  28. });
  29. };
  30. open = (toastData: ToastDataType) => {
  31. const currentData = this.state.data;
  32. const toastID = toastData.id ? toastData.id : uuid();
  33. currentData.push({
  34. ...toastData,
  35. id: toastID
  36. });
  37. this.setState({
  38. data: currentData
  39. });
  40. return toastID;
  41. };
  42. close = (props?: {
  43. index?: number;
  44. id?: string;
  45. }) => {
  46. const currentData = this.state.data;
  47. if (props && props.id) {
  48. const keyIndex = currentData.findIndex((toast) => toast.id === props.id);
  49. if (keyIndex !== -1) {
  50. currentData.splice(keyIndex, 1);
  51. this.setState({
  52. data: currentData
  53. });
  54. }
  55. return;
  56. }
  57. if (props && props.index !== undefined) {
  58. currentData.splice(props.index, 1);
  59. this.setState({
  60. data: currentData
  61. });
  62. return;
  63. }
  64. currentData.pop();
  65. this.setState({
  66. data: currentData
  67. });
  68. };
  69. Render = ({
  70. children
  71. }: {
  72. children: ReactNode;
  73. }) => {
  74. const {
  75. data
  76. } = this.useContext();
  77. return <Fragment>
  78. {children}
  79. {data.map((item: ToastDataType) => {
  80. return <Toast
  81. key={`NCoreUIKit-Toast-${item.id}`}
  82. {...item}
  83. id={item.id as string}
  84. onClosed={(props) => {
  85. this.close({
  86. id: item.id
  87. });
  88. if(item.onClosed) item.onClosed(props);
  89. }}
  90. />;
  91. })}
  92. </Fragment>;
  93. };
  94. }
  95. export default NCoreUIKitToast;