modal.tsx 2.6 KB

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