dialog.tsx 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import {
  2. type ReactNode,
  3. Fragment
  4. } from "react";
  5. import {
  6. type DialogContextType,
  7. type DialogDataType
  8. } from "../types/dialog";
  9. import NCoreContext, {
  10. type ConfigType
  11. } from "ncore-context";
  12. import Dialog from "../components/dialog";
  13. import {
  14. uuid
  15. } from "../utils";
  16. class NCoreUIKitDialog extends NCoreContext<DialogContextType, ConfigType<DialogContextType>> {
  17. constructor({
  18. data = []
  19. }: {
  20. data?: Array<DialogDataType>
  21. }) {
  22. super({
  23. close: () => {},
  24. open: () => "",
  25. data: data
  26. }, {
  27. key: "NCoreUIKit-DialogContext"
  28. });
  29. };
  30. open = (dialogData: DialogDataType) => {
  31. const currentData = this.state.data;
  32. const dialogID = dialogData.id ? dialogData.id : uuid();
  33. currentData.push({
  34. ...dialogData,
  35. id: dialogID
  36. });
  37. this.setState({
  38. data: currentData
  39. });
  40. return dialogID;
  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((dialog) => dialog.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: DialogDataType) => {
  80. return <Dialog
  81. key={`NCoreUIKit-Dialog-${item.id}`}
  82. id={item.id as string}
  83. onClosed={() => {
  84. if(item.onClosed) {
  85. item.onClosed({
  86. id: item.id as string
  87. });
  88. }
  89. if(item.isAutoClosed === undefined || item.isAutoClosed === true) {
  90. this.close({
  91. id: item.id
  92. });
  93. }
  94. }}
  95. {...item}
  96. />;
  97. })}
  98. </Fragment>;
  99. };
  100. }
  101. export default NCoreUIKitDialog;